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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.140.  .2(raebu    4:21): # $Id: lonnet.pm,v 1.1172.2.140.2.1 2021/03/08 14:48:41 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.807     albertel   98: use LONCAPA qw(:DEFAULT :match);
1.740     www        99: use LONCAPA::Configuration;
1.1160    www       100: use LONCAPA::lonmetadata;
1.1172.2.22  raeburn   101: use LONCAPA::Lond;
1.1172.2.110  raeburn   102: use LONCAPA::transliterate;
1.1117    foxr      103: 
1.1090    raeburn   104: use File::Copy;
1.676     albertel  105: 
1.195     www       106: my $readit;
1.1172.2.79  raeburn   107: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  108: 
1.619     albertel  109: require Exporter;
                    110: 
                    111: our @ISA = qw (Exporter);
                    112: our @EXPORT = qw(%env);
                    113: 
1.1172.2.9  raeburn   114: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       115: {
                    116:     my $logid;
1.1172.2.9  raeburn   117:     sub write_log {
                    118: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    119:         if ($context eq 'course') {
                    120:             if (($cnum eq '') || ($cdom eq '')) {
                    121:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    122:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    123:             }
1.957     raeburn   124:         }
1.1172.2.13  raeburn   125: 	$logid ++;
1.957     raeburn   126:         my $now = time();
                    127: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.134  raeburn   128:         my $ip = &get_requestor_ip();  
1.1172.2.9  raeburn   129:         my $logentry = {
                    130:                          $id => {
                    131:                                   'exe_uname' => $env{'user.name'},
                    132:                                   'exe_udom'  => $env{'user.domain'},
                    133:                                   'exe_time'  => $now,
1.1172.2.134  raeburn   134:                                   'exe_ip'    => $ip,
1.1172.2.9  raeburn   135:                                   'delflag'   => $delflag,
                    136:                                   'logentry'  => $storehash,
                    137:                                   'uname'     => $uname,
                    138:                                   'udom'      => $udom,
                    139:                                 }
                    140:                        };
                    141:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       142:     }
                    143: }
1.1       albertel  144: 
1.163     harris41  145: sub logtouch {
                    146:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  147:     unless (-e "$execdir/logs/lonnet.log") {	
1.1172.2.96  raeburn   148: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  149: 	close $fh;
                    150:     }
                    151:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    152:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    153: }
                    154: 
1.1       albertel  155: sub logthis {
                    156:     my $message=shift;
                    157:     my $execdir=$perlvar{'lonDaemons'};
                    158:     my $now=time;
                    159:     my $local=localtime($now);
1.1172.2.96  raeburn   160:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      161: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    162: 	print $fh $logstring;
1.448     albertel  163: 	close($fh);
                    164:     }
1.1       albertel  165:     return 1;
                    166: }
                    167: 
                    168: sub logperm {
                    169:     my $message=shift;
                    170:     my $execdir=$perlvar{'lonDaemons'};
                    171:     my $now=time;
                    172:     my $local=localtime($now);
1.1172.2.96  raeburn   173:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  174: 	print $fh "$now:$message:$local\n";
                    175: 	close($fh);
                    176:     }
1.1       albertel  177:     return 1;
                    178: }
                    179: 
1.850     albertel  180: sub create_connection {
1.853     albertel  181:     my ($hostname,$lonid) = @_;
1.851     albertel  182:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  183: 				     Type    => SOCK_STREAM,
                    184: 				     Timeout => 10);
                    185:     return 0 if (!$client);
1.890     albertel  186:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  187:     my $result = <$client>;
                    188:     chomp($result);
                    189:     return 1 if ($result eq 'done');
                    190:     return 0;
                    191: }
                    192: 
1.983     raeburn   193: sub get_server_timezone {
                    194:     my ($cnum,$cdom) = @_;
                    195:     my $home=&homeserver($cnum,$cdom);
                    196:     if ($home ne 'no_host') {
                    197:         my $cachetime = 24*3600;
                    198:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    199:         if (defined($cached)) {
                    200:             return $timezone;
                    201:         } else {
                    202:             my $timezone = &reply('servertimezone',$home);
                    203:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    204:         }
                    205:     }
                    206: }
1.850     albertel  207: 
1.1106    raeburn   208: sub get_server_distarch {
                    209:     my ($lonhost,$ignore_cache) = @_;
                    210:     if (defined($lonhost)) {
                    211:         if (!defined(&hostname($lonhost))) {
                    212:             return;
                    213:         }
                    214:         my $cachetime = 12*3600;
                    215:         if (!$ignore_cache) {
                    216:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    217:             if (defined($cached)) {
                    218:                 return $distarch;
                    219:             }
                    220:         }
                    221:         my $rep = &reply('serverdistarch',$lonhost);
                    222:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    223:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    224:                 $rep eq '') {
                    225:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    226:         }
                    227:     }
                    228:     return;
                    229: }
                    230: 
1.993     raeburn   231: sub get_server_loncaparev {
1.1073    raeburn   232:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   233:     if (defined($lonhost)) {
                    234:         if (!defined(&hostname($lonhost))) {
                    235:             undef($lonhost);
                    236:         }
                    237:     }
                    238:     if (!defined($lonhost)) {
                    239:         if (defined(&domain($dom,'primary'))) {
                    240:             $lonhost=&domain($dom,'primary');
                    241:             if ($lonhost eq 'no_host') {
                    242:                 undef($lonhost);
                    243:             }
                    244:         }
                    245:     }
                    246:     if (defined($lonhost)) {
1.1073    raeburn   247:         my $cachetime = 12*3600;
                    248:         if (!$ignore_cache) {
                    249:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    250:             if (defined($cached)) {
                    251:                 return $loncaparev;
                    252:             }
                    253:         }
                    254:         my ($answer,$loncaparev);
                    255:         my @ids=&current_machine_ids();
                    256:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    257:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   258:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   259:                 $loncaparev = $1;
                    260:             }
                    261:         } else {
                    262:             $answer = &reply('serverloncaparev',$lonhost);
                    263:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    264:                 if ($caller eq 'loncron') {
                    265:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   266:                     $ua->timeout(4);
1.1172.2.120  raeburn   267:                     my $hostname = &hostname($lonhost);
1.1073    raeburn   268:                     my $protocol = $protocol{$lonhost};
                    269:                     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn   270:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073    raeburn   271:                     my $request=new HTTP::Request('GET',$url);
                    272:                     my $response=$ua->request($request);
                    273:                     unless ($response->is_error()) {
                    274:                         my $content = $response->content;
1.1081    raeburn   275:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   276:                             $loncaparev = $1;
                    277:                         }
                    278:                     }
                    279:                 } else {
                    280:                     $loncaparev = $loncaparevs{$lonhost};
                    281:                 }
1.1081    raeburn   282:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   283:                 $loncaparev = $1;
                    284:             }
1.993     raeburn   285:         }
1.1073    raeburn   286:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   287:     }
                    288: }
                    289: 
1.1074    raeburn   290: sub get_server_homeID {
                    291:     my ($hostname,$ignore_cache,$caller) = @_;
                    292:     unless ($ignore_cache) {
                    293:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    294:         if (defined($cached)) {
                    295:             return $serverhomeID;
                    296:         }
                    297:     }
                    298:     my $cachetime = 12*3600;
                    299:     my $serverhomeID;
                    300:     if ($caller eq 'loncron') { 
                    301:         my @machine_ids = &machine_ids($hostname);
                    302:         foreach my $id (@machine_ids) {
                    303:             my $response = &reply('serverhomeID',$id);
                    304:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    305:                 $serverhomeID = $response;
                    306:                 last;
                    307:             }
                    308:         }
                    309:         if ($serverhomeID eq '') {
                    310:             $serverhomeID = $machine_ids[-1];
                    311:         }
                    312:     } else {
                    313:         $serverhomeID = $serverhomeIDs{$hostname};
                    314:     }
                    315:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    316: }
                    317: 
1.1121    raeburn   318: sub get_remote_globals {
                    319:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   320:     my ($result,%returnhash,%whatneeded);
                    321:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   322:         foreach my $what (sort(keys(%{$whathash}))) {
                    323:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   324:             my ($response,$cached);
1.1121    raeburn   325:             unless ($ignore_cache) {
1.1125    raeburn   326:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   327:             }
                    328:             if (defined($cached)) {
1.1125    raeburn   329:                 $returnhash{$what} = $response;
1.1121    raeburn   330:             } else {
1.1125    raeburn   331:                 $whatneeded{$what} = 1;
1.1121    raeburn   332:             }
                    333:         }
1.1125    raeburn   334:         if (keys(%whatneeded) == 0) {
                    335:             $result = 'ok';
                    336:         } else {
1.1121    raeburn   337:             my $requested = &freeze_escape(\%whatneeded);
                    338:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   339:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    340:                 ($rep eq 'unknown_cmd')) {
                    341:                 $result = $rep;
                    342:             } else {
                    343:                 $result = 'ok';
1.1121    raeburn   344:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   345:                 foreach my $item (@pairs) {
                    346:                     my ($key,$value)=split(/=/,$item,2);
                    347:                     my $what = &unescape($key);
                    348:                     my $hashid = $lonhost.'-'.$what;
                    349:                     $returnhash{$what}=&thaw_unescape($value);
                    350:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   351:                 }
                    352:             }
                    353:         }
                    354:     }
1.1125    raeburn   355:     return ($result,\%returnhash);
1.1121    raeburn   356: }
                    357: 
1.1124    raeburn   358: sub remote_devalidate_cache {
1.1172.2.35  raeburn   359:     my ($lonhost,$cachekeys) = @_;
                    360:     my $items;
                    361:     return unless (ref($cachekeys) eq 'ARRAY');
                    362:     my $cachestr = join('&',@{$cachekeys});
                    363:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   364: }
                    365: 
1.1       albertel  366: # -------------------------------------------------- Non-critical communication
                    367: sub subreply {
                    368:     my ($cmd,$server)=@_;
1.838     albertel  369:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      370:     #
                    371:     #  With loncnew process trimming, there's a timing hole between lonc server
                    372:     #  process exit and the master server picking up the listen on the AF_UNIX
                    373:     #  socket.  In that time interval, a lock file will exist:
                    374: 
                    375:     my $lockfile=$peerfile.".lock";
                    376:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1172.2.79  raeburn   377: 	sleep(0.1);
1.549     foxr      378:     }
                    379:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      380:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      381:     #
1.550     foxr      382:     #   We'll give the connection a few tries before abandoning it.  If
                    383:     #   connection is not possible, we'll con_lost back to the client.
                    384:     #   
                    385:     my $client;
                    386:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    387: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    388: 				      Type    => SOCK_STREAM,
                    389: 				      Timeout => 10);
1.869     albertel  390: 	if ($client) {
1.550     foxr      391: 	    last;		# Connected!
1.850     albertel  392: 	} else {
1.853     albertel  393: 	    &create_connection(&hostname($server),$server);
1.550     foxr      394: 	}
1.1172.2.79  raeburn   395:         sleep(0.1);		# Try again later if failed connection.
1.550     foxr      396:     }
                    397:     my $answer;
                    398:     if ($client) {
1.704     albertel  399: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      400: 	$answer=<$client>;
                    401: 	if (!$answer) { $answer="con_lost"; }
                    402: 	chomp($answer);
                    403:     } else {
                    404: 	$answer = 'con_lost';	# Failed connection.
                    405:     }
1.1       albertel  406:     return $answer;
                    407: }
                    408: 
                    409: sub reply {
                    410:     my ($cmd,$server)=@_;
1.838     albertel  411:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  412:     my $answer=subreply($cmd,$server);
1.65      www       413:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1172.2.111  raeburn   414:         my $logged = $cmd;
                    415:         if ($cmd =~ /^encrypt:([^:]+):/) {
                    416:             my $subcmd = $1;
                    417:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
                    418:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    419:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
                    420:                 (undef,undef,my @rest) = split(/:/,$cmd);
                    421:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
                    422:                     splice(@rest,2,1,'Hidden');
                    423:                 } elsif ($subcmd eq 'passwd') {
                    424:                     splice(@rest,2,2,('Hidden','Hidden'));
                    425:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    426:                          ($subcmd eq 'autoexportgrades')) {
                    427:                     splice(@rest,3,1,'Hidden');
                    428:                 }
                    429:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
                    430:             }
                    431:         }
                    432:         &logthis("<font color=\"blue\">WARNING:".
                    433:                  " $logged to $server returned $answer</font>");
1.12      www       434:     }
1.1       albertel  435:     return $answer;
                    436: }
                    437: 
                    438: # ----------------------------------------------------------- Send USR1 to lonc
                    439: 
                    440: sub reconlonc {
1.891     albertel  441:     my ($lonid) = @_;
                    442:     if ($lonid) {
1.1172.2.72  raeburn   443:         my $hostname = &hostname($lonid);
1.891     albertel  444: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    445: 	if ($hostname && -e $peerfile) {
                    446: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    447: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    448: 					     Type    => SOCK_STREAM,
                    449: 					     Timeout => 10);
                    450: 	    if ($client) {
                    451: 		print $client ("reset_retries\n");
                    452: 		my $answer=<$client>;
                    453: 		#reset just this one.
                    454: 	    }
                    455: 	}
                    456: 	return;
                    457:     }
                    458: 
1.836     www       459:     &logthis("Trying to reconnect lonc");
1.1       albertel  460:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96  raeburn   461:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  462: 	my $loncpid=<$fh>;
                    463:         chomp($loncpid);
                    464:         if (kill 0 => $loncpid) {
                    465: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    466:             kill USR1 => $loncpid;
                    467:             sleep 1;
1.836     www       468:          } else {
1.12      www       469: 	    &logthis(
1.672     albertel  470:                "<font color=\"blue\">WARNING:".
1.12      www       471:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  472:         }
                    473:     } else {
1.836     www       474: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  475:     }
                    476: }
                    477: 
                    478: # ------------------------------------------------------ Critical communication
1.12      www       479: 
1.1       albertel  480: sub critical {
                    481:     my ($cmd,$server)=@_;
1.838     albertel  482:     unless (&hostname($server)) {
1.672     albertel  483:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       484:                " Critical message to unknown server ($server)</font>");
                    485:         return 'no_such_host';
                    486:     }
1.1       albertel  487:     my $answer=reply($cmd,$server);
                    488:     if ($answer eq 'con_lost') {
1.1172.2.72  raeburn   489: 	&reconlonc($server);
1.589     albertel  490: 	my $answer=reply($cmd,$server);
1.1       albertel  491:         if ($answer eq 'con_lost') {
                    492:             my $now=time;
                    493:             my $middlename=$cmd;
1.5       www       494:             $middlename=substr($middlename,0,16);
1.1       albertel  495:             $middlename=~s/\W//g;
                    496:             my $dfilename=
1.305     www       497:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    498:             $dumpcount++;
1.1       albertel  499:             {
1.448     albertel  500: 		my $dfh;
1.1172.2.96  raeburn   501: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  502: 		    print $dfh "$cmd\n"; 
                    503: 		    close($dfh);
                    504: 		}
1.1       albertel  505:             }
1.1172.2.79  raeburn   506:             sleep 1;
1.1       albertel  507:             my $wcmd='';
                    508:             {
1.448     albertel  509: 		my $dfh;
1.1172.2.96  raeburn   510: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  511: 		    $wcmd=<$dfh>; 
                    512: 		    close($dfh);
                    513: 		}
1.1       albertel  514:             }
                    515:             chomp($wcmd);
1.7       www       516:             if ($wcmd eq $cmd) {
1.672     albertel  517: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       518:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  519:                 &logperm("D:$server:$cmd");
                    520: 	        return 'con_delayed';
                    521:             } else {
1.672     albertel  522:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       523:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  524:                 &logperm("F:$server:$cmd");
                    525:                 return 'con_failed';
                    526:             }
                    527:         }
                    528:     }
                    529:     return $answer;
1.405     albertel  530: }
                    531: 
1.755     albertel  532: # ------------------------------------------- check if return value is an error
                    533: 
                    534: sub error {
                    535:     my ($result) = @_;
1.756     albertel  536:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  537: 	if ($2 == 2) { return undef; }
                    538: 	return $1;
                    539:     }
                    540:     return undef;
                    541: }
                    542: 
1.783     albertel  543: sub convert_and_load_session_env {
                    544:     my ($lonidsdir,$handle)=@_;
                    545:     my @profile;
                    546:     {
1.917     albertel  547: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    548: 	if (!$opened) {
1.915     albertel  549: 	    return 0;
                    550: 	}
1.783     albertel  551: 	flock($idf,LOCK_SH);
                    552: 	@profile=<$idf>;
                    553: 	close($idf);
                    554:     }
                    555:     my %temp_env;
                    556:     foreach my $line (@profile) {
1.786     albertel  557: 	if ($line !~ m/=/) {
                    558: 	    return 0;
                    559: 	}
1.783     albertel  560: 	chomp($line);
                    561: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    562: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    563:     }
                    564:     unlink("$lonidsdir/$handle.id");
                    565:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    566: 	    0640)) {
                    567: 	%disk_env = %temp_env;
                    568: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    569: 	untie(%disk_env);
                    570:     }
1.786     albertel  571:     return 1;
1.783     albertel  572: }
                    573: 
1.374     www       574: # ------------------------------------------- Transfer profile into environment
1.780     albertel  575: my $env_loaded;
                    576: sub transfer_profile_to_env {
1.788     albertel  577:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    578:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       579: 
1.720     albertel  580:     if (!defined($lonidsdir)) {
                    581: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    582:     }
                    583:     if (!defined($handle)) {
                    584:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    585:     }
                    586: 
1.786     albertel  587:     my $convert;
                    588:     {
1.917     albertel  589:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    590: 	if (!$opened) {
1.915     albertel  591: 	    return;
                    592: 	}
1.786     albertel  593: 	flock($idf,LOCK_SH);
                    594: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    595: 		&GDBM_READER(),0640)) {
                    596: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    597: 	    untie(%disk_env);
                    598: 	} else {
                    599: 	    $convert = 1;
                    600: 	}
                    601:     }
                    602:     if ($convert) {
                    603: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    604: 	    &logthis("Failed to load session, or convert session.");
                    605: 	}
1.374     www       606:     }
1.783     albertel  607: 
1.786     albertel  608:     my %remove;
1.783     albertel  609:     while ( my $envname = each(%env) ) {
1.433     matthew   610:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    611:             if ($time < time-300) {
1.783     albertel  612:                 $remove{$key}++;
1.433     matthew   613:             }
                    614:         }
                    615:     }
1.783     albertel  616: 
1.619     albertel  617:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  618:     $env_loaded=1;
1.783     albertel  619:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   620:         &delenv($expired_key);
1.374     www       621:     }
1.1       albertel  622: }
                    623: 
1.916     albertel  624: # ---------------------------------------------------- Check for valid session 
                    625: sub check_for_valid_session {
1.1172.2.96  raeburn   626:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  627:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1172.2.108  raeburn   628:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
1.1155    raeburn   629:     if ($name eq 'lonDAV') {
                    630:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    631:     } else {
                    632:         $lonidsdir=$r->dir_config('lonIDsDir');
1.1172.2.108  raeburn   633:         if ($name eq '') {
                    634:             $name = 'lonID';
                    635:         }
                    636:     }
                    637:     if ($name eq 'lonID') {
                    638:         $secure = 'lonSID';
                    639:         $linkname = 'lonLinkID';
                    640:         $pubname = 'lonPubID';
                    641:         if (exists($cookies{$secure})) {
                    642:             $lonid=$cookies{$secure};
                    643:         } elsif (exists($cookies{$name})) {
                    644:             $lonid=$cookies{$name};
                    645:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
                    646:             $lonid=$cookies{$linkname};
                    647:         } elsif (exists($cookies{$pubname})) {
                    648:             $lonid=$cookies{$pubname};
                    649:         }
                    650:     } else {
                    651:         $lonid=$cookies{$name};
                    652:     }
                    653:     return undef if (!$lonid);
                    654: 
                    655:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    656:     if (-l "$lonidsdir/$handle.id") {
                    657:         my $link = readlink("$lonidsdir/$handle.id");
                    658:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    659:             $handle = $1;
                    660:         }
1.1155    raeburn   661:     }
1.1172.2.96  raeburn   662:     if (!-e "$lonidsdir/$handle.id") {
                    663:         if ((ref($domref)) && ($name eq 'lonID') &&
                    664:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    665:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    666:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    667:                 $$domref = $possudom;
                    668:             }
                    669:         }
                    670:         return undef;
                    671:     }
1.916     albertel  672: 
1.917     albertel  673:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    674:     return undef if (!$opened);
1.916     albertel  675: 
                    676:     flock($idf,LOCK_SH);
                    677:     my %disk_env;
                    678:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    679: 	    &GDBM_READER(),0640)) {
                    680: 	return undef;	
                    681:     }
                    682: 
                    683:     if (!defined($disk_env{'user.name'})
                    684: 	|| !defined($disk_env{'user.domain'})) {
1.1172.2.107  raeburn   685:         untie(%disk_env);
1.916     albertel  686: 	return undef;
                    687:     }
1.1172.2.18  raeburn   688: 
1.1172.2.36  raeburn   689:     if (ref($userhashref) eq 'HASH') {
                    690:         $userhashref->{'name'} = $disk_env{'user.name'};
                    691:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18  raeburn   692:     }
1.1172.2.107  raeburn   693:     untie(%disk_env);
1.1172.2.18  raeburn   694: 
1.916     albertel  695:     return $handle;
                    696: }
                    697: 
1.830     albertel  698: sub timed_flock {
                    699:     my ($file,$lock_type) = @_;
                    700:     my $failed=0;
                    701:     eval {
                    702: 	local $SIG{__DIE__}='DEFAULT';
                    703: 	local $SIG{ALRM}=sub {
                    704: 	    $failed=1;
                    705: 	    die("failed lock");
                    706: 	};
                    707: 	alarm(13);
                    708: 	flock($file,$lock_type);
                    709: 	alarm(0);
                    710:     };
                    711:     if ($failed) {
                    712: 	return undef;
                    713:     } else {
                    714: 	return 1;
                    715:     }
                    716: }
                    717: 
1.1172.2.107  raeburn   718: sub get_sessionfile_vars {
                    719:     my ($handle,$lonidsdir,$storearr) = @_;
                    720:     my %returnhash;
                    721:     unless (ref($storearr) eq 'ARRAY') {
                    722:         return %returnhash;
                    723:     }
                    724:     if (-l "$lonidsdir/$handle.id") {
                    725:         my $link = readlink("$lonidsdir/$handle.id");
                    726:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    727:             $handle = $1;
                    728:         }
                    729:     }
                    730:     if ((-e "$lonidsdir/$handle.id") &&
                    731:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    732:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    733:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    734:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    735:                 flock($idf,LOCK_SH);
                    736:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    737:                         &GDBM_READER(),0640)) {
                    738:                     foreach my $item (@{$storearr}) {
                    739:                         $returnhash{$item} = $disk_env{$item};
                    740:                     }
                    741:                     untie(%disk_env);
                    742:                 }
                    743:             }
                    744:         }
                    745:     }
                    746:     return %returnhash;
                    747: }
                    748: 
1.5       www       749: # ---------------------------------------------------------- Append Environment
                    750: 
                    751: sub appenv {
1.949     raeburn   752:     my ($newenv,$roles) = @_;
                    753:     if (ref($newenv) eq 'HASH') {
                    754:         foreach my $key (keys(%{$newenv})) {
                    755:             my $refused = 0;
                    756: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    757:                 $refused = 1;
                    758:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   759:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   760:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    761:                         $refused = 0;
                    762:                     }
                    763:                 }
                    764:             }
                    765:             if ($refused) {
                    766:                 &logthis("<font color=\"blue\">WARNING: ".
                    767:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    768:                          .'</font>');
                    769: 	        delete($newenv->{$key});
                    770:             } else {
                    771:                 $env{$key}=$newenv->{$key};
                    772:             }
                    773:         }
1.1172.2.96  raeburn   774:         my $lonids = $perlvar{'lonIDsDir'};
                    775:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    776:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    777:             if ($opened
                    778: 	        && &timed_flock($env_file,LOCK_EX)
                    779: 	        &&
                    780: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    781: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    782: 	        while (my ($key,$value) = each(%{$newenv})) {
                    783: 	            $disk_env{$key} = $value;
                    784: 	        }
                    785: 	        untie(%disk_env);
                    786:             }
1.35      www       787:         }
1.191     harris41  788:     }
1.56      www       789:     return 'ok';
                    790: }
                    791: # ----------------------------------------------------- Delete from Environment
                    792: 
                    793: sub delenv {
1.1104    raeburn   794:     my ($delthis,$regexp,$roles) = @_;
                    795:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    796:         my $refused = 1;
                    797:         if (ref($roles) eq 'ARRAY') {
                    798:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    799:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    800:                 $refused = 0;
                    801:             }
                    802:         }
                    803:         if ($refused) {
                    804:             &logthis("<font color=\"blue\">WARNING: ".
                    805:                      "Attempt to delete from environment ".$delthis);
                    806:             return 'error';
                    807:         }
1.56      www       808:     }
1.917     albertel  809:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    810:     if ($opened
1.915     albertel  811: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  812: 	&&
                    813: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    814: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  815: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   816: 	    if ($regexp) {
                    817:                 if ($key=~/^$delthis/) {
                    818:                     delete($env{$key});
                    819:                     delete($disk_env{$key});
                    820:                 } 
                    821:             } else {
                    822:                 if ($key=~/^\Q$delthis\E/) {
                    823: 		    delete($env{$key});
                    824: 		    delete($disk_env{$key});
                    825: 	        }
                    826:             }
1.448     albertel  827: 	}
1.783     albertel  828: 	untie(%disk_env);
1.5       www       829:     }
                    830:     return 'ok';
1.369     albertel  831: }
                    832: 
1.790     albertel  833: sub get_env_multiple {
                    834:     my ($name) = @_;
                    835:     my @values;
                    836:     if (defined($env{$name})) {
                    837:         # exists is it an array
                    838:         if (ref($env{$name})) {
                    839:             @values=@{ $env{$name} };
                    840:         } else {
                    841:             $values[0]=$env{$name};
                    842:         }
                    843:     }
                    844:     return(@values);
                    845: }
                    846: 
1.958     www       847: # ------------------------------------------------------------------- Locking
                    848: 
                    849: sub set_lock {
                    850:     my ($text)=@_;
                    851:     $locknum++;
                    852:     my $id=$$.'-'.$locknum;
                    853:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    854:              'session.lock.'.$id => $text});
                    855:     return $id;
                    856: }
                    857: 
                    858: sub get_locks {
                    859:     my $num=0;
                    860:     my %texts=();
                    861:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    862:        if ($lock=~/\w/) {
                    863:           $num++;
                    864:           $texts{$lock}=$env{'session.lock.'.$lock};
                    865:        }
                    866:    }
                    867:    return ($num,%texts);
                    868: }
                    869: 
                    870: sub remove_lock {
                    871:     my ($id)=@_;
                    872:     my $newlocks='';
                    873:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    874:        if (($lock=~/\w/) && ($lock ne $id)) {
                    875:           $newlocks.=','.$lock;
                    876:        }
                    877:     }
                    878:     &appenv({'session.locks' => $newlocks});
                    879:     &delenv('session.lock.'.$id);
                    880: }
                    881: 
                    882: sub remove_all_locks {
                    883:     my $activelocks=$env{'session.locks'};
                    884:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    885:        if ($lock=~/\w/) {
                    886:           &remove_lock($lock);
                    887:        }
                    888:     }
                    889: }
                    890: 
                    891: 
1.369     albertel  892: # ------------------------------------------ Find out current server userload
                    893: sub userload {
                    894:     my $numusers=0;
                    895:     {
                    896: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    897: 	my $filename;
                    898: 	my $curtime=time;
                    899: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  900: 	    next if ($filename eq '.' || $filename eq '..');
                    901: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1172.2.112  raeburn   902:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel  903: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  904: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  905: 	}
                    906: 	closedir(LONIDS);
                    907:     }
                    908:     my $userloadpercent=0;
                    909:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    910:     if ($maxuserload) {
1.371     albertel  911: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  912:     }
1.372     albertel  913:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  914:     return $userloadpercent;
1.283     www       915: }
                    916: 
1.1       albertel  917: # ------------------------------ Find server with least workload from spare.tab
1.11      www       918: 
1.1       albertel  919: sub spareserver {
1.1083    raeburn   920:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  921:     my $spare_server;
1.370     albertel  922:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  923:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    924:                                                      :  $userloadpercent;
1.1083    raeburn   925:     my ($uint_dom,$remotesessions);
                    926:     if (($udom ne '') && (&domain($udom) ne '')) {
                    927:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    928:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    929:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    930:         $remotesessions = $udomdefaults{'remotesessions'};
                    931:     }
1.1123    raeburn   932:     my $spareshash = &this_host_spares($udom);
                    933:     if (ref($spareshash) eq 'HASH') {
                    934:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    935:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62  raeburn   936:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    937:                                              $try_server));
1.1123    raeburn   938: 	        ($spare_server, $lowest_load) =
                    939: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    940:             }
1.1083    raeburn   941:         }
1.784     albertel  942: 
1.1123    raeburn   943:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    944: 
                    945:         if (!$found_server) {
                    946:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    947: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62  raeburn   948:                     next unless (&spare_can_host($udom,$uint_dom,
                    949:                                                  $remotesessions,$try_server));
1.1123    raeburn   950: 	            ($spare_server, $lowest_load) =
                    951: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    952:                 }
                    953: 	    }
                    954:         }
1.784     albertel  955:     }
                    956: 
                    957:     if (!$want_server_name) {
1.1001    raeburn   958:         if (defined($spare_server)) {
                    959:             my $hostname = &hostname($spare_server);
1.1083    raeburn   960:             if (defined($hostname)) {
1.1172.2.120  raeburn   961:                 my $protocol = 'http';
                    962:                 if ($protocol{$spare_server} eq 'https') {
                    963:                     $protocol = $protocol{$spare_server};
                    964:                 }
1.1001    raeburn   965: 	        $spare_server = $protocol.'://'.$hostname;
                    966:             }
                    967:         }
1.784     albertel  968:     }
                    969:     return $spare_server;
                    970: }
                    971: 
                    972: sub compare_server_load {
1.1172.2.41  raeburn   973:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    974: 
                    975:     if ($required) {
                    976:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    977:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    978:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    979:         if (($major eq '' && $minor eq '') ||
                    980:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    981:             return ($spare_server,$lowest_load);
                    982:         }
                    983:     }
1.784     albertel  984: 
                    985:     my $loadans     = &reply('load',    $try_server);
                    986:     my $userloadans = &reply('userload',$try_server);
                    987: 
                    988:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   989: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  990:     }
                    991: 
                    992:     my $load;
                    993:     if ($loadans =~ /\d/) {
                    994: 	if ($userloadans =~ /\d/) {
                    995: 	    #both are numbers, pick the bigger one
                    996: 	    $load = ($loadans > $userloadans) ? $loadans 
                    997: 		                              : $userloadans;
1.411     albertel  998: 	} else {
1.784     albertel  999: 	    $load = $loadans;
1.411     albertel 1000: 	}
1.784     albertel 1001:     } else {
                   1002: 	$load = $userloadans;
                   1003:     }
                   1004: 
                   1005:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1006: 	$spare_server = $try_server;
                   1007: 	$lowest_load  = $load;
1.370     albertel 1008:     }
1.784     albertel 1009:     return ($spare_server,$lowest_load);
1.202     matthew  1010: }
1.914     albertel 1011: 
                   1012: # --------------------------- ask offload servers if user already has a session
                   1013: sub find_existing_session {
                   1014:     my ($udom,$uname) = @_;
1.1123    raeburn  1015:     my $spareshash = &this_host_spares($udom);
                   1016:     if (ref($spareshash) eq 'HASH') {
                   1017:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1018:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1019:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1020:             }
                   1021:         }
                   1022:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1023:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1024:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1025:             }
                   1026:         }
1.914     albertel 1027:     }
                   1028:     return;
                   1029: }
                   1030: 
1.1172.2.107  raeburn  1031: # check if user's browser sent load balancer cookie and server still has session
                   1032: # and is not overloaded.
                   1033: sub check_for_balancer_cookie {
                   1034:     my ($r,$update_mtime) = @_;
                   1035:     my ($otherserver,$cookie);
                   1036:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1037:     if (exists($cookies{'balanceID'})) {
                   1038:         my $balid = $cookies{'balanceID'};
                   1039:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1040:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1041:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1042:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1043:                 my ($possudom,$possuname) = ($1,$2);
                   1044:                 my $has_session = 0;
                   1045:                 if ((&domain($possudom) ne '') &&
                   1046:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1047:                     my $try_server;
                   1048:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1049:                     if ($opened) {
                   1050:                         flock($idf,LOCK_SH);
                   1051:                         while (my $line = <$idf>) {
                   1052:                             chomp($line);
                   1053:                             if (&hostname($line) ne '') {
                   1054:                                 $try_server = $line;
                   1055:                                 last;
                   1056:                             }
                   1057:                         }
                   1058:                         close($idf);
                   1059:                         if (($try_server) &&
                   1060:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1061:                             my $lowest_load = 30000;
                   1062:                             ($otherserver,$lowest_load) =
                   1063:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1064:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1065:                                 $has_session = 1;
                   1066:                             } else {
                   1067:                                 undef($otherserver);
                   1068:                             }
                   1069:                         }
                   1070:                     }
                   1071:                 }
                   1072:                 if ($has_session) {
                   1073:                     if ($update_mtime) {
                   1074:                         my $atime = my $mtime = time;
                   1075:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1076:                     }
                   1077:                 } else {
                   1078:                     unlink("$balancedir/$cookie.id");
                   1079:                 }
                   1080:             }
                   1081:         }
                   1082:     }
                   1083:     return ($otherserver,$cookie);
                   1084: }
                   1085: 
1.1172.2.130  raeburn  1086: sub updatebalcookie {
                   1087:     my ($cookie,$balancer,$lastentry)=@_;
                   1088:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1089:         my ($udom,$uname) = ($1,$2);
                   1090:         my $uprimary_id = &domain($udom,'primary');
                   1091:         my $uintdom = &internet_dom($uprimary_id);
                   1092:         my $intdom = &internet_dom($balancer);
                   1093:         my $serverhomedom = &host_domain($balancer);
                   1094:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1095:             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
                   1096:         }
                   1097:     }
                   1098:     return;
                   1099: }
                   1100: 
1.1172.2.107  raeburn  1101: sub delbalcookie {
                   1102:     my ($cookie,$balancer) =@_;
                   1103:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1104:         my ($udom,$uname) = ($1,$2);
                   1105:         my $uprimary_id = &domain($udom,'primary');
                   1106:         my $uintdom = &internet_dom($uprimary_id);
                   1107:         my $intdom = &internet_dom($balancer);
                   1108:         my $serverhomedom = &host_domain($balancer);
                   1109:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1172.2.130  raeburn  1110:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1172.2.107  raeburn  1111:         }
                   1112:     }
                   1113: }
                   1114: 
1.914     albertel 1115: # -------------------------------- ask if server already has a session for user
                   1116: sub has_user_session {
                   1117:     my ($lonid,$udom,$uname) = @_;
                   1118:     my $result = &reply(join(':','userhassession',
                   1119: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1120:     return 1 if ($result eq 'ok');
                   1121: 
                   1122:     return 0;
                   1123: }
                   1124: 
1.1076    raeburn  1125: # --------- determine least loaded server in a user's domain which allows login
                   1126: 
                   1127: sub choose_server {
1.1172.2.47  raeburn  1128:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1129:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1130:     my %servers = &get_servers($udom);
1.1076    raeburn  1131:     my $lowest_load = 30000;
1.1172.2.47  raeburn  1132:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1133:     if ($skiploadbal) {
                   1134:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1135:         unless (defined($cached)) {
                   1136:             my $cachetime = 60*60*24;
                   1137:             my %domconfig =
                   1138:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1139:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1140:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1141:                                            $cachetime);
                   1142:             }
                   1143:         }
                   1144:     }
1.1076    raeburn  1145:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn  1146:         my $loginvia;
1.1172.2.47  raeburn  1147:         if ($skiploadbal) {
                   1148:             if (ref($balancers) eq 'HASH') {
                   1149:                 next if (exists($balancers->{$lonhost}));
                   1150:             }
                   1151:         }
1.1115    raeburn  1152:         if ($checkloginvia) {
                   1153:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1154:             if ($loginvia) {
                   1155:                 my ($server,$path) = split(/:/,$loginvia);
                   1156:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1157:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1158:                 if ($login_host eq $server) {
                   1159:                     $portal_path = $path;
1.1151    raeburn  1160:                     $isredirect = 1;
1.1116    raeburn  1161:                 }
                   1162:             } else {
                   1163:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1164:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1165:                 if ($login_host eq $lonhost) {
                   1166:                     $portal_path = '';
1.1151    raeburn  1167:                     $isredirect = ''; 
1.1116    raeburn  1168:                 }
                   1169:             }
                   1170:         } else {
1.1076    raeburn  1171:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1172:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1173:         }
                   1174:     }
                   1175:     if ($login_host ne '') {
1.1116    raeburn  1176:         $hostname = &hostname($login_host);
1.1076    raeburn  1177:     }
1.1172.2.88  raeburn  1178:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1179: }
                   1180: 
1.1172.2.123  raeburn  1181: sub get_course_sessions {
                   1182:     my ($cnum,$cdom,$lastactivity) = @_;
                   1183:     my %servers = &internet_dom_servers($cdom);
                   1184:     my %returnhash;
                   1185:     foreach my $server (sort(keys(%servers))) {
                   1186:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
                   1187:         my @pairs=split(/\&/,$rep);
                   1188:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
                   1189:             foreach my $item (@pairs) {
                   1190:                 my ($key,$value)=split(/=/,$item,2);
                   1191:                 $key = &unescape($key);
                   1192:                 next if ($key =~ /^error: 2 /);
                   1193:                 if (exists($returnhash{$key})) {
                   1194:                     next if ($value < $returnhash{$key});
                   1195:                 }
                   1196:                 $returnhash{$key}=$value;
                   1197:             }
                   1198:         }
                   1199:     }
                   1200:     return %returnhash;
                   1201: }
                   1202: 
1.202     matthew  1203: # --------------------------------------------- Try to change a user's password
                   1204: 
                   1205: sub changepass {
1.799     raeburn  1206:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1207:     $currentpass = &escape($currentpass);
                   1208:     $newpass     = &escape($newpass);
1.1030    raeburn  1209:     my $lonhost = $perlvar{'lonHostID'};
                   1210:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1211: 		       $server);
                   1212:     if (! $answer) {
                   1213: 	&logthis("No reply on password change request to $server ".
                   1214: 		 "by $uname in domain $udom.");
                   1215:     } elsif ($answer =~ "^ok") {
                   1216:         &logthis("$uname in $udom successfully changed their password ".
                   1217: 		 "on $server.");
                   1218:     } elsif ($answer =~ "^pwchange_failure") {
                   1219: 	&logthis("$uname in $udom was unable to change their password ".
                   1220: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1221: 		 "or pwchange");
                   1222:     } elsif ($answer =~ "^non_authorized") {
                   1223:         &logthis("$uname in $udom did not get their password correct when ".
                   1224: 		 "attempting to change it on $server.");
                   1225:     } elsif ($answer =~ "^auth_mode_error") {
                   1226:         &logthis("$uname in $udom attempted to change their password despite ".
                   1227: 		 "not being locally or internally authenticated on $server.");
                   1228:     } elsif ($answer =~ "^unknown_user") {
                   1229:         &logthis("$uname in $udom attempted to change their password ".
                   1230: 		 "on $server but were unable to because $server is not ".
                   1231: 		 "their home server.");
                   1232:     } elsif ($answer =~ "^refused") {
                   1233: 	&logthis("$server refused to change $uname in $udom password because ".
                   1234: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1235:     } elsif ($answer =~ "invalid_client") {
                   1236:         &logthis("$server refused to change $uname in $udom password because ".
                   1237:                  "it was a reset by e-mail originating from an invalid server.");
1.1172.2.113  raeburn  1238:     } elsif ($answer =~ "^prioruse") {
                   1239:        &logthis("$server refused to change $uname in $udom password because ".
                   1240:                 "the password had been used before");
1.202     matthew  1241:     }
                   1242:     return $answer;
1.1       albertel 1243: }
                   1244: 
1.169     harris41 1245: # ----------------------- Try to determine user's current authentication scheme
                   1246: 
                   1247: sub queryauthenticate {
                   1248:     my ($uname,$udom)=@_;
1.456     albertel 1249:     my $uhome=&homeserver($uname,$udom);
                   1250:     if (!$uhome) {
                   1251: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1252: 	return 'no_host';
                   1253:     }
                   1254:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1255:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1256: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1257:     }
1.456     albertel 1258:     return $answer;
1.169     harris41 1259: }
                   1260: 
1.1       albertel 1261: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1262: 
1.1       albertel 1263: sub authenticate {
1.1073    raeburn  1264:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1265:     $upass=&escape($upass);
                   1266:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1267:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1268:     my $newhome;
1.836     www      1269:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1270: # Maybe the machine was offline and only re-appeared again recently?
                   1271:         &reconlonc();
                   1272: # One more
1.952     raeburn  1273: 	$uhome=&homeserver($uname,$udom,1);
                   1274:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1275:             if (defined(&domain($udom,'primary'))) {
                   1276:                 $newhome=&domain($udom,'primary');
                   1277:             }
                   1278:             if ($newhome ne '') {
                   1279:                 $uhome = $newhome;
                   1280:             }
                   1281:         }
1.836     www      1282: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1283: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1284: 	    return 'no_host';
                   1285:         }
1.1       albertel 1286:     }
1.1073    raeburn  1287:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1288:     if ($answer eq 'authorized') {
1.952     raeburn  1289:         if ($newhome) {
                   1290:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1291:             return 'no_account_on_host'; 
                   1292:         } else {
                   1293:             &logthis("User $uname at $udom authorized by $uhome");
                   1294:             return $uhome;
                   1295:         }
1.471     albertel 1296:     }
                   1297:     if ($answer eq 'non_authorized') {
                   1298: 	&logthis("User $uname at $udom rejected by $uhome");
                   1299: 	return 'no_host'; 
1.9       www      1300:     }
1.471     albertel 1301:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1302:     return 'no_host';
                   1303: }
                   1304: 
1.1073    raeburn  1305: sub can_host_session {
1.1074    raeburn  1306:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1307:     my $canhost = 1;
1.1074    raeburn  1308:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1309:     if (ref($remotesessions) eq 'HASH') {
                   1310:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1311:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1312:                 $canhost = 0;
                   1313:             } else {
                   1314:                 $canhost = 1;
                   1315:             }
                   1316:         }
                   1317:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1318:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1319:                 $canhost = 1;
                   1320:             } else {
                   1321:                 $canhost = 0;
                   1322:             }
                   1323:         }
                   1324:         if ($canhost) {
                   1325:             if ($remotesessions->{'version'} ne '') {
                   1326:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1327:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1328:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1329:                         my $major = $1;
                   1330:                         my $minor = $2;
                   1331:                         if (($major < $reqmajor ) ||
                   1332:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1333:                             $canhost = 0;
                   1334:                         }
                   1335:                     } else {
                   1336:                         $canhost = 0;
                   1337:                     }
                   1338:                 }
                   1339:             }
                   1340:         }
                   1341:     }
                   1342:     if ($canhost) {
                   1343:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1344:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1345:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1346:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1347:                 if (($uint_dom ne '') && 
                   1348:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1349:                     $canhost = 0;
                   1350:                 } else {
                   1351:                     $canhost = 1;
                   1352:                 }
                   1353:             }
                   1354:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1355:                 if (($uint_dom ne '') && 
                   1356:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1357:                     $canhost = 1;
                   1358:                 } else {
                   1359:                     $canhost = 0;
                   1360:                 }
                   1361:             }
                   1362:         }
                   1363:     }
                   1364:     return $canhost;
                   1365: }
                   1366: 
1.1083    raeburn  1367: sub spare_can_host {
                   1368:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1369:     my $canhost=1;
1.1172.2.62  raeburn  1370:     my $try_server_hostname = &hostname($try_server);
                   1371:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1372:     my $serverhomedom = &host_domain($serverhomeID);
                   1373:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1374:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1375:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1376:             $canhost = 0;
                   1377:         }
                   1378:     }
1.1172.2.136  raeburn  1379:     if ($canhost) {
                   1380:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
                   1381:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
                   1382:                 unless (&shared_institution($udom,$try_server)) {
                   1383:                     $canhost = 0;
                   1384:                 }
                   1385:             }
                   1386:         }
                   1387:     }
1.1172.2.62  raeburn  1388:     if (($canhost) && ($uint_dom)) {
                   1389:         my @intdoms;
                   1390:         my $internet_names = &get_internet_names($try_server);
                   1391:         if (ref($internet_names) eq 'ARRAY') {
                   1392:             @intdoms = @{$internet_names};
                   1393:         }
                   1394:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1395:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1396:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1397:                                          $remotesessions,
                   1398:                                          $defdomdefaults{'hostedsessions'});
                   1399:         }
1.1083    raeburn  1400:     }
                   1401:     return $canhost;
                   1402: }
                   1403: 
1.1123    raeburn  1404: sub this_host_spares {
                   1405:     my ($dom) = @_;
1.1126    raeburn  1406:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1407:     my @hosts = &current_machine_ids();
                   1408:     foreach my $lonhost (@hosts) {
                   1409:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1410:             $dom_in_use = $dom;
                   1411:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1412:             last;
                   1413:         }
                   1414:     }
1.1126    raeburn  1415:     if ($dom_in_use ne '') {
                   1416:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1417:     }
                   1418:     if (ref($result) ne 'HASH') {
                   1419:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1420:         $dom_in_use = &host_domain($lonhost_in_use);
                   1421:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1422:         if (ref($result) ne 'HASH') {
                   1423:             $result = \%spareid;
                   1424:         }
                   1425:     }
                   1426:     return $result;
                   1427: }
                   1428: 
                   1429: sub spares_for_offload  {
                   1430:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1431:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1432:     if (defined($cached)) {
                   1433:         return $result;
                   1434:     } else {
1.1126    raeburn  1435:         my $cachetime = 60*60*24;
                   1436:         my %domconfig =
                   1437:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1438:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1439:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1440:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1441:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1442:                 }
                   1443:             }
                   1444:         }
                   1445:     }
1.1126    raeburn  1446:     return;
1.1123    raeburn  1447: }
                   1448: 
1.1129    raeburn  1449: sub get_lonbalancer_config {
                   1450:     my ($servers) = @_;
                   1451:     my ($currbalancer,$currtargets);
                   1452:     if (ref($servers) eq 'HASH') {
                   1453:         foreach my $server (keys(%{$servers})) {
                   1454:             my %what = (
                   1455:                          spareid => 1,
                   1456:                          perlvar => 1,
                   1457:                        );
                   1458:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1459:             if ($result eq 'ok') {
                   1460:                 if (ref($returnhash) eq 'HASH') {
                   1461:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1462:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1463:                             $currbalancer = $server;
                   1464:                             $currtargets = {};
                   1465:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1466:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1467:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1468:                                 }
                   1469:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1470:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1471:                                 }
                   1472:                             }
                   1473:                             last;
                   1474:                         }
                   1475:                     }
                   1476:                 }
                   1477:             }
                   1478:         }
                   1479:     }
                   1480:     return ($currbalancer,$currtargets);
                   1481: }
                   1482: 
                   1483: sub check_loadbalancing {
1.1172.2.88  raeburn  1484:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1485:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107  raeburn  1486:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129    raeburn  1487:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1488:     my @hosts = &current_machine_ids();
1.1129    raeburn  1489:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1490:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1491:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1492:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1493:     my $domneedscache; 
1.1129    raeburn  1494:     my $cachetime = 60*60*24;
                   1495: 
                   1496:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1497:         $dom_in_use = $udom;
                   1498:         $homeintdom = 1;
                   1499:     } else {
                   1500:         $dom_in_use = $serverhomedom;
                   1501:     }
                   1502:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1503:     unless (defined($cached)) {
                   1504:         my %domconfig =
                   1505:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1506:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1507:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1508:         } else {
                   1509:             $domneedscache = $dom_in_use;
1.1129    raeburn  1510:         }
                   1511:     }
                   1512:     if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1513:         ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1514:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1515:         if ($is_balancer) {
                   1516:             if (ref($currrules) eq 'HASH') {
                   1517:                 if ($homeintdom) {
                   1518:                     if ($uname ne '') {
                   1519:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1520:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1521:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1522:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1523:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1524:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1525:                             }
                   1526:                         }
                   1527:                         if ($rule_in_effect eq '') {
                   1528:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1529:                             if ($userenv{'inststatus'} ne '') {
                   1530:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1531:                                 my ($othertitle,$usertypes,$types) =
                   1532:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1533:                                 if (ref($types) eq 'ARRAY') {
                   1534:                                     foreach my $type (@{$types}) {
                   1535:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1536:                                             if (exists($currrules->{$type})) {
                   1537:                                                 $rule_in_effect = $currrules->{$type};
                   1538:                                             }
                   1539:                                         }
                   1540:                                     }
                   1541:                                 }
                   1542:                             } else {
                   1543:                                 if (exists($currrules->{'default'})) {
                   1544:                                     $rule_in_effect = $currrules->{'default'};
                   1545:                                 }
                   1546:                             }
                   1547:                         }
                   1548:                     } else {
                   1549:                         if (exists($currrules->{'default'})) {
                   1550:                             $rule_in_effect = $currrules->{'default'};
                   1551:                         }
                   1552:                     }
                   1553:                 } else {
                   1554:                     if ($currrules->{'_LC_external'} ne '') {
                   1555:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1556:                     }
                   1557:                 }
                   1558:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1559:                                                        $uname,$udom);
                   1560:             }
                   1561:         }
                   1562:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1563:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1564:         unless (defined($cached)) {
                   1565:             my %domconfig =
                   1566:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1567:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1568:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1569:             } else {
                   1570:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1571:             }
                   1572:         }
                   1573:         if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1574:             ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1575:                 &check_balancer_result($result,@hosts);
                   1576:             if ($is_balancer) {
1.1129    raeburn  1577:                 if (ref($currrules) eq 'HASH') {
                   1578:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1579:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1580:                     }
                   1581:                 }
                   1582:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1583:                                                        $uname,$udom);
                   1584:             }
                   1585:         } else {
                   1586:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1587:                 $is_balancer = 1;
                   1588:                 $offloadto = &this_host_spares($dom_in_use);
                   1589:             }
1.1172.2.75  raeburn  1590:             unless (defined($cached)) {
                   1591:                 $domneedscache = $serverhomedom;
                   1592:             }
1.1129    raeburn  1593:         }
                   1594:     } else {
                   1595:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1596:             $is_balancer = 1;
                   1597:             $offloadto = &this_host_spares($dom_in_use);
                   1598:         }
1.1172.2.75  raeburn  1599:         unless (defined($cached)) {
                   1600:             $domneedscache = $serverhomedom;
                   1601:         }
                   1602:     }
                   1603:     if ($domneedscache) {
                   1604:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1605:     }
1.1172.2.130  raeburn  1606:     if (($is_balancer) && ($caller ne 'switchserver')) {
1.1172.2.5  raeburn  1607:         my $lowest_load = 30000;
                   1608:         if (ref($offloadto) eq 'HASH') {
                   1609:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1610:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1611:                     ($otherserver,$lowest_load) =
                   1612:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1613:                 }
1.1129    raeburn  1614:             }
1.1172.2.5  raeburn  1615:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1616: 
1.1172.2.5  raeburn  1617:             if (!$found_server) {
                   1618:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1619:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1620:                         ($otherserver,$lowest_load) =
                   1621:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1622:                     }
                   1623:                 }
                   1624:             }
                   1625:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1626:             if (@{$offloadto} == 1) {
                   1627:                 $otherserver = $offloadto->[0];
                   1628:             } elsif (@{$offloadto} > 1) {
                   1629:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1630:                     ($otherserver,$lowest_load) =
                   1631:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1632:                 }
                   1633:             }
                   1634:         }
1.1172.2.88  raeburn  1635:         unless ($caller eq 'login') {
                   1636:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1637:                 $is_balancer = 0;
                   1638:                 if ($uname ne '' && $udom ne '') {
                   1639:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1640:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1641:                                  'user.loadbalcheck.time' => time});
                   1642:                     }
1.1172.2.5  raeburn  1643:                 }
1.1129    raeburn  1644:             }
                   1645:         }
1.1172.2.130  raeburn  1646:     }
                   1647:     if (($is_balancer) && (!$homeintdom)) {
                   1648:         undef($setcookie);
1.1129    raeburn  1649:     }
1.1172.2.107  raeburn  1650:     return ($is_balancer,$otherserver,$setcookie);
1.1129    raeburn  1651: }
                   1652: 
1.1172.2.12  raeburn  1653: sub check_balancer_result {
                   1654:     my ($result,@hosts) = @_;
1.1172.2.107  raeburn  1655:     my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1656:     if (ref($result) eq 'HASH') {
                   1657:         if ($result->{'lonhost'} ne '') {
                   1658:             my $currbalancer = $result->{'lonhost'};
                   1659:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1660:                 $is_balancer = 1;
                   1661:                 $currtargets = $result->{'targets'};
                   1662:                 $currrules = $result->{'rules'};
                   1663:             }
                   1664:         } else {
                   1665:             foreach my $key (keys(%{$result})) {
                   1666:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1667:                     (ref($result->{$key}) eq 'HASH')) {
                   1668:                     $is_balancer = 1;
                   1669:                     $currrules = $result->{$key}{'rules'};
                   1670:                     $currtargets = $result->{$key}{'targets'};
1.1172.2.107  raeburn  1671:                     $setcookie = $result->{$key}{'cookie'};
1.1172.2.12  raeburn  1672:                     last;
                   1673:                 }
                   1674:             }
                   1675:         }
                   1676:     }
1.1172.2.107  raeburn  1677:     return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1678: }
                   1679: 
1.1129    raeburn  1680: sub get_loadbalancer_targets {
                   1681:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1682:     my $offloadto;
1.1172.2.4  raeburn  1683:     if ($rule_in_effect eq 'none') {
                   1684:         return [$perlvar{'lonHostID'}];
                   1685:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1686:         $offloadto = $currtargets;
                   1687:     } else {
                   1688:         if ($rule_in_effect eq 'homeserver') {
                   1689:             my $homeserver = &homeserver($uname,$udom);
                   1690:             if ($homeserver ne 'no_host') {
                   1691:                 $offloadto = [$homeserver];
                   1692:             }
                   1693:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1694:             my %domconfig =
                   1695:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1696:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1697:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1698:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1699:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1700:                     }
                   1701:                 }
                   1702:             } else {
1.1172.2.7  raeburn  1703:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1704:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1705:                 if (&hostname($remotebalancer) ne '') {
                   1706:                     $offloadto = [$remotebalancer];
                   1707:                 }
                   1708:             }
                   1709:         } elsif (&hostname($rule_in_effect) ne '') {
                   1710:             $offloadto = [$rule_in_effect];
                   1711:         }
                   1712:     }
                   1713:     return $offloadto;
                   1714: }
                   1715: 
1.1127    raeburn  1716: sub internet_dom_servers {
                   1717:     my ($dom) = @_;
                   1718:     my (%uniqservers,%servers);
                   1719:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1720:     my @machinedoms = &machine_domains($primaryserver);
                   1721:     foreach my $mdom (@machinedoms) {
                   1722:         my %currservers = %servers;
                   1723:         my %server = &get_servers($mdom);
                   1724:         %servers = (%currservers,%server);
                   1725:     }
                   1726:     my %by_hostname;
                   1727:     foreach my $id (keys(%servers)) {
                   1728:         push(@{$by_hostname{$servers{$id}}},$id);
                   1729:     }
                   1730:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1731:         if (@{$by_hostname{$hostname}} > 1) {
                   1732:             my $match = 0;
                   1733:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1734:                 if (&host_domain($id) eq $dom) {
                   1735:                     $uniqservers{$id} = $hostname;
                   1736:                     $match = 1;
                   1737:                 }
                   1738:             }
                   1739:             unless ($match) {
                   1740:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1741:             }
                   1742:         } else {
                   1743:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1744:         }
                   1745:     }
                   1746:     return %uniqservers;
                   1747: }
                   1748: 
1.1       albertel 1749: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1750: 
1.599     albertel 1751: my %homecache;
1.1       albertel 1752: sub homeserver {
1.230     stredwic 1753:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1754:     my $index="$uname:$udom";
1.426     albertel 1755: 
1.599     albertel 1756:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1757: 
                   1758:     my %servers = &get_servers($udom,'library');
                   1759:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1760:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1761: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1762: 
                   1763: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1764: 	if ($answer eq 'found') {
                   1765: 	    delete($badServerCache{$tryserver}); 
                   1766: 	    return $homecache{$index}=$tryserver;
                   1767: 	} elsif ($answer eq 'no_host') {
                   1768: 	    $badServerCache{$tryserver}=1;
                   1769: 	}
1.1       albertel 1770:     }    
                   1771:     return 'no_host';
1.70      www      1772: }
                   1773: 
                   1774: # ------------------------------------- Find the usernames behind a list of IDs
                   1775: 
                   1776: sub idget {
                   1777:     my ($udom,@ids)=@_;
                   1778:     my %returnhash=();
                   1779:     
1.841     albertel 1780:     my %servers = &get_servers($udom,'library');
                   1781:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1782: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1783: 	$idlist=~tr/A-Z/a-z/; 
                   1784: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1785: 	my @answer=();
                   1786: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1787: 	    @answer=split(/\&/,$reply);
                   1788: 	}                    ;
                   1789: 	my $i;
                   1790: 	for ($i=0;$i<=$#ids;$i++) {
                   1791: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1792: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1793: 	    } 
                   1794: 	}
                   1795:     } 
1.70      www      1796:     return %returnhash;
                   1797: }
                   1798: 
                   1799: # ------------------------------------- Find the IDs behind a list of usernames
                   1800: 
                   1801: sub idrget {
                   1802:     my ($udom,@unames)=@_;
                   1803:     my %returnhash=();
1.800     albertel 1804:     foreach my $uname (@unames) {
                   1805:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1806:     }
1.70      www      1807:     return %returnhash;
                   1808: }
                   1809: 
                   1810: # ------------------------------- Store away a list of names and associated IDs
                   1811: 
                   1812: sub idput {
                   1813:     my ($udom,%ids)=@_;
                   1814:     my %servers=();
1.800     albertel 1815:     foreach my $uname (keys(%ids)) {
                   1816: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1817:         my $uhom=&homeserver($uname,$udom);
1.70      www      1818:         if ($uhom ne 'no_host') {
1.800     albertel 1819:             my $id=&escape($ids{$uname});
1.70      www      1820:             $id=~tr/A-Z/a-z/;
1.800     albertel 1821:             my $esc_unam=&escape($uname);
1.70      www      1822: 	    if ($servers{$uhom}) {
1.800     albertel 1823: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1824:             } else {
1.800     albertel 1825:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1826:             }
                   1827:         }
1.191     harris41 1828:     }
1.800     albertel 1829:     foreach my $server (keys(%servers)) {
                   1830:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1831:     }
1.344     www      1832: }
                   1833: 
1.1172.2.30  raeburn  1834: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1835: 
                   1836: sub iddel {
                   1837:     my ($udom,$idshashref,$uhome)=@_;
                   1838:     my %result=();
                   1839:     unless (ref($idshashref) eq 'HASH') {
                   1840:         return %result;
                   1841:     }
                   1842:     my %servers=();
                   1843:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1844:         my $uhom;
                   1845:         if ($uhome) {
                   1846:             $uhom = $uhome;
                   1847:         } else {
                   1848:             $uhom=&homeserver($uname,$udom);
                   1849:         }
                   1850:         if ($uhom ne 'no_host') {
                   1851:             if ($servers{$uhom}) {
                   1852:                 $servers{$uhom}.='&'.&escape($id);
                   1853:             } else {
                   1854:                 $servers{$uhom}=&escape($id);
                   1855:             }
                   1856:         }
                   1857:     }
                   1858:     foreach my $server (keys(%servers)) {
                   1859:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1860:     }
                   1861:     return %result;
                   1862: }
                   1863: 
1.1023    raeburn  1864: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1865: sub dump_dom {
1.1165    droeschl 1866:     my ($namespace, $udom, $regexp) = @_;
                   1867: 
                   1868:     $udom ||= $env{'user.domain'};
                   1869: 
                   1870:     return () unless $udom;
                   1871: 
                   1872:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1873: }
                   1874: 
1.1023    raeburn  1875: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1876: 
                   1877: sub get_dom {
1.860     raeburn  1878:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1879:     return if ($udom eq 'public');
1.806     raeburn  1880:     my $items='';
                   1881:     foreach my $item (@$storearr) {
                   1882:         $items.=&escape($item).'&';
                   1883:     }
                   1884:     $items=~s/\&$//;
1.860     raeburn  1885:     if (!$udom) {
                   1886:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1887:         return if ($udom eq 'public');
1.860     raeburn  1888:         if (defined(&domain($udom,'primary'))) {
                   1889:             $uhome=&domain($udom,'primary');
                   1890:         } else {
1.874     albertel 1891:             undef($uhome);
1.860     raeburn  1892:         }
                   1893:     } else {
                   1894:         if (!$uhome) {
                   1895:             if (defined(&domain($udom,'primary'))) {
                   1896:                 $uhome=&domain($udom,'primary');
                   1897:             }
                   1898:         }
                   1899:     }
                   1900:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1172.2.139  raeburn  1901:         my $rep;
                   1902:         if (grep { $_ eq $uhome } &current_machine_ids()) {
                   1903:             # domain information is hosted on this machine
                   1904:             $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
                   1905:         } else {        
                   1906:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   1907:         }
1.866     raeburn  1908:         my %returnhash;
1.875     albertel 1909:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1910:             return %returnhash;
                   1911:         }
1.806     raeburn  1912:         my @pairs=split(/\&/,$rep);
                   1913:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1914:             return @pairs;
                   1915:         }
                   1916:         my $i=0;
                   1917:         foreach my $item (@$storearr) {
                   1918:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1919:             $i++;
                   1920:         }
                   1921:         return %returnhash;
                   1922:     } else {
1.880     banghart 1923:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1924:     }
                   1925: }
                   1926: 
                   1927: # -------------------------------------------- put items in domain db files 
                   1928: 
                   1929: sub put_dom {
1.860     raeburn  1930:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1931:     if (!$udom) {
                   1932:         $udom=$env{'user.domain'};
                   1933:         if (defined(&domain($udom,'primary'))) {
                   1934:             $uhome=&domain($udom,'primary');
                   1935:         } else {
1.874     albertel 1936:             undef($uhome);
1.860     raeburn  1937:         }
                   1938:     } else {
                   1939:         if (!$uhome) {
                   1940:             if (defined(&domain($udom,'primary'))) {
                   1941:                 $uhome=&domain($udom,'primary');
                   1942:             }
                   1943:         }
                   1944:     } 
                   1945:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1946:         my $items='';
                   1947:         foreach my $item (keys(%$storehash)) {
                   1948:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1949:         }
                   1950:         $items=~s/\&$//;
                   1951:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1952:     } else {
1.860     raeburn  1953:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1954:     }
                   1955: }
                   1956: 
1.1023    raeburn  1957: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1958: sub newput_dom {
1.1023    raeburn  1959:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1960:     my $result;
                   1961:     if (!$udom) {
                   1962:         $udom=$env{'user.domain'};
                   1963:     }
1.1023    raeburn  1964:     if ($udom) {
                   1965:         my $uname = &get_domainconfiguser($udom);
                   1966:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1967:     }
                   1968:     return $result;
                   1969: }
                   1970: 
1.1023    raeburn  1971: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1972: sub del_dom {
1.1023    raeburn  1973:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1974:     if (ref($storearr) eq 'ARRAY') {
                   1975:         if (!$udom) {
                   1976:             $udom=$env{'user.domain'};
                   1977:         }
1.1023    raeburn  1978:         if ($udom) {
                   1979:             my $uname = &get_domainconfiguser($udom); 
                   1980:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1981:         }
                   1982:     }
                   1983: }
                   1984: 
1.1023    raeburn  1985: # ----------------------------------construct domainconfig user for a domain 
                   1986: sub get_domainconfiguser {
                   1987:     my ($udom) = @_;
                   1988:     return $udom.'-domainconfig';
                   1989: }
                   1990: 
1.837     raeburn  1991: sub retrieve_inst_usertypes {
                   1992:     my ($udom) = @_;
                   1993:     my (%returnhash,@order);
1.989     raeburn  1994:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1995:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1996:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1997:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1998:     } else {
                   1999:         if (defined(&domain($udom,'primary'))) {
                   2000:             my $uhome=&domain($udom,'primary');
                   2001:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2002:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  2003:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2004:                 return (\%returnhash,\@order);
                   2005:             }
                   2006:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2007:             my @pairs=split(/\&/,$hashitems);
                   2008:             foreach my $item (@pairs) {
                   2009:                 my ($key,$value)=split(/=/,$item,2);
                   2010:                 $key = &unescape($key);
                   2011:                 next if ($key =~ /^error: 2 /);
                   2012:                 $returnhash{$key}=&thaw_unescape($value);
                   2013:             }
                   2014:             my @esc_order = split(/\&/,$orderitems);
                   2015:             foreach my $item (@esc_order) {
                   2016:                 push(@order,&unescape($item));
                   2017:             }
                   2018:         } else {
1.1172.2.44  raeburn  2019:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2020:         }
1.1172.2.44  raeburn  2021:         return (\%returnhash,\@order);
1.837     raeburn  2022:     }
                   2023: }
                   2024: 
1.868     raeburn  2025: sub is_domainimage {
                   2026:     my ($url) = @_;
1.1172.2.74  raeburn  2027:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2028:         if (&domain($1) ne '') {
                   2029:             return '1';
                   2030:         }
                   2031:     }
                   2032:     return;
                   2033: }
                   2034: 
1.899     raeburn  2035: sub inst_directory_query {
                   2036:     my ($srch) = @_;
                   2037:     my $udom = $srch->{'srchdomain'};
                   2038:     my %results;
                   2039:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2040:     my $outcome;
1.899     raeburn  2041:     if ($homeserver ne '') {
1.1172.2.116  raeburn  2042:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2043:             if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2044:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116  raeburn  2045:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
                   2046:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2047:                     (($major == 2) && ($minor < 11)) ||
                   2048:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
                   2049:                     return;
                   2050:                 }
                   2051:             }
                   2052:         }
1.904     albertel 2053: 	my $queryid=&reply("querysend:instdirsearch:".
                   2054: 			   &escape($srch->{'srchby'}).':'.
                   2055: 			   &escape($srch->{'srchterm'}).':'.
                   2056: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2057: 	my $host=&hostname($homeserver);
                   2058: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  2059: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2060: 	    return;
                   2061: 	}
                   2062: 	my $response = &get_query_reply($queryid);
                   2063: 	my $maxtries = 5;
                   2064: 	my $tries = 1;
                   2065: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2066: 	    $response = &get_query_reply($queryid);
                   2067: 	    $tries ++;
                   2068: 	}
                   2069: 
                   2070:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2071:             if ($response eq 'unavailable') {
                   2072:                 $outcome = $response;
                   2073:             } else {
                   2074:                 $outcome = 'ok';
                   2075:                 my @matches = split(/\n/,$response);
                   2076:                 foreach my $match (@matches) {
                   2077:                     my ($key,$value) = split(/=/,$match);
                   2078:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2079:                 }
1.899     raeburn  2080:             }
                   2081:         }
                   2082:     }
1.909     raeburn  2083:     return ($outcome,%results);
1.899     raeburn  2084: }
                   2085: 
                   2086: sub usersearch {
                   2087:     my ($srch) = @_;
                   2088:     my $dom = $srch->{'srchdomain'};
                   2089:     my %results;
                   2090:     my %libserv = &all_library();
                   2091:     my $query = 'usersearch';
                   2092:     foreach my $tryserver (keys(%libserv)) {
                   2093:         if (&host_domain($tryserver) eq $dom) {
1.1172.2.116  raeburn  2094:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2095:                 if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2096:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.119  raeburn  2097:                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116  raeburn  2098:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2099:                              (($major == 2) && ($minor < 11)) ||
                   2100:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
                   2101:                 }
                   2102:             }
1.899     raeburn  2103:             my $host=&hostname($tryserver);
                   2104:             my $queryid=
1.911     raeburn  2105:                 &reply("querysend:".&escape($query).':'.
                   2106:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2107:                        &escape($srch->{'srchtype'}).':'.
                   2108:                        &escape($srch->{'srchterm'}),$tryserver);
                   2109:             if ($queryid !~/^\Q$host\E\_/) {
                   2110:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2111:                 next;
1.899     raeburn  2112:             }
                   2113:             my $reply = &get_query_reply($queryid);
                   2114:             my $maxtries = 1;
                   2115:             my $tries = 1;
                   2116:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2117:                 $reply = &get_query_reply($queryid);
                   2118:                 $tries ++;
                   2119:             }
                   2120:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2121:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2122:             } else {
1.911     raeburn  2123:                 my @matches;
                   2124:                 if ($reply =~ /\n/) {
                   2125:                     @matches = split(/\n/,$reply);
                   2126:                 } else {
                   2127:                     @matches = split(/\&/,$reply);
                   2128:                 }
1.899     raeburn  2129:                 foreach my $match (@matches) {
                   2130:                     my ($uname,$udom,%userhash);
1.911     raeburn  2131:                     foreach my $entry (split(/:/,$match)) {
                   2132:                         my ($key,$value) =
                   2133:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2134:                         $userhash{$key} = $value;
                   2135:                         if ($key eq 'username') {
                   2136:                             $uname = $value;
                   2137:                         } elsif ($key eq 'domain') {
                   2138:                             $udom = $value;
1.911     raeburn  2139:                         }
1.899     raeburn  2140:                     }
                   2141:                     $results{$uname.':'.$udom} = \%userhash;
                   2142:                 }
                   2143:             }
                   2144:         }
                   2145:     }
                   2146:     return %results;
                   2147: }
                   2148: 
1.912     raeburn  2149: sub get_instuser {
                   2150:     my ($udom,$uname,$id) = @_;
                   2151:     my $homeserver = &domain($udom,'primary');
                   2152:     my ($outcome,%results);
                   2153:     if ($homeserver ne '') {
                   2154:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2155:                            &escape($id).':'.&escape($udom),$homeserver);
                   2156:         my $host=&hostname($homeserver);
                   2157:         if ($queryid !~/^\Q$host\E\_/) {
                   2158:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2159:             return;
                   2160:         }
                   2161:         my $response = &get_query_reply($queryid);
                   2162:         my $maxtries = 5;
                   2163:         my $tries = 1;
                   2164:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2165:             $response = &get_query_reply($queryid);
                   2166:             $tries ++;
                   2167:         }
                   2168:         if (!&error($response) && $response ne 'refused') {
                   2169:             if ($response eq 'unavailable') {
                   2170:                 $outcome = $response;
                   2171:             } else {
                   2172:                 $outcome = 'ok';
                   2173:                 my @matches = split(/\n/,$response);
                   2174:                 foreach my $match (@matches) {
                   2175:                     my ($key,$value) = split(/=/,$match);
                   2176:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2177:                 }
                   2178:             }
                   2179:         }
                   2180:     }
                   2181:     my %userinfo;
                   2182:     if (ref($results{$uname}) eq 'HASH') {
                   2183:         %userinfo = %{$results{$uname}};
                   2184:     } 
                   2185:     return ($outcome,%userinfo);
                   2186: }
                   2187: 
1.1172.2.69  raeburn  2188: sub get_multiple_instusers {
                   2189:     my ($udom,$users,$caller) = @_;
                   2190:     my ($outcome,$results);
                   2191:     if (ref($users) eq 'HASH') {
                   2192:         my $count = keys(%{$users});
                   2193:         my $requested = &freeze_escape($users);
                   2194:         my $homeserver = &domain($udom,'primary');
                   2195:         if ($homeserver ne '') {
                   2196:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2197:             my $host=&hostname($homeserver);
                   2198:             if ($queryid !~/^\Q$host\E\_/) {
                   2199:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2200:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2201:                 return ($outcome,$results);
                   2202:             }
                   2203:             my $response = &get_query_reply($queryid);
                   2204:             my $maxtries = 5;
                   2205:             if ($count > 100) {
                   2206:                 $maxtries = 1+int($count/20);
                   2207:             }
                   2208:             my $tries = 1;
                   2209:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2210:                 $response = &get_query_reply($queryid);
                   2211:                 $tries ++;
                   2212:             }
                   2213:             if ($response eq '') {
                   2214:                 $results = {};
                   2215:                 foreach my $key (keys(%{$users})) {
                   2216:                     my ($uname,$id);
                   2217:                     if ($caller eq 'id') {
                   2218:                         $id = $key;
                   2219:                     } else {
                   2220:                         $uname = $key;
                   2221:                     }
                   2222:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2223:                     $outcome = $resp;
                   2224:                     if ($resp eq 'ok') {
                   2225:                         %{$results} = (%{$results}, %info);
                   2226:                     } else {
                   2227:                         last;
                   2228:                     }
                   2229:                 }
                   2230:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2231:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2232:                     $outcome = $response;
                   2233:                 } else {
                   2234:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2235:                     if ($outcome eq 'ok') {
                   2236:                         $results = &thaw_unescape($userdata);
                   2237:                     }
                   2238:                 }
                   2239:             }
                   2240:         }
                   2241:     }
                   2242:     return ($outcome,$results);
                   2243: }
                   2244: 
1.912     raeburn  2245: sub inst_rulecheck {
1.923     raeburn  2246:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2247:     my %returnhash;
                   2248:     if ($udom ne '') {
                   2249:         if (ref($rules) eq 'ARRAY') {
                   2250:             @{$rules} = map {&escape($_);} (@{$rules});
                   2251:             my $rulestr = join(':',@{$rules});
                   2252:             my $homeserver=&domain($udom,'primary');
                   2253:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2254:                 my $response;
                   2255:                 if ($item eq 'username') {                
                   2256:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2257:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2258:                                               $homeserver));
1.923     raeburn  2259:                 } elsif ($item eq 'id') {
                   2260:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2261:                                               ':'.&escape($id).':'.$rulestr,
                   2262:                                               $homeserver));
1.945     raeburn  2263:                 } elsif ($item eq 'selfcreate') {
                   2264:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2265:                                                &escape($udom).':'.&escape($uname).
                   2266:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2267:                 }
1.912     raeburn  2268:                 if ($response ne 'refused') {
                   2269:                     my @pairs=split(/\&/,$response);
                   2270:                     foreach my $item (@pairs) {
                   2271:                         my ($key,$value)=split(/=/,$item,2);
                   2272:                         $key = &unescape($key);
                   2273:                         next if ($key =~ /^error: 2 /);
                   2274:                         $returnhash{$key}=&thaw_unescape($value);
                   2275:                     }
                   2276:                 }
                   2277:             }
                   2278:         }
                   2279:     }
                   2280:     return %returnhash;
                   2281: }
                   2282: 
                   2283: sub inst_userrules {
1.923     raeburn  2284:     my ($udom,$check) = @_;
1.912     raeburn  2285:     my (%ruleshash,@ruleorder);
                   2286:     if ($udom ne '') {
                   2287:         my $homeserver=&domain($udom,'primary');
                   2288:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2289:             my $response;
                   2290:             if ($check eq 'id') {
                   2291:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2292:                                  $homeserver);
1.943     raeburn  2293:             } elsif ($check eq 'email') {
                   2294:                 $response=&reply('instemailrules:'.&escape($udom),
                   2295:                                  $homeserver);
1.923     raeburn  2296:             } else {
                   2297:                 $response=&reply('instuserrules:'.&escape($udom),
                   2298:                                  $homeserver);
                   2299:             }
1.912     raeburn  2300:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2301:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2302:                 ($response ne 'no_such_host')) {
                   2303:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2304:                 my @pairs=split(/\&/,$hashitems);
                   2305:                 foreach my $item (@pairs) {
                   2306:                     my ($key,$value)=split(/=/,$item,2);
                   2307:                     $key = &unescape($key);
                   2308:                     next if ($key =~ /^error: 2 /);
                   2309:                     $ruleshash{$key}=&thaw_unescape($value);
                   2310:                 }
                   2311:                 my @esc_order = split(/\&/,$orderitems);
                   2312:                 foreach my $item (@esc_order) {
                   2313:                     push(@ruleorder,&unescape($item));
                   2314:                 }
                   2315:             }
                   2316:         }
                   2317:     }
                   2318:     return (\%ruleshash,\@ruleorder);
                   2319: }
                   2320: 
1.976     raeburn  2321: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2322: 
                   2323: sub get_domain_defaults {
1.1172.2.35  raeburn  2324:     my ($domain,$ignore_cache) = @_;
                   2325:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2326:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2327:     unless ($ignore_cache) {
                   2328:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2329:         if (defined($cached)) {
                   2330:             if (ref($result) eq 'HASH') {
                   2331:                 return %{$result};
                   2332:             }
1.943     raeburn  2333:         }
                   2334:     }
                   2335:     my %domdefaults;
                   2336:     my %domconfig =
1.989     raeburn  2337:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2338:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2339:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2340:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2341:                                   'coursecategories','autoenroll',
                   2342:                                   'helpsettings'],$domain);
1.1172.2.41  raeburn  2343:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2344:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2345:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2346:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2347:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2348:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2349:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2350:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2351:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2352:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2353:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2354:     } else {
                   2355:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2356:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2357:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2358:     }
1.976     raeburn  2359:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2360:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2361:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2362:         } else {
                   2363:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2364:         }
1.1172.2.6  raeburn  2365:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2366:         foreach my $item (@usertools) {
                   2367:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2368:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2369:             }
                   2370:         }
1.1172.2.29  raeburn  2371:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2372:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2373:         }
1.976     raeburn  2374:     }
1.985     raeburn  2375:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2376:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2377:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2378:         }
                   2379:     }
1.1172.2.9  raeburn  2380:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2381:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2382:     }
1.989     raeburn  2383:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2384:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2385:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2386:         }
                   2387:     }
1.1047    raeburn  2388:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2389:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2390:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2391:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2392:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2393:         }
1.1172.2.41  raeburn  2394:         foreach my $type (@coursetypes) {
                   2395:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2396:                 unless ($type eq 'community') {
                   2397:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2398:                 }
                   2399:             }
                   2400:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2401:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2402:             }
1.1172.2.60  raeburn  2403:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2404:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2405:                     $domdefaults{$type.'postsubtimeout'} =
                   2406:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2407:                 }
                   2408:             }
1.1172.2.30  raeburn  2409:         }
1.1172.2.67  raeburn  2410:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2411:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2412:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2413:                 if (@clonecodes) {
                   2414:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2415:                 }
                   2416:             }
                   2417:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2418:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2419:         }
1.1172.2.103  raeburn  2420:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2421:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2422:         }
1.1047    raeburn  2423:     }
1.1073    raeburn  2424:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2425:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2426:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2427:         }
                   2428:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2429:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2430:         }
1.1172.2.62  raeburn  2431:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2432:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2433:         }
1.1172.2.137  raeburn  2434:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1172.2.136  raeburn  2435:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
                   2436:         }
1.1073    raeburn  2437:     }
1.1172.2.41  raeburn  2438:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2439:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2440:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2441:                             'approval','limit');
                   2442:             foreach my $type (@coursetypes) {
                   2443:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2444:                     my @mgrdc = ();
                   2445:                     foreach my $item (@settings) {
                   2446:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2447:                             push(@mgrdc,$item);
                   2448:                         }
                   2449:                     }
                   2450:                     if (@mgrdc) {
                   2451:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2452:                     }
                   2453:                 }
                   2454:             }
                   2455:         }
                   2456:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2457:             foreach my $type (@coursetypes) {
                   2458:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2459:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2460:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2461:                     }
                   2462:                 }
                   2463:             }
                   2464:         }
                   2465:     }
1.1172.2.46  raeburn  2466:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2467:         $domdefaults{'catauth'} = 'std';
                   2468:         $domdefaults{'catunauth'} = 'std';
                   2469:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2470:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2471:         }
                   2472:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2473:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2474:         }
                   2475:     }
1.1172.2.76  raeburn  2476:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2477:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2478:     }
1.1172.2.89  raeburn  2479:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2480:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2481:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2482:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2483:         }
                   2484:     }
1.1172.2.23  raeburn  2485:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2486:     return %domdefaults;
                   2487: }
                   2488: 
1.1172.2.106  raeburn  2489: sub get_dom_cats {
                   2490:     my ($dom) = @_;
                   2491:     return unless (&domain($dom));
                   2492:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2493:     unless (defined($cached)) {
                   2494:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2495:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2496:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2497:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2498:             } else {
                   2499:                 $cats = {};
                   2500:             }
                   2501:         } else {
                   2502:             $cats = {};
                   2503:         }
                   2504:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2505:     }
                   2506:     return $cats;
                   2507: }
                   2508: 
                   2509: sub get_dom_instcats {
                   2510:     my ($dom) = @_;
                   2511:     return unless (&domain($dom));
                   2512:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2513:     unless (defined($cached)) {
                   2514:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2515:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2516:         if ($totcodes > 0) {
                   2517:             my $caller = 'global';
                   2518:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2519:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2520:                 $instcats = {
                   2521:                                 codes => \%codes,
                   2522:                                 codetitles => \@codetitles,
                   2523:                                 cat_titles => \%cat_titles,
                   2524:                                 cat_order => \%cat_order,
                   2525:                             };
                   2526:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2527:             }
                   2528:         }
                   2529:     }
                   2530:     return $instcats;
                   2531: }
                   2532: 
                   2533: sub retrieve_instcodes {
                   2534:     my ($coursecodes,$dom) = @_;
                   2535:     my $totcodes;
                   2536:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2537:     foreach my $course (keys(%courses)) {
                   2538:         if (ref($courses{$course}) eq 'HASH') {
                   2539:             if ($courses{$course}{'inst_code'} ne '') {
                   2540:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2541:                 $totcodes ++;
                   2542:             }
                   2543:         }
                   2544:     }
                   2545:     return $totcodes;
                   2546: }
                   2547: 
1.1172.2.113  raeburn  2548: # --------------------------------------------- Get domain config for passwords
                   2549: 
                   2550: sub get_passwdconf {
                   2551:     my ($dom) = @_;
                   2552:     my (%passwdconf,$gotconf,$lookup);
                   2553:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2554:     if (defined($cached)) {
                   2555:         if (ref($result) eq 'HASH') {
                   2556:             %passwdconf = %{$result};
                   2557:             $gotconf = 1;
                   2558:         }
                   2559:     }
                   2560:     unless ($gotconf) {
                   2561:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2562:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2563:             %passwdconf = %{$domconfig{'passwords'}};
                   2564:         }
                   2565:         my $cachetime = 24*60*60;
                   2566:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2567:     }
                   2568:     return %passwdconf;
                   2569: }
                   2570: 
1.344     www      2571: # --------------------------------------------------- Assign a key to a student
                   2572: 
                   2573: sub assign_access_key {
1.364     www      2574: #
                   2575: # a valid key looks like uname:udom#comments
                   2576: # comments are being appended
                   2577: #
1.498     www      2578:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2579:     $kdom=
1.620     albertel 2580:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2581:     $knum=
1.620     albertel 2582:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2583:     $cdom=
1.620     albertel 2584:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2585:     $cnum=
1.620     albertel 2586:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2587:     $udom=$env{'user.name'} unless (defined($udom));
                   2588:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2589:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2590:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2591:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2592:                                                   # assigned to this person
                   2593:                                                   # - this should not happen,
1.345     www      2594:                                                   # unless something went wrong
                   2595:                                                   # the first time around
                   2596: # ready to assign
1.364     www      2597:         $logentry=$1.'; '.$logentry;
1.496     www      2598:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2599:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2600: # key now belongs to user
1.346     www      2601: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2602:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2603:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2604:                 return 'ok';
                   2605:             } else {
                   2606:                 return 
                   2607:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2608: 	    }
                   2609:         } else {
                   2610:             return 'error: Could not assign key, try again later.';
                   2611:         }
1.364     www      2612:     } elsif (!$existing{$ckey}) {
1.345     www      2613: # the key does not exist
                   2614: 	return 'error: The key does not exist';
                   2615:     } else {
                   2616: # the key is somebody else's
                   2617: 	return 'error: The key is already in use';
                   2618:     }
1.344     www      2619: }
                   2620: 
1.364     www      2621: # ------------------------------------------ put an additional comment on a key
                   2622: 
                   2623: sub comment_access_key {
                   2624: #
                   2625: # a valid key looks like uname:udom#comments
                   2626: # comments are being appended
                   2627: #
                   2628:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2629:     $cdom=
1.620     albertel 2630:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2631:     $cnum=
1.620     albertel 2632:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2633:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2634:     if ($existing{$ckey}) {
                   2635:         $existing{$ckey}.='; '.$logentry;
                   2636: # ready to assign
1.367     www      2637:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2638:                                                  $cdom,$cnum) eq 'ok') {
                   2639: 	    return 'ok';
                   2640:         } else {
                   2641: 	    return 'error: Count not store comment.';
                   2642:         }
                   2643:     } else {
                   2644: # the key does not exist
                   2645: 	return 'error: The key does not exist';
                   2646:     }
                   2647: }
                   2648: 
1.344     www      2649: # ------------------------------------------------------ Generate a set of keys
                   2650: 
                   2651: sub generate_access_keys {
1.364     www      2652:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2653:     $cdom=
1.620     albertel 2654:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2655:     $cnum=
1.620     albertel 2656:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2657:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2658:     unless (($cdom) && ($cnum)) { return 0; }
                   2659:     if ($number>10000) { return 0; }
                   2660:     sleep(2); # make sure don't get same seed twice
                   2661:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2662:     my $total=0;
                   2663:     for (my $i=1;$i<=$number;$i++) {
                   2664:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2665:                   sprintf("%lx",int(100000*rand)).'-'.
                   2666:                   sprintf("%lx",int(100000*rand));
                   2667:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2668:        $newkey=~s/0/h/g; # and also 0 and O
                   2669:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2670:        if ($existing{$newkey}) {
                   2671:            $i--;
                   2672:        } else {
1.364     www      2673: 	  if (&put('accesskeys',
                   2674:               { $newkey => '# generated '.localtime().
1.620     albertel 2675:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2676:                            '; '.$logentry },
                   2677: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2678:               $total++;
                   2679: 	  }
                   2680:        }
                   2681:     }
1.620     albertel 2682:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2683:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2684:     return $total;
                   2685: }
                   2686: 
                   2687: # ------------------------------------------------------- Validate an accesskey
                   2688: 
                   2689: sub validate_access_key {
                   2690:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2691:     $cdom=
1.620     albertel 2692:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2693:     $cnum=
1.620     albertel 2694:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2695:     $udom=$env{'user.domain'} unless (defined($udom));
                   2696:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2697:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2698:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2699: }
                   2700: 
                   2701: # ------------------------------------- Find the section of student in a course
1.652     albertel 2702: sub devalidate_getsection_cache {
                   2703:     my ($udom,$unam,$courseid)=@_;
                   2704:     my $hashid="$udom:$unam:$courseid";
                   2705:     &devalidate_cache_new('getsection',$hashid);
                   2706: }
1.298     matthew  2707: 
1.815     albertel 2708: sub courseid_to_courseurl {
                   2709:     my ($courseid) = @_;
                   2710:     #already url style courseid
                   2711:     return $courseid if ($courseid =~ m{^/});
                   2712: 
                   2713:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2714: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2715: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2716: 	return "/$cdom/$cnum";
                   2717:     }
                   2718: 
                   2719:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2720:     if (exists($courseinfo{'num'})) {
                   2721: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2722:     }
                   2723: 
                   2724:     return undef;
                   2725: }
                   2726: 
1.298     matthew  2727: sub getsection {
                   2728:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2729:     my $cachetime=1800;
1.551     albertel 2730: 
                   2731:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2732:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2733:     if (defined($cached)) { return $result; }
                   2734: 
1.298     matthew  2735:     my %Pending; 
                   2736:     my %Expired;
                   2737:     #
                   2738:     # Each role can either have not started yet (pending), be active, 
                   2739:     #    or have expired.
                   2740:     #
                   2741:     # If there is an active role, we are done.
                   2742:     #
                   2743:     # If there is more than one role which has not started yet, 
                   2744:     #     choose the one which will start sooner
                   2745:     # If there is one role which has not started yet, return it.
                   2746:     #
                   2747:     # If there is more than one expired role, choose the one which ended last.
                   2748:     # If there is a role which has expired, return it.
                   2749:     #
1.815     albertel 2750:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2751:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2752:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2753:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2754:         my $section=$1;
                   2755:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2756:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2757:         my $now=time;
1.548     albertel 2758:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2759:             $Expired{$end}=$section;
                   2760:             next;
                   2761:         }
1.548     albertel 2762:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2763:             $Pending{$start}=$section;
                   2764:             next;
                   2765:         }
1.599     albertel 2766:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2767:     }
                   2768:     #
                   2769:     # Presumedly there will be few matching roles from the above
                   2770:     # loop and the sorting time will be negligible.
                   2771:     if (scalar(keys(%Pending))) {
                   2772:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2773:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2774:     } 
                   2775:     if (scalar(keys(%Expired))) {
                   2776:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2777:         my $time = pop(@sorted);
1.599     albertel 2778:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2779:     }
1.599     albertel 2780:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2781: }
1.70      www      2782: 
1.599     albertel 2783: sub save_cache {
                   2784:     &purge_remembered();
1.722     albertel 2785:     #&Apache::loncommon::validate_page();
1.620     albertel 2786:     undef(%env);
1.780     albertel 2787:     undef($env_loaded);
1.599     albertel 2788: }
1.452     albertel 2789: 
1.599     albertel 2790: my $to_remember=-1;
                   2791: my %remembered;
                   2792: my %accessed;
                   2793: my $kicks=0;
                   2794: my $hits=0;
1.849     albertel 2795: sub make_key {
                   2796:     my ($name,$id) = @_;
1.872     albertel 2797:     if (length($id) > 65 
                   2798: 	&& length(&escape($id)) > 200) {
                   2799: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2800:     }
1.849     albertel 2801:     return &escape($name.':'.$id);
                   2802: }
                   2803: 
1.599     albertel 2804: sub devalidate_cache_new {
                   2805:     my ($name,$id,$debug) = @_;
                   2806:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2807:     my $remembered_id=$name.':'.$id;
1.849     albertel 2808:     $id=&make_key($name,$id);
1.599     albertel 2809:     $memcache->delete($id);
1.1172.2.81  raeburn  2810:     delete($remembered{$remembered_id});
                   2811:     delete($accessed{$remembered_id});
1.599     albertel 2812: }
                   2813: 
                   2814: sub is_cached_new {
                   2815:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2816:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2817:                                      # keys in %remembered hash, which persists for
                   2818:                                      # duration of request (no restriction on key length).
                   2819:     if (exists($remembered{$remembered_id})) {
                   2820: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2821: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2822: 	$hits++;
1.1172.2.81  raeburn  2823: 	return ($remembered{$remembered_id},1);
1.599     albertel 2824:     }
1.1172.2.81  raeburn  2825:     $id=&make_key($name,$id);
1.599     albertel 2826:     my $value = $memcache->get($id);
                   2827:     if (!(defined($value))) {
                   2828: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2829: 	return (undef,undef);
1.416     albertel 2830:     }
1.599     albertel 2831:     if ($value eq '__undef__') {
                   2832: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2833: 	$value=undef;
                   2834:     }
1.1172.2.81  raeburn  2835:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2836:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2837:     return ($value,1);
                   2838: }
                   2839: 
                   2840: sub do_cache_new {
                   2841:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2842:     my $remembered_id=$name.':'.$id;
1.849     albertel 2843:     $id=&make_key($name,$id);
1.599     albertel 2844:     my $setvalue=$value;
                   2845:     if (!defined($setvalue)) {
                   2846: 	$setvalue='__undef__';
                   2847:     }
1.623     albertel 2848:     if (!defined($time) ) {
                   2849: 	$time=600;
                   2850:     }
1.599     albertel 2851:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2852:     my $result = $memcache->set($id,$setvalue,$time);
                   2853:     if (! $result) {
1.872     albertel 2854: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2855: 	$memcache->disconnect_all();
1.872     albertel 2856:     }
1.600     albertel 2857:     # need to make a copy of $value
1.1172.2.81  raeburn  2858:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2859:     return $value;
                   2860: }
                   2861: 
                   2862: sub make_room {
1.1172.2.81  raeburn  2863:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2864: 
1.1172.2.81  raeburn  2865:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2866:                                     : $value;
1.599     albertel 2867:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2868:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2869:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2870:     my $to_kick;
                   2871:     my $max_time=0;
                   2872:     foreach my $other (keys(%accessed)) {
                   2873: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2874: 	    $to_kick=$other;
                   2875: 	    $max_time=&tv_interval($accessed{$other});
                   2876: 	}
                   2877:     }
                   2878:     delete($remembered{$to_kick});
                   2879:     delete($accessed{$to_kick});
                   2880:     $kicks++;
                   2881:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2882:     return;
                   2883: }
                   2884: 
1.599     albertel 2885: sub purge_remembered {
1.604     albertel 2886:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2887:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2888:     undef(%remembered);
                   2889:     undef(%accessed);
1.428     albertel 2890: }
1.70      www      2891: # ------------------------------------- Read an entry from a user's environment
                   2892: 
                   2893: sub userenvironment {
                   2894:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2895:     my $items;
                   2896:     foreach my $item (@what) {
                   2897:         $items.=&escape($item).'&';
                   2898:     }
                   2899:     $items=~s/\&$//;
1.70      www      2900:     my %returnhash=();
1.1009    raeburn  2901:     my $uhome = &homeserver($unam,$udom);
                   2902:     unless ($uhome eq 'no_host') {
                   2903:         my @answer=split(/\&/, 
                   2904:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2905:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2906:             return %returnhash;
                   2907:         }
1.1009    raeburn  2908:         my $i;
                   2909:         for ($i=0;$i<=$#what;$i++) {
                   2910: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2911:         }
1.70      www      2912:     }
                   2913:     return %returnhash;
1.1       albertel 2914: }
                   2915: 
1.617     albertel 2916: # ---------------------------------------------------------- Get a studentphoto
                   2917: sub studentphoto {
                   2918:     my ($udom,$unam,$ext) = @_;
                   2919:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2920:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2921:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2922:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2923:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2924:             } else {
                   2925:                 my ($result,$perm_reqd)=
1.707     albertel 2926: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2927:                 if ($result eq 'ok') {
                   2928:                     if (!($perm_reqd eq 'yes')) {
                   2929:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2930:                     }
                   2931:                 }
                   2932:             }
                   2933:         }
                   2934:     } else {
                   2935:         my ($result,$perm_reqd) = 
1.707     albertel 2936: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2937:         if ($result eq 'ok') {
                   2938:             if (!($perm_reqd eq 'yes')) {
                   2939:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2940:             }
                   2941:         }
                   2942:     }
                   2943:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2944: }
                   2945: 
                   2946: sub retrievestudentphoto {
                   2947:     my ($udom,$unam,$ext,$type) = @_;
                   2948:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2949:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2950:     if ($ret eq 'ok') {
                   2951:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2952:         if ($type eq 'thumbnail') {
                   2953:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2954:         }
                   2955:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2956:         return $tokenurl;
                   2957:     } else {
                   2958:         if ($type eq 'thumbnail') {
                   2959:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2960:         } else { 
                   2961:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2962:         }
1.617     albertel 2963:     }
                   2964: }
                   2965: 
1.263     www      2966: # -------------------------------------------------------------------- New chat
                   2967: 
                   2968: sub chatsend {
1.724     raeburn  2969:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2970:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2971:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2972:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2973:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2974: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2975: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2976: }
                   2977: 
                   2978: # ------------------------------------------ Find current version of a resource
                   2979: 
                   2980: sub getversion {
                   2981:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2982:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2983:     return &currentversion(&filelocation('',$fname));
                   2984: }
                   2985: 
                   2986: sub currentversion {
                   2987:     my $fname=shift;
                   2988:     my $author=$fname;
                   2989:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2990:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2991:     my $home=&homeserver($uname,$udom);
1.292     www      2992:     if ($home eq 'no_host') { 
                   2993:         return -1; 
                   2994:     }
1.1112    www      2995:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2996:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2997: 	return -1;
                   2998:     }
1.1112    www      2999:     return $answer;
1.263     www      3000: }
                   3001: 
1.1111    www      3002: #
                   3003: # Return special version number of resource if set by override, empty otherwise
                   3004: #
                   3005: sub usedversion {
                   3006:     my $fname=shift;
                   3007:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3008:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3009:     if ($urlversion) { return $urlversion; }
                   3010:     return '';
                   3011: }
                   3012: 
1.1       albertel 3013: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3014: 
1.1       albertel 3015: sub subscribe {
                   3016:     my $fname=shift;
1.761     raeburn  3017:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3018:     $fname=~s/[\n\r]//g;
1.1       albertel 3019:     my $author=$fname;
                   3020:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3021:     my ($udom,$uname)=split(/\//,$author);
                   3022:     my $home=homeserver($uname,$udom);
1.335     albertel 3023:     if ($home eq 'no_host') {
                   3024:         return 'not_found';
1.1       albertel 3025:     }
                   3026:     my $answer=reply("sub:$fname",$home);
1.64      www      3027:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3028: 	$answer.=' by '.$home;
                   3029:     }
1.1       albertel 3030:     return $answer;
                   3031: }
                   3032:     
1.8       www      3033: # -------------------------------------------------------------- Replicate file
                   3034: 
                   3035: sub repcopy {
                   3036:     my $filename=shift;
1.23      www      3037:     $filename=~s/\/+/\//g;
1.1142    raeburn  3038:     my $londocroot = $perlvar{'lonDocRoot'};
                   3039:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3040:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3041:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3042: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3043: 	return &repcopy_userfile($filename);
                   3044:     }
1.532     albertel 3045:     $filename=~s/[\n\r]//g;
1.8       www      3046:     my $transname="$filename.in.transfer";
1.828     www      3047: # FIXME: this should flock
1.607     raeburn  3048:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3049:     my $remoteurl=subscribe($filename);
1.64      www      3050:     if ($remoteurl =~ /^con_lost by/) {
                   3051: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3052:            return 'unavailable';
1.8       www      3053:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3054: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3055: 	   return 'not_found';
1.64      www      3056:     } elsif ($remoteurl =~ /^rejected by/) {
                   3057: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3058:            return 'forbidden';
1.20      www      3059:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3060:            return 'ok';
1.8       www      3061:     } else {
1.290     www      3062:         my $author=$filename;
                   3063:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3064:         my ($udom,$uname)=split(/\//,$author);
                   3065:         my $home=homeserver($uname,$udom);
                   3066:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3067:            my @parts=split(/\//,$filename);
                   3068:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3069:            if ($path ne "$londocroot/res") {
1.8       www      3070:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3071: 	       return 'bad_request';
1.8       www      3072:            }
                   3073:            my $count;
                   3074:            for ($count=5;$count<$#parts;$count++) {
                   3075:                $path.="/$parts[$count]";
                   3076:                if ((-e $path)!=1) {
                   3077: 		   mkdir($path,0777);
                   3078:                }
                   3079:            }
                   3080:            my $ua=new LWP::UserAgent;
                   3081:            my $request=new HTTP::Request('GET',"$remoteurl");
                   3082:            my $response=$ua->request($request,$transname);
                   3083:            if ($response->is_error()) {
                   3084: 	       unlink($transname);
                   3085:                my $message=$response->status_line;
1.672     albertel 3086:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3087:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3088:                return 'unavailable';
1.8       www      3089:            } else {
1.16      www      3090: 	       if ($remoteurl!~/\.meta$/) {
                   3091:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   3092:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   3093:                   if ($mresponse->is_error()) {
                   3094: 		      unlink($filename.'.meta');
                   3095:                       &logthis(
1.672     albertel 3096:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3097:                   }
                   3098: 	       }
1.8       www      3099:                rename($transname,$filename);
1.607     raeburn  3100:                return 'ok';
1.8       www      3101:            }
1.290     www      3102:        }
1.8       www      3103:     }
1.330     www      3104: }
                   3105: 
1.1172.2.124  raeburn  3106: # ------------------------------------------------- Unsubscribe from a resource
                   3107: 
                   3108: sub unsubscribe {
                   3109:     my ($fname) = @_;
                   3110:     my $answer;
                   3111:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3112:     $fname=~s/[\n\r]//g;
                   3113:     my $author=$fname;
                   3114:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3115:     my ($udom,$uname)=split(/\//,$author);
                   3116:     my $home=homeserver($uname,$udom);
                   3117:     if ($home eq 'no_host') {
                   3118:         $answer = 'no_host';
                   3119:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3120:         $answer = 'home';
                   3121:     } else {
1.1172.2.125  raeburn  3122:         $answer = reply("unsub:$fname",$home);
1.1172.2.124  raeburn  3123:     }
                   3124:     return $answer;
                   3125: }
                   3126: 
1.330     www      3127: # ------------------------------------------------ Get server side include body
                   3128: sub ssi_body {
1.381     albertel 3129:     my ($filelink,%form)=@_;
1.606     matthew  3130:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3131:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3132:     }
1.953     www      3133:     my $output='';
                   3134:     my $response;
1.980     raeburn  3135:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3136:        ($output,$response)=&externalssi($filelink);
1.953     www      3137:     } else {
1.1004    droeschl 3138:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3139:        $filelink .= 'inhibitmenu=yes';
1.953     www      3140:        ($output,$response)=&ssi($filelink,%form);
                   3141:     }
1.778     albertel 3142:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3143:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3144:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3145:     if (wantarray) {
                   3146:         return ($output, $response);
                   3147:     } else {
                   3148:         return $output;
                   3149:     }
1.8       www      3150: }
                   3151: 
1.15      www      3152: # --------------------------------------------------------- Server Side Include
                   3153: 
1.782     albertel 3154: sub absolute_url {
                   3155:     my ($host_name) = @_;
                   3156:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3157:     if ($host_name eq '') {
                   3158: 	$host_name = $ENV{'SERVER_NAME'};
                   3159:     }
                   3160:     return $protocol.$host_name;
                   3161: }
                   3162: 
1.942     foxr     3163: #
                   3164: #   Server side include.
                   3165: # Parameters:
                   3166: #  fn     Possibly encrypted resource name/id.
                   3167: #  form   Hash that describes how the rendering should be done
                   3168: #         and other things.
1.944     foxr     3169: # Returns:
1.950     raeburn  3170: #   Scalar context: The content of the response.
                   3171: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3172: #     
1.15      www      3173: sub ssi {
                   3174: 
1.944     foxr     3175:     my ($fn,%form)=@_;
1.1172.2.100  raeburn  3176:     my ($request,$response);
1.711     albertel 3177: 
                   3178:     $form{'no_update_last_known'}=1;
1.895     albertel 3179:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3180:     if (%form) {
1.782     albertel 3181:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  3182:       $request->content(join('&',map {
                   3183:             my $name = escape($_);
                   3184:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3185:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3186:             : &escape($form{$_}) );
                   3187:         } keys(%form)));
1.23      www      3188:     } else {
1.782     albertel 3189:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3190:     }
                   3191: 
1.15      www      3192:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3193: 
1.1172.2.101  raeburn  3194:     if (($env{'request.course.id'}) &&
                   3195:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3196:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3197:         ($form{'grade_symb'} ne '') &&
                   3198:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3199:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3200:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3201:             my $ua=new LWP::UserAgent;
                   3202:             $ua->local_address('127.0.0.1');
                   3203:             $response = $ua->request($request);
                   3204:         } else {
                   3205:             {
                   3206:                 require LWP::Protocol::http;
                   3207:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3208:                 my $ua=new LWP::UserAgent;
                   3209:                 $response = $ua->request($request);
                   3210:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3211:             }
                   3212:         }
                   3213:     } else {
                   3214:         my $ua=new LWP::UserAgent;
                   3215:         $response = $ua->request($request);
                   3216:     }
1.944     foxr     3217:     if (wantarray) {
1.1172.2.3  raeburn  3218: 	return ($response->content, $response);
1.944     foxr     3219:     } else {
1.1172.2.3  raeburn  3220: 	return $response->content;
1.942     foxr     3221:     }
1.324     www      3222: }
                   3223: 
                   3224: sub externalssi {
                   3225:     my ($url)=@_;
                   3226:     my $ua=new LWP::UserAgent;
                   3227:     my $request=new HTTP::Request('GET',$url);
                   3228:     my $response=$ua->request($request);
1.954     raeburn  3229:     if (wantarray) {
                   3230:         return ($response->content, $response);
                   3231:     } else {
                   3232:         return $response->content;
                   3233:     }
1.15      www      3234: }
1.254     www      3235: 
1.1172.2.98  raeburn  3236: # If the local copy of a replicated resource is outdated, trigger a
                   3237: # connection from the homeserver to flush the delayed queue. If no update
                   3238: # happens, remove local copies of outdated resource (and corresponding
                   3239: # metadata file).
                   3240: 
                   3241: sub remove_stale_resfile {
                   3242:     my ($url) = @_;
                   3243:     my $removed;
                   3244:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3245:         my $audom = $1;
                   3246:         my $auname = $2;
                   3247:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3248:             my $homeserver = &homeserver($auname,$audom);
                   3249:             unless (($homeserver eq 'no_host') ||
                   3250:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3251:                 my $fname = &filelocation('',$url);
                   3252:                 if (-e $fname) {
                   3253:                     my $hostname = &hostname($homeserver);
                   3254:                     if ($hostname) {
1.1172.2.120  raeburn  3255:                         my $protocol = $protocol{$homeserver};
                   3256:                         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98  raeburn  3257:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.120  raeburn  3258:                         my $ua=new LWP::UserAgent;
                   3259:                         $ua->timeout(5);
1.1172.2.98  raeburn  3260:                         my $request=new HTTP::Request('HEAD',$uri);
                   3261:                         my $response=$ua->request($request);
                   3262:                         if ($response->is_success()) {
                   3263:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3264:                             my $locmodtime = (stat($fname))[9];
                   3265:                             if ($locmodtime < $remmodtime) {
                   3266:                                 my $stale;
                   3267:                                 my $answer = &reply('pong',$homeserver);
                   3268:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3269:                                     sleep(0.2);
                   3270:                                     $locmodtime = (stat($fname))[9];
                   3271:                                     if ($locmodtime < $remmodtime) {
                   3272:                                         my $posstransfer = $fname.'.in.transfer';
                   3273:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3274:                                             $removed = 1;
                   3275:                                         } else {
                   3276:                                             $stale = 1;
                   3277:                                         }
                   3278:                                     } else {
                   3279:                                         $removed = 1;
                   3280:                                     }
                   3281:                                 } else {
                   3282:                                     $stale = 1;
                   3283:                                 }
                   3284:                                 if ($stale) {
1.1172.2.124  raeburn  3285:                                     if (unlink($fname)) {
                   3286:                                         if ($uri!~/\.meta$/) {
                   3287:                                             if (-e $fname.'.meta') {
                   3288:                                                 unlink($fname.'.meta');
                   3289:                                             }
                   3290:                                         }
                   3291:                                         my $unsubresult = &unsubscribe($fname);
                   3292:                                         unless ($unsubresult eq 'ok') {
                   3293:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3294:                                         }
                   3295:                                         $removed = 1;
1.1172.2.98  raeburn  3296:                                     }
                   3297:                                 }
                   3298:                             }
                   3299:                         }
                   3300:                     }
                   3301:                 }
                   3302:             }
                   3303:         }
                   3304:     }
                   3305:     return $removed;
                   3306: }
                   3307: 
1.492     albertel 3308: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3309: 
                   3310: sub allowuploaded {
                   3311:     my ($srcurl,$url)=@_;
                   3312:     $url=&clutter(&declutter($url));
                   3313:     my $dir=$url;
                   3314:     $dir=~s/\/[^\/]+$//;
                   3315:     my %httpref=();
                   3316:     my $httpurl=&hreflocation('',$url);
                   3317:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3318:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3319: }
1.477     raeburn  3320: 
1.1172.2.13  raeburn  3321: #
                   3322: # Determine if the current user should be able to edit a particular resource,
                   3323: # when viewing in course context.
                   3324: # (a) When viewing resource used to determine if "Edit" item is included in
                   3325: #     Functions.
                   3326: # (b) When displaying folder contents in course editor, used to determine if
                   3327: #     "Edit" link will be displayed alongside resource.
                   3328: #
                   3329: #  input: six args -- filename (decluttered), course number, course domain,
                   3330: #                   url, symb (if registered) and group (if this is a group
                   3331: #                   item -- e.g., bulletin board, group page etc.).
                   3332: #  output: array of five scalars --
                   3333: #          $cfile -- url for file editing if editable on current server
                   3334: #          $home -- homeserver of resource (i.e., for author if published,
                   3335: #                                           or course if uploaded.).
                   3336: #          $switchserver --  1 if server switch will be needed.
                   3337: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3338: #          $forceview -- 1 if icon/link should be to go to view mode
                   3339: #
                   3340: 
                   3341: sub can_edit_resource {
                   3342:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3343:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3344: #
                   3345: # For aboutme pages user can only edit his/her own.
                   3346: #
                   3347:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3348:         my ($sdom,$sname) = ($1,$2);
                   3349:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3350:             $home = $env{'user.home'};
                   3351:             $cfile = $resurl;
                   3352:             if ($env{'form.forceedit'}) {
                   3353:                 $forceview = 1;
                   3354:             } else {
                   3355:                 $forceedit = 1;
                   3356:             }
                   3357:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3358:         } else {
                   3359:             return;
                   3360:         }
                   3361:     }
                   3362: 
                   3363:     if ($env{'request.course.id'}) {
                   3364:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3365:         if ($group ne '') {
                   3366: # if this is a group homepage or group bulletin board, check group privs
                   3367:             my $allowed = 0;
                   3368:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3369:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3370:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3371:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3372:                     $allowed = 1;
                   3373:                 }
                   3374:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3375:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3376:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3377:                     $allowed = 1;
                   3378:                 }
                   3379:             }
                   3380:             if ($allowed) {
                   3381:                 $home=&homeserver($cnum,$cdom);
                   3382:                 if ($env{'form.forceedit'}) {
                   3383:                     $forceview = 1;
                   3384:                 } else {
                   3385:                     $forceedit = 1;
                   3386:                 }
                   3387:                 $cfile = $resurl;
                   3388:             } else {
                   3389:                 return;
                   3390:             }
                   3391:         } else {
1.1172.2.15  raeburn  3392:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3393:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3394:                     return;
                   3395:                 }
                   3396:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3397: #
                   3398: # No edit allowed where CC has switched to student role.
                   3399: #
                   3400:                 return;
                   3401:             }
                   3402:         }
                   3403:     }
                   3404: 
                   3405:     if ($file ne '') {
                   3406:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3407:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3408:                 $uploaded = 1;
                   3409:                 $incourse = 1;
                   3410:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3411:                     $cfile = &hreflocation('',$file);
                   3412:                     if ($env{'form.forceedit'}) {
                   3413:                         $forceview = 1;
                   3414:                     } else {
                   3415:                         $forceedit = 1;
                   3416:                     }
                   3417:                 }
                   3418:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3419:                 $incourse = 1;
                   3420:                 if ($env{'form.forceedit'}) {
                   3421:                     $forceview = 1;
                   3422:                 } else {
                   3423:                     $forceedit = 1;
                   3424:                 }
                   3425:                 $cfile = $resurl;
                   3426:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3427:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3428:                     $incourse = 1;
                   3429:                     if ($env{'form.forceedit'}) {
                   3430:                         $forceview = 1;
                   3431:                     } else {
                   3432:                         $forceedit = 1;
                   3433:                     }
                   3434:                     $cfile = $resurl;
                   3435:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3436:                     $incourse = 1;
                   3437:                     $cfile = $resurl.'/smpedit';
                   3438:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3439:                     $incourse = 1;
                   3440:                     if ($env{'form.forceedit'}) {
                   3441:                         $forceview = 1;
                   3442:                     } else {
                   3443:                         $forceedit = 1;
                   3444:                     }
                   3445:                     $cfile = $resurl;
1.1172.2.122  raeburn  3446:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3447:                     my ($map,$id,$res) = &decode_symb($symb);
                   3448:                     if ($map =~ /\.page$/) {
                   3449:                         $incourse = 1;
                   3450:                         if ($env{'form.forceedit'}) {
                   3451:                             $forceview = 1;
                   3452:                             $cfile = $map;
                   3453:                         } else {
                   3454:                             $forceedit = 1;
                   3455:                             $cfile =  '/adm/wrapper'.$resurl;
                   3456:                         }
                   3457:                     }
1.1172.2.15  raeburn  3458:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3459:                     $incourse = 1;
                   3460:                     if ($env{'form.forceedit'}) {
                   3461:                         $forceview = 1;
                   3462:                     } else {
                   3463:                         $forceedit = 1;
                   3464:                     }
                   3465:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3466:                 }
                   3467:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3468:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3469:                 if (&is_on_map($template)) {
                   3470:                     $incourse = 1;
                   3471:                     $forceview = 1;
                   3472:                     $cfile = $template;
                   3473:                 }
                   3474:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118  raeburn  3475:                 $incourse = 1;
                   3476:                 if ($env{'form.forceedit'}) {
                   3477:                     $forceview = 1;
                   3478:                 } else {
                   3479:                     $forceedit = 1;
                   3480:                 }
                   3481:                 $cfile = $resurl;
1.1172.2.13  raeburn  3482:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3483:                 $incourse = 1;
                   3484:                 $forceview = 1;
                   3485:                 if ($symb) {
                   3486:                     my ($map,$id,$res)=&decode_symb($symb);
                   3487:                     $env{'request.symb'} = $symb;
                   3488:                     $cfile = &clutter($res);
                   3489:                 } else {
                   3490:                     $cfile = $env{'form.suppurl'};
                   3491:                     $cfile =~ s{^http://}{};
                   3492:                     $cfile = '/adm/wrapper/ext/'.$cfile;
                   3493:                 }
1.1172.2.31  raeburn  3494:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3495:                 if ($env{'form.forceedit'}) {
                   3496:                     $forceview = 1;
                   3497:                 } else {
                   3498:                     $forceedit = 1;
                   3499:                 }
                   3500:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3501:             }
                   3502:         }
                   3503:         if ($uploaded || $incourse) {
                   3504:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3505:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3506:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3507:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3508:             # Check that the user has permission to edit this resource
                   3509:             my $setpriv = 1;
                   3510:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3511:             if (defined($cfudom)) {
                   3512:                 $home=&homeserver($cfuname,$cfudom);
                   3513:                 $cfile=$file;
                   3514:             }
                   3515:         }
                   3516:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3517:             (($home ne '') && ($home ne 'no_host'))) {
                   3518:             my @ids=&current_machine_ids();
                   3519:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3520:                 $switchserver=1;
                   3521:             }
                   3522:         }
                   3523:     }
                   3524:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3525: }
                   3526: 
                   3527: sub is_course_upload {
                   3528:     my ($file,$cnum,$cdom) = @_;
                   3529:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3530:     $uploadpath =~ s{^\/}{};
                   3531:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3532:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3533:         return 1;
                   3534:     }
                   3535:     return;
                   3536: }
                   3537: 
                   3538: sub in_course {
                   3539:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3540:     if ($hideprivileged) {
                   3541:         my $skipuser;
1.1172.2.23  raeburn  3542:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3543:         my @possdoms = ($cdom);
                   3544:         if ($coursehash{'checkforpriv'}) {
                   3545:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3546:         }
                   3547:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3548:             $skipuser = 1;
                   3549:             if ($coursehash{'nothideprivileged'}) {
                   3550:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3551:                     my $user;
                   3552:                     if ($item =~ /:/) {
                   3553:                         $user = $item;
                   3554:                     } else {
                   3555:                         $user = join(':',split(/[\@]/,$item));
                   3556:                     }
                   3557:                     if ($user eq $uname.':'.$udom) {
                   3558:                         undef($skipuser);
                   3559:                         last;
                   3560:                     }
                   3561:                 }
                   3562:             }
                   3563:             if ($skipuser) {
                   3564:                 return 0;
                   3565:             }
                   3566:         }
                   3567:     }
                   3568:     $type ||= 'any';
                   3569:     if (!defined($cdom) || !defined($cnum)) {
                   3570:         my $cid  = $env{'request.course.id'};
                   3571:         $cdom = $env{'course.'.$cid.'.domain'};
                   3572:         $cnum = $env{'course.'.$cid.'.num'};
                   3573:     }
                   3574:     my $typesref;
                   3575:     if (($type eq 'any') || ($type eq 'all')) {
                   3576:         $typesref = ['active','previous','future'];
                   3577:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3578:         $typesref = [$type];
                   3579:     }
                   3580:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3581:                               $typesref,undef,[$cdom]);
                   3582:     my ($tmp) = keys(%roles);
                   3583:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3584:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3585:     if (@course_roles > 0) {
                   3586:         return 1;
                   3587:     }
                   3588:     return 0;
                   3589: }
                   3590: 
1.478     albertel 3591: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3592: # input: action, courseID, current domain, intended
1.637     raeburn  3593: #        path to file, source of file, instruction to parse file for objects,
                   3594: #        ref to hash for embedded objects,
                   3595: #        ref to hash for codebase of java objects.
1.1095    raeburn  3596: #        reference to scalar to accommodate mime type determined
                   3597: #          from File::MMagic if $parser = parse.
1.637     raeburn  3598: #
1.485     raeburn  3599: # output: url to file (if action was uploaddoc), 
                   3600: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3601: #
1.478     albertel 3602: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3603: # course.
1.477     raeburn  3604: #
1.478     albertel 3605: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3606: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3607: #          course's home server.
1.477     raeburn  3608: #
1.478     albertel 3609: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3610: #          be copied from $source (current location) to 
                   3611: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3612: #         and will then be copied to
                   3613: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3614: #         course's home server.
1.485     raeburn  3615: #
1.481     raeburn  3616: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3617: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3618: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3619: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3620: #         in course's home server.
1.637     raeburn  3621: #
1.477     raeburn  3622: 
                   3623: sub process_coursefile {
1.1095    raeburn  3624:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3625:         $mimetype)=@_;
1.477     raeburn  3626:     my $fetchresult;
1.638     albertel 3627:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3628:     if ($action eq 'propagate') {
1.638     albertel 3629:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3630: 			     $home);
1.481     raeburn  3631:     } else {
1.477     raeburn  3632:         my $fpath = '';
                   3633:         my $fname = $file;
1.478     albertel 3634:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3635:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3636:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3637:         if ($action eq 'copy') {
                   3638:             if ($source eq '') {
                   3639:                 $fetchresult = 'no source file';
                   3640:                 return $fetchresult;
                   3641:             } else {
                   3642:                 my $destination = $filepath.'/'.$fname;
                   3643:                 rename($source,$destination);
                   3644:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3645:                                  $home);
1.481     raeburn  3646:             }
                   3647:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3648:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3649:             print $fh $env{'form.'.$source};
1.481     raeburn  3650:             close($fh);
1.637     raeburn  3651:             if ($parser eq 'parse') {
1.1024    raeburn  3652:                 my $mm = new File::MMagic;
1.1095    raeburn  3653:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3654:                 if ($type eq 'text/html') {
1.1024    raeburn  3655:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3656:                     unless ($parse_result eq 'ok') {
                   3657:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3658:                     }
1.637     raeburn  3659:                 }
1.1095    raeburn  3660:                 if (ref($mimetype)) {
                   3661:                     $$mimetype = $type;
                   3662:                 } 
1.637     raeburn  3663:             }
1.477     raeburn  3664:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3665:                                  $home);
1.481     raeburn  3666:             if ($fetchresult eq 'ok') {
                   3667:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3668:             } else {
                   3669:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3670:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3671:                 return '/adm/notfound.html';
                   3672:             }
1.477     raeburn  3673:         }
                   3674:     }
1.485     raeburn  3675:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3676:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3677:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3678:     }
                   3679:     return $fetchresult;
                   3680: }
                   3681: 
1.637     raeburn  3682: sub build_filepath {
                   3683:     my ($fpath) = @_;
                   3684:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3685:     unless ($fpath eq '') {
                   3686:         my @parts=split('/',$fpath);
                   3687:         foreach my $part (@parts) {
                   3688:             $filepath.= '/'.$part;
                   3689:             if ((-e $filepath)!=1) {
                   3690:                 mkdir($filepath,0777);
                   3691:             }
                   3692:         }
                   3693:     }
                   3694:     return $filepath;
                   3695: }
                   3696: 
                   3697: sub store_edited_file {
1.638     albertel 3698:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3699:     my $file = $primary_url;
                   3700:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3701:     my $fpath = '';
                   3702:     my $fname = $file;
                   3703:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3704:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3705:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3706:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3707:     print $fh $content;
                   3708:     close($fh);
1.638     albertel 3709:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3710:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3711: 			  $home);
1.637     raeburn  3712:     if ($$fetchresult eq 'ok') {
                   3713:         return '/uploaded/'.$fpath.'/'.$fname;
                   3714:     } else {
1.638     albertel 3715:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3716: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3717:         return '/adm/notfound.html';
                   3718:     }
                   3719: }
                   3720: 
1.531     albertel 3721: sub clean_filename {
1.831     albertel 3722:     my ($fname,$args)=@_;
1.315     www      3723: # Replace Windows backslashes by forward slashes
1.257     www      3724:     $fname=~s/\\/\//g;
1.831     albertel 3725:     if (!$args->{'keep_path'}) {
                   3726:         # Get rid of everything but the actual filename
                   3727: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3728:     }
1.315     www      3729: # Replace spaces by underscores
                   3730:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  3731: # Transliterate non-ascii text to ascii
                   3732:     my $lang = &Apache::lonlocal::current_language();
                   3733:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3734: # Replace all other weird characters by nothing
1.831     albertel 3735:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3736: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3737: # numbers
                   3738:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1172.2.140  raeburn  3739: # Replace three or more adjacent underscores with one for consistency
                   3740: # with loncfile::filename_check() so complete url can be extracted by
                   3741: # lonnet::decode_symb()
                   3742:     $fname=~s/_{3,}/_/g;
1.531     albertel 3743:     return $fname;
                   3744: }
1.1172.2.110  raeburn  3745: 
1.1051    raeburn  3746: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3747: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3748: # image with the same aspect ratio as the original, but with dimensions which do 
                   3749: # not exceed $resizewidth and $resizeheight.
                   3750:  
1.984     neumanie 3751: sub resizeImage {
1.1051    raeburn  3752:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3753:     my $ima = Image::Magick->new;
                   3754:     my $resized;
                   3755:     if (-e $img_path) {
                   3756:         $ima->Read($img_path);
                   3757:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3758:             my $width = $ima->Get('width');
                   3759:             my $height = $ima->Get('height');
                   3760:             if ($width > $resizewidth) {
                   3761: 	        my $factor = $width/$resizewidth;
                   3762:                 my $newheight = $height/$factor;
                   3763:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3764:                 $resized = 1;
                   3765:             }
                   3766:         }
                   3767:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3768:             my $width = $ima->Get('width');
                   3769:             my $height = $ima->Get('height');
                   3770:             if ($height > $resizeheight) {
                   3771:                 my $factor = $height/$resizeheight;
                   3772:                 my $newwidth = $width/$factor;
                   3773:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3774:                 $resized = 1;
                   3775:             }
                   3776:         }
                   3777:         if ($resized) {
                   3778:             $ima->Write($img_path);
                   3779:         }
                   3780:     }
                   3781:     return;
1.977     amueller 3782: }
                   3783: 
1.608     albertel 3784: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3785: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3786: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3787: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.109  raeburn  3788: #                                    canceloverwrite, scantron or ''. 
1.1090    raeburn  3789: #                   if 'coursedoc': upload to the current course
                   3790: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3791: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3792: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3793: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  3794: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3795: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3796: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   3797: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3798: #        $allfiles - reference to hash for embedded objects
                   3799: #        $codebase - reference to hash for codebase of java objects
                   3800: #        $desuname - username for permanent storage of uploaded file
                   3801: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3802: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3803: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3804: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3805: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3806: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3807: #                    from File::MMagic.
1.858     raeburn  3808: # 
1.686     albertel 3809: # output: url of file in userspace, or error: <message> 
                   3810: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3811: 
1.531     albertel 3812: sub userfileupload {
1.1090    raeburn  3813:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3814:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3815:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3816:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3817:     $fname=&clean_filename($fname);
1.1090    raeburn  3818:     # See if there is anything left
1.257     www      3819:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  3820:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   3821:     if ($fname =~ /^\./) {
                   3822:         my ($s,$usec) = &gettimeofday();
                   3823:         while (length($usec) < 6) {
                   3824:             $usec = '0'.$usec;
                   3825:         }
                   3826:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   3827:     }
1.1090    raeburn  3828:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3829:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3830:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3831:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3832:         my $now = time;
1.1090    raeburn  3833:         my $filepath;
1.1095    raeburn  3834:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3835:              $filepath = 'tmp/helprequests/'.$now;
                   3836:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3837:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3838:                          '_'.$env{'user.domain'}.'/pending';
                   3839:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3840:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3841:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3842:                 $docudom = $destudom;
                   3843:             } else {
                   3844:                 $docudom = $env{'user.domain'};
                   3845:             }
1.1172.2.96  raeburn  3846:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3847:                 $docuname = $destuname;
                   3848:             } else {
                   3849:                 $docuname = $env{'user.name'};
                   3850:             }
                   3851:             if (exists($env{'form.group'})) {
                   3852:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3853:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3854:             }
                   3855:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3856:             if ($context eq 'canceloverwrite') {
                   3857:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3858:                 if (-e  $tempfile) {
                   3859:                     my @info = stat($tempfile);
                   3860:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3861:                         unlink($tempfile);
                   3862:                     }
                   3863:                 }
                   3864:                 return;
1.523     raeburn  3865:             }
                   3866:         }
1.1090    raeburn  3867:         # Create the directory if not present
1.741     raeburn  3868:         my @parts=split(/\//,$filepath);
                   3869:         my $fullpath = $perlvar{'lonDaemons'};
                   3870:         for (my $i=0;$i<@parts;$i++) {
                   3871:             $fullpath .= '/'.$parts[$i];
                   3872:             if ((-e $fullpath)!=1) {
                   3873:                 mkdir($fullpath,0777);
                   3874:             }
                   3875:         }
1.1172.2.96  raeburn  3876:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3877:         print $fh $env{'form.'.$formname};
                   3878:         close($fh);
1.1090    raeburn  3879:         if ($context eq 'existingfile') {
                   3880:             my @info = stat($fullpath.'/'.$fname);
                   3881:             return ($fullpath.'/'.$fname,$info[9]);
                   3882:         } else {
                   3883:             return $fullpath.'/'.$fname;
                   3884:         }
1.523     raeburn  3885:     }
1.995     raeburn  3886:     if ($subdir eq 'scantron') {
                   3887:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3888:     } else {
1.995     raeburn  3889:         $fname="$subdir/$fname";
                   3890:     }
1.1090    raeburn  3891:     if ($context eq 'coursedoc') {
1.638     albertel 3892: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3893: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3894:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3895:             return &finishuserfileupload($docuname,$docudom,
                   3896: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3897: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3898:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3899:         } else {
1.1172.2.21  raeburn  3900:             if ($env{'form.folder'}) {
                   3901:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3902:             }
1.638     albertel 3903:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3904: 				       $fname,$formname,$parser,
1.1095    raeburn  3905: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3906:         }
1.719     banghart 3907:     } elsif (defined($destuname)) {
                   3908:         my $docuname=$destuname;
                   3909:         my $docudom=$destudom;
1.860     raeburn  3910: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3911: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3912:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3913:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3914:     } else {
1.638     albertel 3915:         my $docuname=$env{'user.name'};
                   3916:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3917:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3918:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3919:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3920:         }
1.860     raeburn  3921: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3922: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3923:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3924:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3925:     }
1.271     www      3926: }
                   3927: 
                   3928: sub finishuserfileupload {
1.860     raeburn  3929:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3930:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3931:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3932:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3933:   
1.860     raeburn  3934:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3935:     $file=$fname;
                   3936:     if ($fname=~m|/|) {
                   3937:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3938: 	$path.=$fnamepath.'/';
                   3939:     }
1.259     www      3940:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3941:     my $count;
                   3942:     for ($count=4;$count<=$#parts;$count++) {
                   3943:         $filepath.="/$parts[$count]";
                   3944:         if ((-e $filepath)!=1) {
                   3945: 	    mkdir($filepath,0777);
                   3946:         }
                   3947:     }
1.984     neumanie 3948: 
1.258     www      3949: # Save the file
                   3950:     {
1.1172.2.96  raeburn  3951: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3952: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3953: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3954: 	    return '/adm/notfound.html';
                   3955: 	}
1.1090    raeburn  3956:         if ($context eq 'overwrite') {
1.1117    foxr     3957:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3958:             my $target = $filepath.'/'.$file;
                   3959:             if (-e $source) {
                   3960:                 my @info = stat($source);
                   3961:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3962:                     unless (&File::Copy::move($source,$target)) {
                   3963:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3964:                         return "Moving from $source failed";
                   3965:                     }
                   3966:                 } else {
                   3967:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3968:                 }
                   3969:             } else {
                   3970:                 return "Temporary file: $source missing";
                   3971:             }
                   3972:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3973: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3974: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3975: 	    return '/adm/notfound.html';
                   3976: 	}
1.570     albertel 3977: 	close(FH);
1.1051    raeburn  3978:         if ($resizewidth && $resizeheight) {
                   3979:             my $mm = new File::MMagic;
                   3980:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3981:             if ($mime_type =~ m{^image/}) {
                   3982: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3983:             }  
1.977     amueller 3984: 	}
1.258     www      3985:     }
1.1152    raeburn  3986:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3987:         if (ref($mimetype)) {
                   3988:             if ($$mimetype eq '') {
                   3989:                 my $mm = new File::MMagic;
                   3990:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3991:                 $$mimetype = $type;
                   3992:             }
                   3993:         }
                   3994:     }
1.1172.2.109  raeburn  3995:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  3996:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3997:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3998:                                                        $allfiles,$codebase);
                   3999:             unless ($parse_result eq 'ok') {
                   4000:                 &logthis('Failed to parse '.$filepath.$file.
                   4001: 	   	         ' for embedded media: '.$parse_result); 
                   4002:             }
1.637     raeburn  4003:         }
1.1172.2.109  raeburn  4004:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4005:         my $format = $env{'form.scantron_format'};
                   4006:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4007:     }
1.860     raeburn  4008:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4009:         my $input = $filepath.'/'.$file;
                   4010:         my $output = $filepath.'/'.'tn-'.$file;
                   4011:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  4012:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4013:         system({$args[0]} @args);
1.860     raeburn  4014:         if (-e $filepath.'/'.'tn-'.$file) {
                   4015:             $fetchthumb  = 1; 
                   4016:         }
                   4017:     }
1.858     raeburn  4018:  
1.259     www      4019: # Notify homeserver to grep it
                   4020: #
1.984     neumanie 4021:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4022:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4023:     if ($fetchresult eq 'ok') {
1.860     raeburn  4024:         if ($fetchthumb) {
                   4025:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4026:             if ($thumbresult ne 'ok') {
                   4027:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4028:                          $docuhome.': '.$thumbresult);
                   4029:             }
                   4030:         }
1.259     www      4031: #
1.258     www      4032: # Return the URL to it
1.494     albertel 4033:         return '/uploaded/'.$path.$file;
1.263     www      4034:     } else {
1.494     albertel 4035:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4036: 		 ': '.$fetchresult);
1.263     www      4037:         return '/adm/notfound.html';
1.858     raeburn  4038:     }
1.493     albertel 4039: }
                   4040: 
1.637     raeburn  4041: sub extract_embedded_items {
1.961     raeburn  4042:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4043:     my @state = ();
1.1164    raeburn  4044:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4045:     my %javafiles = (
                   4046:                       codebase => '',
                   4047:                       code => '',
                   4048:                       archive => ''
                   4049:                     );
                   4050:     my %mediafiles = (
                   4051:                       src => '',
                   4052:                       movie => '',
                   4053:                      );
1.648     raeburn  4054:     my $p;
                   4055:     if ($content) {
                   4056:         $p = HTML::LCParser->new($content);
                   4057:     } else {
1.961     raeburn  4058:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4059:     }
1.641     albertel 4060:     while (my $t=$p->get_token()) {
1.640     albertel 4061: 	if ($t->[0] eq 'S') {
                   4062: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4063: 	    push(@state, $tagname);
1.648     raeburn  4064:             if (lc($tagname) eq 'allow') {
                   4065:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4066:             }
1.640     albertel 4067: 	    if (lc($tagname) eq 'img') {
                   4068: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4069: 	    }
1.886     albertel 4070: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  4071:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   4072: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   4073:                 }
1.886     albertel 4074: 	    }
1.645     raeburn  4075:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4076:                 my $src;
1.645     raeburn  4077:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4078:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4079:                 } else {
1.1164    raeburn  4080:                     if ($attr->{'src'} ne '') {
                   4081:                         $src = $attr->{'src'};
                   4082:                         &add_filetype($allfiles,$src,'src');
                   4083:                     }
                   4084:                 }
                   4085:                 my $text = $p->get_trimmed_text();
                   4086:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4087:                     my @swfargs = split(/,/,$1);
                   4088:                     foreach my $item (@swfargs) {
                   4089:                         $item =~ s/["']//g;
                   4090:                         $item =~ s/^\s+//;
                   4091:                         $item =~ s/\s+$//;
                   4092:                     }
                   4093:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4094:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4095:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4096:                         } else {
                   4097:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4098:                         }
                   4099:                     }
1.645     raeburn  4100:                 }
                   4101:             }
                   4102:             if (lc($tagname) eq 'link') {
                   4103:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4104:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4105:                 }
                   4106:             }
1.640     albertel 4107: 	    if (lc($tagname) eq 'object' ||
                   4108: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4109: 		foreach my $item (keys(%javafiles)) {
                   4110: 		    $javafiles{$item} = '';
                   4111: 		}
1.1164    raeburn  4112:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4113:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4114:                 }
1.640     albertel 4115: 	    }
                   4116: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4117: 		my $name = lc($attr->{'name'});
                   4118: 		foreach my $item (keys(%javafiles)) {
                   4119: 		    if ($name eq $item) {
                   4120: 			$javafiles{$item} = $attr->{'value'};
                   4121: 			last;
                   4122: 		    }
                   4123: 		}
1.1164    raeburn  4124:                 my $pathfrom;
1.640     albertel 4125: 		foreach my $item (keys(%mediafiles)) {
                   4126: 		    if ($name eq $item) {
1.1164    raeburn  4127:                         $pathfrom = $attr->{'value'};
                   4128:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4129: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4130: 			last;
                   4131: 		    }
                   4132: 		}
1.1164    raeburn  4133:                 if ($name eq 'flashvars') {
                   4134:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4135:                 }
                   4136:                 if ($pathfrom ne '') {
                   4137:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4138:                                          $pathfrom);
                   4139:                 }
1.640     albertel 4140: 	    }
                   4141: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4142: 		foreach my $item (keys(%javafiles)) {
                   4143: 		    if ($attr->{$item}) {
                   4144: 			$javafiles{$item} = $attr->{$item};
                   4145: 			last;
                   4146: 		    }
                   4147: 		}
                   4148: 		foreach my $item (keys(%mediafiles)) {
                   4149: 		    if ($attr->{$item}) {
                   4150: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4151: 			last;
                   4152: 		    }
                   4153: 		}
1.1164    raeburn  4154:                 if (lc($tagname) eq 'embed') {
                   4155:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4156:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4157:                                              $attr->{'src'});
                   4158:                     }
                   4159:                 }
1.640     albertel 4160: 	    }
1.1172.2.35  raeburn  4161:             if (lc($tagname) eq 'iframe') {
                   4162:                 my $src = $attr->{'src'} ;
                   4163:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4164:                     &add_filetype($allfiles,$src,'src');
                   4165:                 } elsif ($src =~ m{^/}) {
                   4166:                     if ($env{'request.course.id'}) {
                   4167:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4168:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4169:                         my $url = &hreflocation('',$fullpath);
                   4170:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4171:                             my $relpath = $1;
                   4172:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4173:                                 &add_filetype($allfiles,$1,'src');
                   4174:                             }
                   4175:                         }
                   4176:                     }
                   4177:                 }
                   4178:             }
1.1164    raeburn  4179:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4180:                 pop(@state);
1.1164    raeburn  4181:             }
1.640     albertel 4182: 	} elsif ($t->[0] eq 'E') {
                   4183: 	    my ($tagname) = ($t->[1]);
                   4184: 	    if ($javafiles{'codebase'} ne '') {
                   4185: 		$javafiles{'codebase'} .= '/';
                   4186: 	    }  
                   4187: 	    if (lc($tagname) eq 'applet' ||
                   4188: 		lc($tagname) eq 'object' ||
                   4189: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4190: 		) {
                   4191: 		foreach my $item (keys(%javafiles)) {
                   4192: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4193: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4194: 			&add_filetype($allfiles,$file,$item);
                   4195: 		    }
                   4196: 		}
                   4197: 	    } 
                   4198: 	    pop @state;
                   4199: 	}
                   4200:     }
1.1164    raeburn  4201:     foreach my $id (sort(keys(%flashvars))) {
                   4202:         if ($shockwave{$id} ne '') {
                   4203:             my @pairs = split(/\&/,$flashvars{$id});
                   4204:             foreach my $pair (@pairs) {
                   4205:                 my ($key,$value) = split(/\=/,$pair);
                   4206:                 if ($key eq 'thumb') {
                   4207:                     &add_filetype($allfiles,$value,$key);
                   4208:                 } elsif ($key eq 'content') {
                   4209:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4210:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4211:                     if ($ext ne '') {
                   4212:                         &add_filetype($allfiles,$path.$value,$ext);
                   4213:                     }
                   4214:                 }
                   4215:             }
                   4216:         }
                   4217:     }
1.637     raeburn  4218:     return 'ok';
                   4219: }
                   4220: 
1.639     albertel 4221: sub add_filetype {
                   4222:     my ($allfiles,$file,$type)=@_;
                   4223:     if (exists($allfiles->{$file})) {
                   4224: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4225: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4226: 	}
                   4227:     } else {
                   4228: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4229:     }
                   4230: }
                   4231: 
1.1164    raeburn  4232: sub embedded_dependency {
                   4233:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4234:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4235:         if (($identifier ne '') &&
                   4236:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4237:             ($pathfrom ne '')) {
                   4238:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4239:             foreach my $dep (@{$related->{$identifier}}) {
                   4240:                 &add_filetype($allfiles,$path.$dep,'object');
                   4241:             }
                   4242:         }
                   4243:     }
                   4244:     return;
                   4245: }
                   4246: 
1.1172.2.109  raeburn  4247: sub bubblesheet_converter {
                   4248:     my ($cdom,$fullpath,$config,$format) = @_;
                   4249:     if ((&domain($cdom) ne '') &&
                   4250:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4251:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4252:         my (%csvcols,%csvoptions);
                   4253:         if (ref($config->{'fields'}) eq 'HASH') {
                   4254:             %csvcols = %{$config->{'fields'}};
                   4255:         }
                   4256:         if (ref($config->{'options'}) eq 'HASH') {
                   4257:             %csvoptions = %{$config->{'options'}};
                   4258:         }
                   4259:         my %csvbynum = reverse(%csvcols);
                   4260:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4261:         if (keys(%scantronconf)) {
                   4262:             my %bynum = (
                   4263:                           $scantronconf{CODEstart} => 'CODEstart',
                   4264:                           $scantronconf{IDstart}   => 'IDstart',
                   4265:                           $scantronconf{PaperID}   => 'PaperID',
                   4266:                           $scantronconf{FirstName} => 'FirstName',
                   4267:                           $scantronconf{LastName}  => 'LastName',
                   4268:                           $scantronconf{Qstart}    => 'Qstart',
                   4269:                         );
                   4270:             my @ordered;
                   4271:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4272:                 push(@ordered,$bynum{$item});
                   4273:             }
                   4274:             my %mapstart = (
                   4275:                               CODEstart => 'CODE',
                   4276:                               IDstart   => 'ID',
                   4277:                               PaperID   => 'PaperID',
                   4278:                               FirstName => 'FirstName',
                   4279:                               LastName  => 'LastName',
                   4280:                               Qstart    => 'FirstQuestion',
                   4281:                            );
                   4282:             my %maplength = (
                   4283:                               CODEstart => 'CODElength',
                   4284:                               IDstart   => 'IDlength',
                   4285:                               PaperID   => 'PaperIDlength',
                   4286:                               FirstName => 'FirstNamelength',
                   4287:                               LastName  => 'LastNamelength',
                   4288:             );
                   4289:             if (open(my $fh,'<',$fullpath)) {
                   4290:                 my $output;
                   4291:                 my %lettdig = &letter_to_digits();
                   4292:                 my %diglett = reverse(%lettdig);
                   4293:                 my $numletts = scalar(keys(%lettdig));
                   4294:                 my $num = 0;
                   4295:                 while (my $line=<$fh>) {
                   4296:                     $num ++;
                   4297:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4298:                     $line =~ s{[\r\n]+$}{};
                   4299:                     my %found;
                   4300:                     my @values = split(/,/,$line);
                   4301:                     my ($qstart,$record);
                   4302:                     for (my $i=0; $i<@values; $i++) {
                   4303:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4304:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4305:                             if ($values[$i] eq '') {
                   4306:                                 $values[$i] = $scantronconf{'Qoff'};
                   4307:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4308:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4309:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4310:                                 }
                   4311:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4312:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4313:                                     $values[$i] = $diglett{$values[$i]};
                   4314:                                 }
                   4315:                             } else {
                   4316:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4317:                                     my $digit;
                   4318:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4319:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4320:                                         if ($values[$i] eq 'J') {
                   4321:                                             $digit += $numletts;
                   4322:                                         }
                   4323:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4324:                                         $digit = $values[$i]-1;
                   4325:                                         if ($values[$i] eq '0') {
                   4326:                                             $digit += $numletts;
                   4327:                                         }
                   4328:                                     }
                   4329:                                     my $qval='';
                   4330:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4331:                                         if ($j == $digit) {
                   4332:                                             $qval .= $scantronconf{'Qon'};
                   4333:                                         } else {
                   4334:                                             $qval .= $scantronconf{'Qoff'};
                   4335:                                         }
                   4336:                                     }
                   4337:                                     $values[$i] = $qval;
                   4338:                                 }
                   4339:                             }
                   4340:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4341:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4342:                             }
                   4343:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4344:                             if ($numblank > 0) {
                   4345:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4346:                             }
                   4347:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4348:                                 $qstart = $i;
                   4349:                                 $found{$csvbynum{$i}} = $values[$i];
                   4350:                             } else {
                   4351:                                 $found{'FirstQuestion'} .= $values[$i];
                   4352:                             }
                   4353:                         } elsif (exists($csvbynum{$i})) {
                   4354:                             if ($csvoptions{'rem'}) {
                   4355:                                 $values[$i] =~ s/^\s+//;
                   4356:                             }
                   4357:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4358:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4359:                                     $values[$i] = '0'.$values[$i];
                   4360:                                 }
                   4361:                             }
                   4362:                             $found{$csvbynum{$i}} = $values[$i];
                   4363:                         }
                   4364:                     }
                   4365:                     foreach my $item (@ordered) {
                   4366:                         my $currlength = 1+length($record);
                   4367:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4368:                         if ($numspaces > 0) {
                   4369:                             $record .= (' ' x $numspaces);
                   4370:                         }
                   4371:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4372:                             unless ($item eq 'Qstart') {
                   4373:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4374:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4375:                                 }
                   4376:                             }
                   4377:                             $record .= $found{$mapstart{$item}};
                   4378:                         }
                   4379:                     }
                   4380:                     $output .= "$record\n";
                   4381:                 }
                   4382:                 close($fh);
                   4383:                 if ($output) {
                   4384:                     if (open(my $fh,'>',$fullpath)) {
                   4385:                         print $fh $output;
                   4386:                         close($fh);
                   4387:                     }
                   4388:                 }
                   4389:             }
                   4390:         }
                   4391:         return;
                   4392:     }
                   4393: }
                   4394: 
                   4395: sub letter_to_digits {
                   4396:     my %lettdig = (
                   4397:                     A => 1,
                   4398:                     B => 2,
                   4399:                     C => 3,
                   4400:                     D => 4,
                   4401:                     E => 5,
                   4402:                     F => 6,
                   4403:                     G => 7,
                   4404:                     H => 8,
                   4405:                     I => 9,
                   4406:                     J => 0,
                   4407:                   );
                   4408:     return %lettdig;
                   4409: }
                   4410: 
                   4411: sub get_scantron_config {
                   4412:     my ($which,$cdom) = @_;
                   4413:     my @lines = &get_scantronformat_file($cdom);
                   4414:     my %config;
                   4415:     #FIXME probably should move to XML it has already gotten a bit much now
                   4416:     foreach my $line (@lines) {
                   4417:         my ($name,$descrip)=split(/:/,$line);
                   4418:         if ($name ne $which ) { next; }
                   4419:         chomp($line);
                   4420:         my @config=split(/:/,$line);
                   4421:         $config{'name'}=$config[0];
                   4422:         $config{'description'}=$config[1];
                   4423:         $config{'CODElocation'}=$config[2];
                   4424:         $config{'CODEstart'}=$config[3];
                   4425:         $config{'CODElength'}=$config[4];
                   4426:         $config{'IDstart'}=$config[5];
                   4427:         $config{'IDlength'}=$config[6];
                   4428:         $config{'Qstart'}=$config[7];
                   4429:         $config{'Qlength'}=$config[8];
                   4430:         $config{'Qoff'}=$config[9];
                   4431:         $config{'Qon'}=$config[10];
                   4432:         $config{'PaperID'}=$config[11];
                   4433:         $config{'PaperIDlength'}=$config[12];
                   4434:         $config{'FirstName'}=$config[13];
                   4435:         $config{'FirstNamelength'}=$config[14];
                   4436:         $config{'LastName'}=$config[15];
                   4437:         $config{'LastNamelength'}=$config[16];
                   4438:         $config{'BubblesPerRow'}=$config[17];
                   4439:         last;
                   4440:     }
                   4441:     return %config;
                   4442: }
                   4443: 
                   4444: sub get_scantronformat_file {
                   4445:     my ($cdom) = @_;
                   4446:     if ($cdom eq '') {
                   4447:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4448:     }
                   4449:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4450:     my $gottab = 0;
                   4451:     my @lines;
                   4452:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4453:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4454:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4455:             if ($formatfile ne '-1') {
                   4456:                 @lines = split("\n",$formatfile,-1);
                   4457:                 $gottab = 1;
                   4458:             }
                   4459:         }
                   4460:     }
                   4461:     if (!$gottab) {
                   4462:         my $confname = $cdom.'-domainconfig';
                   4463:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4464:         my $formatfile = &getfile($default);
                   4465:         if ($formatfile ne '-1') {
                   4466:             @lines = split("\n",$formatfile,-1);
                   4467:             $gottab = 1;
                   4468:         }
                   4469:     }
                   4470:     if (!$gottab) {
                   4471:         my @domains = &current_machine_domains();
                   4472:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4473:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4474:                 @lines = <$fh>;
                   4475:                 close($fh);
                   4476:             }
                   4477:         } else {
                   4478:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4479:                 @lines = <$fh>;
                   4480:                 close($fh);
                   4481:             }
                   4482:         }
                   4483:     }
                   4484:     return @lines;
                   4485: }
                   4486: 
1.493     albertel 4487: sub removeuploadedurl {
1.984     neumanie 4488:     my ($url)=@_;	
                   4489:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4490:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4491: }
                   4492: 
                   4493: sub removeuserfile {
                   4494:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4495:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4496:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4497:     if ($result eq 'ok') {	
1.798     raeburn  4498:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4499:             my $metafile = $fname.'.meta';
                   4500:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4501: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4502:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4503:             my $sqlresult = 
1.823     albertel 4504:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4505:                                         'portfolio_metadata',$group,
                   4506:                                         'delete');
1.798     raeburn  4507:         }
                   4508:     }
                   4509:     return $result;
1.257     www      4510: }
1.15      www      4511: 
1.530     albertel 4512: sub mkdiruserfile {
                   4513:     my ($docuname,$docudom,$dir)=@_;
                   4514:     my $home=&homeserver($docuname,$docudom);
                   4515:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4516: }
                   4517: 
1.531     albertel 4518: sub renameuserfile {
                   4519:     my ($docuname,$docudom,$old,$new)=@_;
                   4520:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4521:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4522:                         &escape("$old").':'.&escape("$new"),$home);
                   4523:     if ($result eq 'ok') {
                   4524:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4525:             my $oldmeta = $old.'.meta';
                   4526:             my $newmeta = $new.'.meta';
                   4527:             my $metaresult = 
                   4528:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4529: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4530:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4531:             my $sqlresult = 
1.823     albertel 4532:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4533:                                         'portfolio_metadata',$group,
                   4534:                                         'delete');
1.798     raeburn  4535:         }
                   4536:     }
                   4537:     return $result;
1.531     albertel 4538: }
                   4539: 
1.14      www      4540: # ------------------------------------------------------------------------- Log
                   4541: 
                   4542: sub log {
                   4543:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4544:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4545: }
                   4546: 
                   4547: # ------------------------------------------------------------------ Course Log
1.352     www      4548: #
                   4549: # This routine flushes several buffers of non-mission-critical nature
                   4550: #
1.157     www      4551: 
                   4552: sub flushcourselogs {
1.352     www      4553:     &logthis('Flushing log buffers');
                   4554: #
                   4555: # course logs
                   4556: # This is a log of all transactions in a course, which can be used
                   4557: # for data mining purposes
                   4558: #
                   4559: # It also collects the courseid database, which lists last transaction
                   4560: # times and course titles for all courseids
                   4561: #
                   4562:     my %courseidbuffer=();
1.921     raeburn  4563:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4564:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4565: 		          &escape($courselogs{$crsid}),
                   4566: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4567: 	    delete $courselogs{$crsid};
                   4568:         } else {
                   4569:             &logthis('Failed to flush log buffer for '.$crsid);
                   4570:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4571:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4572:                         " exceeded maximum size, deleting.</font>");
                   4573:                delete $courselogs{$crsid};
                   4574:             }
1.352     www      4575:         }
1.920     raeburn  4576:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4577:             'description' => $coursedescrbuf{$crsid},
                   4578:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4579:             'type'        => $coursetypebuf{$crsid},
                   4580:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4581:         };
1.191     harris41 4582:     }
1.352     www      4583: #
                   4584: # Write course id database (reverse lookup) to homeserver of courses 
                   4585: # Is used in pickcourse
                   4586: #
1.840     albertel 4587:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4588:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4589:                                     $courseidbuffer{$crs_home},
                   4590:                                     $crs_home,'timeonly');
1.352     www      4591:     }
                   4592: #
                   4593: # File accesses
                   4594: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4595: #
1.449     matthew  4596:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4597:         if ($entry =~ /___count$/) {
                   4598:             my ($dom,$name);
1.807     albertel 4599:             ($dom,$name,undef)=
1.811     albertel 4600: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4601:             if (! defined($dom) || $dom eq '' || 
                   4602:                 ! defined($name) || $name eq '') {
1.620     albertel 4603:                 my $cid = $env{'request.course.id'};
                   4604:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4605:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4606:             }
1.450     matthew  4607:             my $value = $accesshash{$entry};
                   4608:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4609:             my %temphash=($url => $value);
1.449     matthew  4610:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4611:             if ($result eq 'ok') {
                   4612:                 delete $accesshash{$entry};
                   4613:             }
                   4614:         } else {
1.811     albertel 4615:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4616:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4617:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4618:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4619:                 delete $accesshash{$entry};
                   4620:             }
1.185     www      4621:         }
1.191     harris41 4622:     }
1.352     www      4623: #
                   4624: # Roles
                   4625: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4626: #
1.800     albertel 4627:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4628:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4629: 	    split(/\:/,$entry);
                   4630:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4631:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4632:                 $rudom,$runame) eq 'ok') {
                   4633: 	    delete $userrolehash{$entry};
                   4634:         }
                   4635:     }
1.662     raeburn  4636: #
1.1172.2.90  raeburn  4637: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4638: #
                   4639:     my %domrolebuffer = ();
1.1000    raeburn  4640:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4641:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4642:         if ($domrolebuffer{$rudom}) {
                   4643:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4644:                       '='.&escape($domainrolehash{$entry});
                   4645:         } else {
                   4646:             $domrolebuffer{$rudom}.=&escape($entry).
                   4647:                       '='.&escape($domainrolehash{$entry});
                   4648:         }
                   4649:         delete $domainrolehash{$entry};
                   4650:     }
                   4651:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4652:         my %servers;
                   4653:         if (defined(&domain($dom,'primary'))) {
                   4654:             my $primary=&domain($dom,'primary');
                   4655:             my $hostname=&hostname($primary);
                   4656:             $servers{$primary} = $hostname;
                   4657:         } else {
                   4658:             %servers = &get_servers($dom,'library');
                   4659:         }
1.841     albertel 4660: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4661: 	    if (&reply('domroleput:'.$dom.':'.
                   4662: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4663: 	        last;
                   4664: 	    } else {
1.841     albertel 4665: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4666: 	    }
1.662     raeburn  4667:         }
                   4668:     }
1.186     www      4669:     $dumpcount++;
1.157     www      4670: }
                   4671: 
                   4672: sub courselog {
                   4673:     my $what=shift;
1.158     www      4674:     $what=time.':'.$what;
1.620     albertel 4675:     unless ($env{'request.course.id'}) { return ''; }
                   4676:     $coursedombuf{$env{'request.course.id'}}=
                   4677:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4678:     $coursenumbuf{$env{'request.course.id'}}=
                   4679:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4680:     $coursehombuf{$env{'request.course.id'}}=
                   4681:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4682:     $coursedescrbuf{$env{'request.course.id'}}=
                   4683:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4684:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4685:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4686:     $courseownerbuf{$env{'request.course.id'}}=
                   4687:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4688:     $coursetypebuf{$env{'request.course.id'}}=
                   4689:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4690:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4691: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4692:     } else {
1.620     albertel 4693: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4694:     }
1.620     albertel 4695:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4696: 	&flushcourselogs();
                   4697:     }
1.158     www      4698: }
                   4699: 
                   4700: sub courseacclog {
                   4701:     my $fnsymb=shift;
1.620     albertel 4702:     unless ($env{'request.course.id'}) { return ''; }
                   4703:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4704:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4705:         $what.=':POST';
1.583     matthew  4706:         # FIXME: Probably ought to escape things....
1.800     albertel 4707: 	foreach my $key (keys(%env)) {
                   4708:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4709:                 my $formitem = $1;
                   4710:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4711:                     $what.=':'.$formitem.'='.$env{$key};
                   4712:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.131  raeburn  4713:                     if ($formitem eq 'proctorpassword') {
1.1172.2.132  raeburn  4714:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1172.2.131  raeburn  4715:                     } else {
                   4716:                         $what.=':'.$formitem.'='.$env{$key};
                   4717:                     }
1.975     raeburn  4718:                 }
1.158     www      4719:             }
1.191     harris41 4720:         }
1.583     matthew  4721:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4722:         # FIXME: We should not be depending on a form parameter that someone
                   4723:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4724:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4725:             $what.= ':POST';
                   4726:             # FIXME: Probably ought to escape things....
                   4727:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4728:                                  'crsdiscuss') {
1.620     albertel 4729:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4730:             }
                   4731:         }
1.158     www      4732:     }
                   4733:     &courselog($what);
1.149     www      4734: }
                   4735: 
1.185     www      4736: sub countacc {
                   4737:     my $url=&declutter(shift);
1.458     matthew  4738:     return if (! defined($url) || $url eq '');
1.620     albertel 4739:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4740: #
                   4741: # Mark that this url was used in this course
                   4742: #
1.620     albertel 4743:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4744: #
                   4745: # Increase the access count for this resource in this child process
                   4746: #
1.281     www      4747:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4748:     $accesshash{$key}++;
1.185     www      4749: }
1.349     www      4750: 
1.361     www      4751: sub linklog {
                   4752:     my ($from,$to)=@_;
                   4753:     $from=&declutter($from);
                   4754:     $to=&declutter($to);
                   4755:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4756:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4757: }
1.1160    www      4758: 
                   4759: sub statslog {
                   4760:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4761:     if ($users<2) { return; }
                   4762:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4763:             'course'       => $env{'request.course.id'},
                   4764:             'sections'     => '"all"',
                   4765:             'num_students' => $users,
                   4766:             'part'         => $part,
                   4767:             'symb'         => $symb,
                   4768:             'mean_tries'   => $av_attempts,
                   4769:             'deg_of_diff'  => $degdiff});
                   4770:     foreach my $key (keys(%dynstore)) {
                   4771:         $accesshash{$key}=$dynstore{$key};
                   4772:     }
                   4773: }
1.361     www      4774:   
1.349     www      4775: sub userrolelog {
                   4776:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4777:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4778:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4779:        $userrolehash
                   4780:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4781:                     =$tend.':'.$tstart;
1.662     raeburn  4782:     }
1.1169    droeschl 4783:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4784:        $userrolehash
                   4785:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4786:                     =$tend.':'.$tstart;
                   4787:     }
1.1172.2.90  raeburn  4788:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4789:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4790:        $domainrolehash
                   4791:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4792:                     = $tend.':'.$tstart;
                   4793:     }
1.351     www      4794: }
                   4795: 
1.957     raeburn  4796: sub courserolelog {
                   4797:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4798:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4799:         my $cdom = $1;
                   4800:         my $cnum = $2;
                   4801:         my $sec = $3;
                   4802:         my $namespace = 'rolelog';
                   4803:         my %storehash = (
                   4804:                            role    => $trole,
                   4805:                            start   => $tstart,
                   4806:                            end     => $tend,
                   4807:                            selfenroll => $selfenroll,
                   4808:                            context    => $context,
                   4809:                         );
                   4810:         if ($trole eq 'gr') {
                   4811:             $namespace = 'groupslog';
                   4812:             $storehash{'group'} = $sec;
                   4813:         } else {
                   4814:             $storehash{'section'} = $sec;
                   4815:         }
                   4816:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4817:                    $domain,$cnum,$cdom);
                   4818:         if (($trole ne 'st') || ($sec ne '')) {
                   4819:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4820:         }
                   4821:     }
                   4822:     return;
                   4823: }
                   4824: 
1.1172.2.9  raeburn  4825: sub domainrolelog {
                   4826:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4827:     if ($area =~ m{^/($match_domain)/$}) {
                   4828:         my $cdom = $1;
                   4829:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4830:         my $namespace = 'rolelog';
                   4831:         my %storehash = (
                   4832:                            role    => $trole,
                   4833:                            start   => $tstart,
                   4834:                            end     => $tend,
                   4835:                            context => $context,
                   4836:                         );
                   4837:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4838:                    $domain,$domconfiguser,$cdom);
                   4839:     }
                   4840:     return;
                   4841: 
                   4842: }
                   4843: 
                   4844: sub coauthorrolelog {
                   4845:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4846:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4847:         my $audom = $1;
                   4848:         my $auname = $2;
                   4849:         my $namespace = 'rolelog';
                   4850:         my %storehash = (
                   4851:                            role    => $trole,
                   4852:                            start   => $tstart,
                   4853:                            end     => $tend,
                   4854:                            context => $context,
                   4855:                         );
                   4856:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4857:                    $domain,$auname,$audom);
                   4858:     }
                   4859:     return;
                   4860: }
                   4861: 
1.351     www      4862: sub get_course_adv_roles {
1.948     raeburn  4863:     my ($cid,$codes) = @_;
1.620     albertel 4864:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4865:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4866:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4867:     my %nothide=();
1.800     albertel 4868:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4869:         if ($user !~ /:/) {
                   4870: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4871:         } else {
                   4872:             $nothide{$user}=1;
                   4873:         }
1.470     www      4874:     }
1.1172.2.23  raeburn  4875:     my @possdoms = ($coursehash{'domain'});
                   4876:     if ($coursehash{'checkforpriv'}) {
                   4877:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4878:     }
1.351     www      4879:     my %returnhash=();
                   4880:     my %dumphash=
                   4881:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4882:     my $now=time;
1.997     raeburn  4883:     my %privileged;
1.1000    raeburn  4884:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4885: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4886:         if (($tstart) && ($tstart<0)) { next; }
                   4887:         if (($tend) && ($tend<$now)) { next; }
                   4888:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4889:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4890: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4891:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4892:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4893: 	if ($role eq 'cr') { next; }
1.948     raeburn  4894:         if ($codes) {
                   4895:             if ($section) { $role .= ':'.$section; }
                   4896:             if ($returnhash{$role}) {
                   4897:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4898:             } else {
                   4899:                 $returnhash{$role}=$username.':'.$domain;
                   4900:             }
1.351     www      4901:         } else {
1.988     raeburn  4902:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4903:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4904:             if ($returnhash{$key}) {
                   4905: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4906:             } else {
                   4907:                 $returnhash{$key}=$username.':'.$domain;
                   4908:             }
1.351     www      4909:         }
1.948     raeburn  4910:     }
1.400     www      4911:     return %returnhash;
                   4912: }
                   4913: 
                   4914: sub get_my_roles {
1.937     raeburn  4915:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4916:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4917:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4918:     my (%dumphash,%nothide);
1.1086    raeburn  4919:     if ($context eq 'userroles') {
1.1166    raeburn  4920:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4921:     } else {
1.1172.2.23  raeburn  4922:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4923:         if ($hidepriv) {
                   4924:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4925:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4926:                 if ($user !~ /:/) {
                   4927:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4928:                 } else {
                   4929:                     $nothide{$user} = 1;
                   4930:                 }
                   4931:             }
                   4932:         }
1.858     raeburn  4933:     }
1.400     www      4934:     my %returnhash=();
                   4935:     my $now=time;
1.999     raeburn  4936:     my %privileged;
1.800     albertel 4937:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4938:         my ($role,$tend,$tstart);
                   4939:         if ($context eq 'userroles') {
1.1149    raeburn  4940:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4941: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4942:         } else {
                   4943:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4944:         }
1.400     www      4945:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4946:         my $status = 'active';
1.939     raeburn  4947:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4948:             $status = 'previous';
                   4949:         } 
                   4950:         if (($tstart) && ($now<$tstart)) {
                   4951:             $status = 'future';
                   4952:         }
                   4953:         if (ref($types) eq 'ARRAY') {
                   4954:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4955:                 next;
                   4956:             } 
                   4957:         } else {
                   4958:             if ($status ne 'active') {
                   4959:                 next;
                   4960:             }
                   4961:         }
1.867     raeburn  4962:         my ($rolecode,$username,$domain,$section,$area);
                   4963:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4964:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4965:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4966:         } else {
                   4967:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4968:         }
1.832     raeburn  4969:         if (ref($roledoms) eq 'ARRAY') {
                   4970:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4971:                 next;
                   4972:             }
                   4973:         }
                   4974:         if (ref($roles) eq 'ARRAY') {
                   4975:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4976:                 if ($role =~ /^cr\//) {
                   4977:                     if (!grep(/^cr$/,@{$roles})) {
                   4978:                         next;
                   4979:                     }
1.1104    raeburn  4980:                 } elsif ($role =~ /^gr\//) {
                   4981:                     if (!grep(/^gr$/,@{$roles})) {
                   4982:                         next;
                   4983:                     }
1.922     raeburn  4984:                 } else {
                   4985:                     next;
                   4986:                 }
1.832     raeburn  4987:             }
1.867     raeburn  4988:         }
1.937     raeburn  4989:         if ($hidepriv) {
1.1172.2.23  raeburn  4990:             my @privroles = ('dc','su');
1.999     raeburn  4991:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4992:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4993:             } else {
1.1172.2.23  raeburn  4994:                 my $possdoms = [$domain];
                   4995:                 if (ref($roledoms) eq 'ARRAY') {
                   4996:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  4997:                 }
1.1172.2.23  raeburn  4998:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4999:                     if (!$nothide{$username.':'.$domain}) {
                   5000:                         next;
                   5001:                     }
                   5002:                 }
1.937     raeburn  5003:             }
                   5004:         }
1.933     raeburn  5005:         if ($withsec) {
                   5006:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5007:                 $tstart.':'.$tend;
                   5008:         } else {
                   5009:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5010:         }
1.832     raeburn  5011:     }
1.373     www      5012:     return %returnhash;
1.399     www      5013: }
                   5014: 
1.1172.2.89  raeburn  5015: sub get_all_adhocroles {
                   5016:     my ($dom) = @_;
                   5017:     my @roles_by_num = ();
                   5018:     my %domdefaults = &get_domain_defaults($dom);
                   5019:     my (%description,%access_in_dom,%access_info);
                   5020:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5021:         my $count = 0;
                   5022:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5023:         my %ordered;
                   5024:         foreach my $role (sort(keys(%domcurrent))) {
                   5025:             my ($order,$desc,$access_in_dom);
                   5026:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5027:                 $order = $domcurrent{$role}{'order'};
                   5028:                 $desc = $domcurrent{$role}{'desc'};
                   5029:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5030:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5031:             }
                   5032:             if ($order eq '') {
                   5033:                 $order = $count;
                   5034:             }
                   5035:             $ordered{$order} = $role;
                   5036:             if ($desc ne '') {
                   5037:                 $description{$role} = $desc;
                   5038:             } else {
                   5039:                 $description{$role}= $role;
                   5040:             }
                   5041:             $count++;
                   5042:         }
                   5043:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5044:             push(@roles_by_num,$ordered{$item});
                   5045:         }
                   5046:     }
                   5047:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5048: }
                   5049: 
                   5050: sub get_my_adhocroles {
                   5051:     my ($cid,$checkreg) = @_;
                   5052:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5053:     if ($env{'request.course.id'} eq $cid) {
                   5054:         $cdom = $env{'course.'.$cid.'.domain'};
                   5055:         $cnum = $env{'course.'.$cid.'.num'};
                   5056:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5057:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5058:         $cdom = $1;
                   5059:         $cnum = $2;
                   5060:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5061:                                      $cdom,$cnum);
                   5062:     }
                   5063:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5064:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5065:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5066:         if ($rosterhash{$user} ne '') {
                   5067:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5068:             return ([],{}) if ($type eq 'auto');
                   5069:         }
                   5070:     }
                   5071:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5072:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5073:             my $then=$env{'user.login.time'};
                   5074:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5075:             if (!$update) {
                   5076:                 $update = $then;
                   5077:             }
                   5078:             my @liveroles;
                   5079:             foreach my $role ('dh','da') {
                   5080:                 if ($env{"user.role.$role./$cdom/"}) {
                   5081:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5082:                     my $limit = $update;
                   5083:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5084:                         $limit = $then;
                   5085:                     }
                   5086:                     my $activerole = 1;
                   5087:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5088:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5089:                     if ($activerole) {
                   5090:                         push(@liveroles,$role);
                   5091:                     }
                   5092:                 }
                   5093:             }
                   5094:             if (@liveroles) {
1.1172.2.89  raeburn  5095:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5096:                     my ($accessref,$accessinfo,%access_in_dom);
                   5097:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5098:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5099:                         if (@{$roles_by_num}) {
                   5100:                             my %settings;
                   5101:                             if ($env{'request.course.id'} eq $cid) {
                   5102:                                 foreach my $envkey (keys(%env)) {
                   5103:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5104:                                         $settings{$1} = $env{$envkey};
                   5105:                                     }
                   5106:                                 }
                   5107:                             } else {
                   5108:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5109:                             }
                   5110:                             my %setincrs;
                   5111:                             if ($settings{'internal.adhocaccess'}) {
                   5112:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5113:                             }
                   5114:                             my @statuses;
                   5115:                             if ($env{'environment.inststatus'}) {
                   5116:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5117:                             }
                   5118:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5119:                             if (ref($accessref) eq 'HASH') {
                   5120:                                 %access_in_dom = %{$accessref};
                   5121:                             }
                   5122:                             foreach my $role (@{$roles_by_num}) {
                   5123:                                 my ($curraccess,@okstatus,@personnel);
                   5124:                                 if ($setincrs{$role}) {
                   5125:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5126:                                     if ($curraccess eq 'status') {
                   5127:                                         @okstatus = split(/\&/,$rest);
                   5128:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5129:                                         @personnel = split(/\&/,$rest);
                   5130:                                     }
                   5131:                                 } else {
                   5132:                                     $curraccess = $access_in_dom{$role};
                   5133:                                     if (ref($accessinfo) eq 'HASH') {
                   5134:                                         if ($curraccess eq 'status') {
                   5135:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5136:                                                 @okstatus = @{$accessinfo->{$role}};
                   5137:                                             }
                   5138:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5139:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5140:                                                 @personnel = @{$accessinfo->{$role}};
                   5141:                                             }
                   5142:                                         }
                   5143:                                     }
                   5144:                                 }
                   5145:                                 if ($curraccess eq 'none') {
                   5146:                                     next;
                   5147:                                 } elsif ($curraccess eq 'all') {
                   5148:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5149:                                 } elsif ($curraccess eq 'dh') {
                   5150:                                     if (grep(/^dh$/,@liveroles)) {
                   5151:                                         push(@possroles,$role);
                   5152:                                     } else {
                   5153:                                         next;
                   5154:                                     }
                   5155:                                 } elsif ($curraccess eq 'da') {
                   5156:                                     if (grep(/^da$/,@liveroles)) {
                   5157:                                         push(@possroles,$role);
                   5158:                                     } else {
                   5159:                                         next;
                   5160:                                     }
1.1172.2.89  raeburn  5161:                                 } elsif ($curraccess eq 'status') {
                   5162:                                     if (@okstatus) {
                   5163:                                         if (!@statuses) {
                   5164:                                             if (grep(/^default$/,@okstatus)) {
                   5165:                                                 push(@possroles,$role);
                   5166:                                             }
                   5167:                                         } else {
                   5168:                                             foreach my $status (@okstatus) {
                   5169:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5170:                                                     push(@possroles,$role);
                   5171:                                                     last;
                   5172:                                                 }
                   5173:                                             }
                   5174:                                         }
                   5175:                                     }
                   5176:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5177:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5178:                                         if ($curraccess eq 'exc') {
                   5179:                                             push(@possroles,$role);
                   5180:                                         }
                   5181:                                     } elsif ($curraccess eq 'inc') {
                   5182:                                         push(@possroles,$role);
                   5183:                                     }
                   5184:                                 }
                   5185:                             }
                   5186:                         }
                   5187:                     }
                   5188:                 }
                   5189:             }
                   5190:         }
                   5191:     }
                   5192:     unless (ref($description) eq 'HASH') {
                   5193:         if (ref($roles_by_num) eq 'ARRAY') {
                   5194:             my %desc;
                   5195:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5196:             $description = \%desc;
                   5197:         } else {
                   5198:             $description = {};
                   5199:         }
                   5200:     }
                   5201:     return (\@possroles,$description);
                   5202: }
                   5203: 
1.399     www      5204: # ----------------------------------------------------- Frontpage Announcements
                   5205: #
                   5206: #
                   5207: 
                   5208: sub postannounce {
                   5209:     my ($server,$text)=@_;
1.844     albertel 5210:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5211:     unless ($text=~/\w/) { $text=''; }
                   5212:     return &reply('setannounce:'.&escape($text),$server);
                   5213: }
                   5214: 
                   5215: sub getannounce {
1.448     albertel 5216: 
1.1172.2.96  raeburn  5217:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5218: 	my $announcement='';
1.800     albertel 5219: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5220: 	close($fh);
1.399     www      5221: 	if ($announcement=~/\w/) { 
                   5222: 	    return 
                   5223:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5224:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5225: 	} else {
                   5226: 	    return '';
                   5227: 	}
                   5228:     } else {
                   5229: 	return '';
                   5230:     }
1.351     www      5231: }
1.353     www      5232: 
                   5233: # ---------------------------------------------------------- Course ID routines
                   5234: # Deal with domain's nohist_courseid.db files
                   5235: #
                   5236: 
                   5237: sub courseidput {
1.921     raeburn  5238:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5239:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5240:     my $outcome;
                   5241:     if ($caller eq 'timeonly') {
                   5242:         my $cids = '';
                   5243:         foreach my $item (keys(%$storehash)) {
                   5244:             $cids.=&escape($item).'&';
                   5245:         }
                   5246:         $cids=~s/\&$//;
                   5247:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5248:                           $coursehome);       
                   5249:     } else {
                   5250:         my $items = '';
                   5251:         foreach my $item (keys(%$storehash)) {
                   5252:             $items.= &escape($item).'='.
                   5253:                      &freeze_escape($$storehash{$item}).'&';
                   5254:         }
                   5255:         $items=~s/\&$//;
                   5256:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5257:                           $coursehome);
1.918     raeburn  5258:     }
                   5259:     if ($outcome eq 'unknown_cmd') {
                   5260:         my $what;
                   5261:         foreach my $cid (keys(%$storehash)) {
                   5262:             $what .= &escape($cid).'=';
1.921     raeburn  5263:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5264:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5265:             }
                   5266:             $what =~ s/\:$/&/;
                   5267:         }
                   5268:         $what =~ s/\&$//;  
                   5269:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5270:     } else {
                   5271:         return $outcome;
                   5272:     }
1.353     www      5273: }
                   5274: 
                   5275: sub courseiddump {
1.921     raeburn  5276:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5277:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5278:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5279:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5280:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5281:     my $as_hash = 1;
                   5282:     my %returnhash;
                   5283:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5284:     my %libserv = &all_library();
                   5285:     foreach my $tryserver (keys(%libserv)) {
                   5286:         if ( (  $hostidflag == 1 
                   5287: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5288: 	     || (!defined($hostidflag)) ) {
                   5289: 
1.918     raeburn  5290: 	    if (($domfilter eq '') ||
                   5291: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5292:                 my $rep;
                   5293:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5294:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5295:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5296:                                 &escape($descfilter), &escape($instcodefilter),
                   5297:                                 &escape($ownerfilter), &escape($coursefilter),
                   5298:                                 &escape($typefilter), &escape($regexp_ok),
                   5299:                                 $as_hash, &escape($selfenrollonly),
                   5300:                                 &escape($catfilter), $showhidden, $caller,
                   5301:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5302:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5303:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5304:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5305:                 } else {
                   5306:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5307:                              $sincefilter.':'.&escape($descfilter).':'.
                   5308:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5309:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5310:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5311:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5312:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5313:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5314:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5315:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5316:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5317:                 }
                   5318: 
1.918     raeburn  5319:                 my @pairs=split(/\&/,$rep);
                   5320:                 foreach my $item (@pairs) {
                   5321:                     my ($key,$value)=split(/\=/,$item,2);
                   5322:                     $key = &unescape($key);
                   5323:                     next if ($key =~ /^error: 2 /);
                   5324:                     my $result = &thaw_unescape($value);
                   5325:                     if (ref($result) eq 'HASH') {
                   5326:                         $returnhash{$key}=$result;
                   5327:                     } else {
1.921     raeburn  5328:                         my @responses = split(/:/,$value);
                   5329:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5330:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5331:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5332:                         }
1.1008    raeburn  5333:                     }
1.353     www      5334:                 }
                   5335:             }
                   5336:         }
                   5337:     }
                   5338:     return %returnhash;
                   5339: }
                   5340: 
1.1055    raeburn  5341: sub courselastaccess {
                   5342:     my ($cdom,$cnum,$hostidref) = @_;
                   5343:     my %returnhash;
                   5344:     if ($cdom && $cnum) {
                   5345:         my $chome = &homeserver($cnum,$cdom);
                   5346:         if ($chome ne 'no_host') {
                   5347:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5348:             &extract_lastaccess(\%returnhash,$rep);
                   5349:         }
                   5350:     } else {
                   5351:         if (!$cdom) { $cdom=''; }
                   5352:         my %libserv = &all_library();
                   5353:         foreach my $tryserver (keys(%libserv)) {
                   5354:             if (ref($hostidref) eq 'ARRAY') {
                   5355:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5356:             } 
                   5357:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5358:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5359:                 &extract_lastaccess(\%returnhash,$rep);
                   5360:             }
                   5361:         }
                   5362:     }
                   5363:     return %returnhash;
                   5364: }
                   5365: 
                   5366: sub extract_lastaccess {
                   5367:     my ($returnhash,$rep) = @_;
                   5368:     if (ref($returnhash) eq 'HASH') {
                   5369:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5370:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5371:                  $rep eq '') {
                   5372:             my @pairs=split(/\&/,$rep);
                   5373:             foreach my $item (@pairs) {
                   5374:                 my ($key,$value)=split(/\=/,$item,2);
                   5375:                 $key = &unescape($key);
                   5376:                 next if ($key =~ /^error: 2 /);
                   5377:                 $returnhash->{$key} = &thaw_unescape($value);
                   5378:             }
                   5379:         }
                   5380:     }
                   5381:     return;
                   5382: }
                   5383: 
1.658     raeburn  5384: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5385: 
                   5386: sub dcmailput {
1.685     raeburn  5387:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5388:     my $status = &Apache::lonnet::critical(
1.740     www      5389:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5390:        &escape($message),$server);
1.662     raeburn  5391:     return $status;
                   5392: }
                   5393: 
1.658     raeburn  5394: sub dcmaildump {
                   5395:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5396:     my %returnhash=();
1.846     albertel 5397: 
                   5398:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5399:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5400:                                                          &escape($enddate).':';
                   5401: 	my @esc_senders=map { &escape($_)} @$senders;
                   5402: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5403: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5404:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5405:             if (($key) && ($value)) {
                   5406:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5407:             }
                   5408:         }
                   5409:     }
                   5410:     return %returnhash;
                   5411: }
1.662     raeburn  5412: # ---------------------------------------------------------- Domain roles
                   5413: 
                   5414: sub get_domain_roles {
                   5415:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5416:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5417:         $startdate = '.';
                   5418:     }
1.1018    raeburn  5419:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5420:         $enddate = '.';
                   5421:     }
1.922     raeburn  5422:     my $rolelist;
                   5423:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5424:         $rolelist = join('&',@{$roles});
1.922     raeburn  5425:     }
1.662     raeburn  5426:     my %personnel = ();
1.841     albertel 5427: 
                   5428:     my %servers = &get_servers($dom,'library');
                   5429:     foreach my $tryserver (keys(%servers)) {
                   5430: 	%{$personnel{$tryserver}}=();
                   5431: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5432: 					    &escape($startdate).':'.
                   5433: 					    &escape($enddate).':'.
                   5434: 					    &escape($rolelist), $tryserver))) {
                   5435: 	    my ($key,$value) = split(/\=/,$line,2);
                   5436: 	    if (($key) && ($value)) {
                   5437: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5438: 	    }
                   5439: 	}
1.662     raeburn  5440:     }
                   5441:     return %personnel;
                   5442: }
1.658     raeburn  5443: 
1.1172.2.89  raeburn  5444: sub get_active_domroles {
                   5445:     my ($dom,$roles) = @_;
                   5446:     return () unless (ref($roles) eq 'ARRAY');
                   5447:     my $now = time;
                   5448:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5449:     my %domroles;
                   5450:     foreach my $server (keys(%dompersonnel)) {
                   5451:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5452:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5453:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5454:         }
                   5455:     }
                   5456:     return %domroles;
                   5457: }
                   5458: 
1.1057    www      5459: # ----------------------------------------------------------- Interval timing 
1.149     www      5460: 
1.1153    www      5461: {
                   5462: # Caches needed for speedup of navmaps
                   5463: # We don't want to cache this for very long at all (5 seconds at most)
                   5464: # 
                   5465: # The user for whom we cache
                   5466: my $cachedkey='';
                   5467: # The cached times for this user
                   5468: my %cachedtimes=();
                   5469: # When this was last done
1.1172.2.66  raeburn  5470: my $cachedtime='';
1.1153    www      5471: 
                   5472: sub load_all_first_access {
1.1172.2.140.  .1(raebu 5473:21):     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5474:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.140.  .1(raebu 5475:21):         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5476:21):         (!$ignorecache)) {
1.1154    raeburn  5477:         return;
                   5478:     }
                   5479:     $cachedtime=time;
                   5480:     $cachedkey=$uname.':'.$udom;
                   5481:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5482: }
                   5483: 
1.504     albertel 5484: sub get_first_access {
1.1172.2.140.  .1(raebu 5485:21):     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5486:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5487:     if ($argsymb) { $symb=$argsymb; }
                   5488:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5489:     if ($argmap) { $map = $argmap; }
1.926     albertel 5490:     if ($type eq 'course') {
                   5491: 	$res='course';
                   5492:     } elsif ($type eq 'map') {
1.588     albertel 5493: 	$res=&symbread($map);
                   5494:     } else {
                   5495: 	$res=$symb;
                   5496:     }
1.1172.2.140.  .1(raebu 5497:21):     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5498:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5499: }
                   5500: 
                   5501: sub set_first_access {
1.1162    raeburn  5502:     my ($type,$interval)=@_;
1.790     albertel 5503:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5504:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5505:     if ($type eq 'course') {
                   5506: 	$res='course';
                   5507:     } elsif ($type eq 'map') {
1.588     albertel 5508: 	$res=&symbread($map);
                   5509:     } else {
                   5510: 	$res=$symb;
                   5511:     }
1.1153    www      5512:     $cachedkey='';
1.1162    raeburn  5513:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5514:     if ($firstaccess) {
                   5515:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5516:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5517:                  "in $courseid");
                   5518:         return 'already_set';
                   5519:     } else {
1.1162    raeburn  5520:         my $start = time;
                   5521: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5522:                           $udom,$uname);
                   5523:         if ($putres eq 'ok') {
                   5524:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5525:                  $udom,$uname); 
                   5526:             &appenv(
                   5527:                      {
                   5528:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5529:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5530:                      }
                   5531:                   );
1.1172.2.97  raeburn  5532:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5533:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5534:             }
1.1172.2.102  raeburn  5535:         } elsif ($putres ne 'refused') {
                   5536:             &logthis("Result: $putres when attempting to set first access time ".
                   5537:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5538:         }
                   5539:         return $putres;
1.505     albertel 5540:     }
                   5541:     return 'already_set';
1.504     albertel 5542: }
1.1153    www      5543: }
1.1172.2.32  raeburn  5544: 
                   5545: sub checkout {
                   5546:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5547:     my $now=time;
                   5548:     my $lonhost=$perlvar{'lonHostID'};
1.1172.2.134  raeburn  5549:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5550:     my $infostr=&escape(
                   5551:                  'CHECKOUTTOKEN&'.
                   5552:                  $tuname.'&'.
                   5553:                  $tudom.'&'.
                   5554:                  $tcrsid.'&'.
                   5555:                  $symb.'&'.
1.1172.2.134  raeburn  5556:                  $now.'&'.$ip);
1.1172.2.32  raeburn  5557:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5558:     if ($token=~/^error\:/) {
                   5559:         &logthis("<font color=\"blue\">WARNING: ".
                   5560:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5561:                  "</font>");
                   5562:         return '';
                   5563:     }
                   5564: 
                   5565:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5566:     $token=~tr/a-z/A-Z/;
                   5567: 
                   5568:     my %infohash=('resource.0.outtoken' => $token,
                   5569:                   'resource.0.checkouttime' => $now,
1.1172.2.134  raeburn  5570:                   'resource.0.outremote' => $ip);
1.1172.2.32  raeburn  5571: 
                   5572:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5573:        return '';
                   5574:     } else {
                   5575:         &logthis("<font color=\"blue\">WARNING: ".
                   5576:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5577:                  "</font>");
                   5578:     }
                   5579: 
                   5580:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5581:                          &escape('Checkout '.$infostr.' - '.
                   5582:                                                  $token)) ne 'ok') {
                   5583:         return '';
                   5584:     } else {
                   5585:         &logthis("<font color=\"blue\">WARNING: ".
                   5586:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5587:                  "</font>");
                   5588:     }
                   5589:     return $token;
                   5590: }
                   5591: 
                   5592: # ------------------------------------------------------------ Check in an item
                   5593: 
                   5594: sub checkin {
                   5595:     my $token=shift;
                   5596:     my $now=time;
                   5597:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5598:     $lonhost=~tr/A-Z/a-z/;
                   5599:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5600:     $dtoken=~s/\W/\_/g;
1.1172.2.134  raeburn  5601:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5602:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5603:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5604: 
                   5605:     unless (($tuname) && ($tudom)) {
                   5606:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5607:         return '';
                   5608:     }
                   5609: 
                   5610:     unless (&allowed('mgr',$tcrsid)) {
                   5611:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5612:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5613:         return '';
                   5614:     }
                   5615: 
                   5616:     my %infohash=('resource.0.intoken' => $token,
                   5617:                   'resource.0.checkintime' => $now,
1.1172.2.134  raeburn  5618:                   'resource.0.inremote' => $ip);
1.1172.2.32  raeburn  5619: 
                   5620:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5621:        return '';
                   5622:     }
                   5623: 
                   5624:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5625:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5626:         return '';
                   5627:     }
                   5628: 
                   5629:     return ($symb,$tuname,$tudom,$tcrsid);
                   5630: }
                   5631: 
1.110     www      5632: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5633: 
                   5634: sub expirespread {
                   5635:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5636:     my $cid=$env{'request.course.id'}; 
1.110     www      5637:     if ($cid) {
                   5638:        my $now=time;
                   5639:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5640:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5641:                             $env{'course.'.$cid.'.num'}.
1.110     www      5642: 	        	    ':nohist_expirationdates:'.
                   5643:                             &escape($key).'='.$now,
1.620     albertel 5644:                             $env{'course.'.$cid.'.home'})
1.110     www      5645:     }
                   5646:     return 'ok';
1.14      www      5647: }
                   5648: 
1.109     www      5649: # ----------------------------------------------------- Devalidate Spreadsheets
                   5650: 
                   5651: sub devalidate {
1.325     www      5652:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5653:     my $cid=$env{'request.course.id'}; 
1.109     www      5654:     if ($cid) {
1.391     matthew  5655:         # delete the stored spreadsheets for
                   5656:         # - the student level sheet of this user in course's homespace
                   5657:         # - the assessment level sheet for this resource 
                   5658:         #   for this user in user's homespace
1.553     albertel 5659: 	# - current conditional state info
1.325     www      5660: 	my $key=$uname.':'.$udom.':';
1.109     www      5661:         my $status=
1.299     matthew  5662: 	    &del('nohist_calculatedsheets',
1.391     matthew  5663: 		 [$key.'studentcalc:'],
1.620     albertel 5664: 		 $env{'course.'.$cid.'.domain'},
                   5665: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5666: 		.' '.
                   5667: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5668: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5669:         unless ($status eq 'ok ok') {
                   5670:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5671:                     $uname.' at '.$udom.' for '.
1.109     www      5672: 		    $symb.': '.$status);
1.133     albertel 5673:         }
1.553     albertel 5674: 	&delenv('user.state.'.$cid);
1.109     www      5675:     }
                   5676: }
                   5677: 
1.265     albertel 5678: sub get_scalar {
                   5679:     my ($string,$end) = @_;
                   5680:     my $value;
                   5681:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5682: 	$value = $1;
                   5683:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5684: 	$value = $1;
                   5685:     }
                   5686:     return &unescape($value);
                   5687: }
                   5688: 
                   5689: sub array2str {
                   5690:   my (@array) = @_;
                   5691:   my $result=&arrayref2str(\@array);
                   5692:   $result=~s/^__ARRAY_REF__//;
                   5693:   $result=~s/__END_ARRAY_REF__$//;
                   5694:   return $result;
                   5695: }
                   5696: 
1.204     albertel 5697: sub arrayref2str {
                   5698:   my ($arrayref) = @_;
1.265     albertel 5699:   my $result='__ARRAY_REF__';
1.204     albertel 5700:   foreach my $elem (@$arrayref) {
1.265     albertel 5701:     if(ref($elem) eq 'ARRAY') {
                   5702:       $result.=&arrayref2str($elem).'&';
                   5703:     } elsif(ref($elem) eq 'HASH') {
                   5704:       $result.=&hashref2str($elem).'&';
                   5705:     } elsif(ref($elem)) {
                   5706:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5707:     } else {
                   5708:       $result.=&escape($elem).'&';
                   5709:     }
                   5710:   }
                   5711:   $result=~s/\&$//;
1.265     albertel 5712:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5713:   return $result;
                   5714: }
                   5715: 
1.168     albertel 5716: sub hash2str {
1.204     albertel 5717:   my (%hash) = @_;
                   5718:   my $result=&hashref2str(\%hash);
1.265     albertel 5719:   $result=~s/^__HASH_REF__//;
                   5720:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5721:   return $result;
                   5722: }
                   5723: 
                   5724: sub hashref2str {
                   5725:   my ($hashref)=@_;
1.265     albertel 5726:   my $result='__HASH_REF__';
1.800     albertel 5727:   foreach my $key (sort(keys(%$hashref))) {
                   5728:     if (ref($key) eq 'ARRAY') {
                   5729:       $result.=&arrayref2str($key).'=';
                   5730:     } elsif (ref($key) eq 'HASH') {
                   5731:       $result.=&hashref2str($key).'=';
                   5732:     } elsif (ref($key)) {
1.265     albertel 5733:       $result.='=';
1.800     albertel 5734:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5735:     } else {
1.1132    raeburn  5736: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5737:     }
                   5738: 
1.800     albertel 5739:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5740:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5741:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5742:       $result.=&hashref2str($hashref->{$key}).'&';
                   5743:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5744:        $result.='&';
1.800     albertel 5745:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5746:     } else {
1.800     albertel 5747:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5748:     }
                   5749:   }
1.168     albertel 5750:   $result=~s/\&$//;
1.265     albertel 5751:   $result .= '__END_HASH_REF__';
1.168     albertel 5752:   return $result;
                   5753: }
                   5754: 
                   5755: sub str2hash {
1.265     albertel 5756:     my ($string)=@_;
                   5757:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5758:     return %$hash;
                   5759: }
                   5760: 
                   5761: sub str2hashref {
1.168     albertel 5762:   my ($string) = @_;
1.265     albertel 5763: 
                   5764:   my %hash;
                   5765: 
                   5766:   if($string !~ /^__HASH_REF__/) {
                   5767:       if (! ($string eq '' || !defined($string))) {
                   5768: 	  $hash{'error'}='Not hash reference';
                   5769:       }
                   5770:       return (\%hash, $string);
                   5771:   }
                   5772: 
                   5773:   $string =~ s/^__HASH_REF__//;
                   5774: 
                   5775:   while($string !~ /^__END_HASH_REF__/) {
                   5776:       #key
                   5777:       my $key='';
                   5778:       if($string =~ /^__HASH_REF__/) {
                   5779:           ($key, $string)=&str2hashref($string);
                   5780:           if(defined($key->{'error'})) {
                   5781:               $hash{'error'}='Bad data';
                   5782:               return (\%hash, $string);
                   5783:           }
                   5784:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5785:           ($key, $string)=&str2arrayref($string);
                   5786:           if($key->[0] eq 'Array reference error') {
                   5787:               $hash{'error'}='Bad data';
                   5788:               return (\%hash, $string);
                   5789:           }
                   5790:       } else {
                   5791:           $string =~ s/^(.*?)=//;
1.267     albertel 5792: 	  $key=&unescape($1);
1.265     albertel 5793:       }
                   5794:       $string =~ s/^=//;
                   5795: 
                   5796:       #value
                   5797:       my $value='';
                   5798:       if($string =~ /^__HASH_REF__/) {
                   5799:           ($value, $string)=&str2hashref($string);
                   5800:           if(defined($value->{'error'})) {
                   5801:               $hash{'error'}='Bad data';
                   5802:               return (\%hash, $string);
                   5803:           }
                   5804:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5805:           ($value, $string)=&str2arrayref($string);
                   5806:           if($value->[0] eq 'Array reference error') {
                   5807:               $hash{'error'}='Bad data';
                   5808:               return (\%hash, $string);
                   5809:           }
                   5810:       } else {
                   5811: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5812:       }
                   5813:       $string =~ s/^&//;
                   5814: 
                   5815:       $hash{$key}=$value;
1.204     albertel 5816:   }
1.265     albertel 5817: 
                   5818:   $string =~ s/^__END_HASH_REF__//;
                   5819: 
                   5820:   return (\%hash, $string);
1.204     albertel 5821: }
                   5822: 
                   5823: sub str2array {
1.265     albertel 5824:     my ($string)=@_;
                   5825:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5826:     return @$array;
                   5827: }
                   5828: 
                   5829: sub str2arrayref {
1.204     albertel 5830:   my ($string) = @_;
1.265     albertel 5831:   my @array;
                   5832: 
                   5833:   if($string !~ /^__ARRAY_REF__/) {
                   5834:       if (! ($string eq '' || !defined($string))) {
                   5835: 	  $array[0]='Array reference error';
                   5836:       }
                   5837:       return (\@array, $string);
                   5838:   }
                   5839: 
                   5840:   $string =~ s/^__ARRAY_REF__//;
                   5841: 
                   5842:   while($string !~ /^__END_ARRAY_REF__/) {
                   5843:       my $value='';
                   5844:       if($string =~ /^__HASH_REF__/) {
                   5845:           ($value, $string)=&str2hashref($string);
                   5846:           if(defined($value->{'error'})) {
                   5847:               $array[0] ='Array reference error';
                   5848:               return (\@array, $string);
                   5849:           }
                   5850:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5851:           ($value, $string)=&str2arrayref($string);
                   5852:           if($value->[0] eq 'Array reference error') {
                   5853:               $array[0] ='Array reference error';
                   5854:               return (\@array, $string);
                   5855:           }
                   5856:       } else {
                   5857: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5858:       }
                   5859:       $string =~ s/^&//;
                   5860: 
                   5861:       push(@array, $value);
1.191     harris41 5862:   }
1.265     albertel 5863: 
                   5864:   $string =~ s/^__END_ARRAY_REF__//;
                   5865: 
                   5866:   return (\@array, $string);
1.168     albertel 5867: }
                   5868: 
1.167     albertel 5869: # -------------------------------------------------------------------Temp Store
                   5870: 
1.168     albertel 5871: sub tmpreset {
                   5872:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5873:   if (!$symb) {
                   5874:     $symb=&symbread();
1.620     albertel 5875:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5876:   }
                   5877:   $symb=escape($symb);
                   5878: 
1.620     albertel 5879:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5880:   $namespace=~s/\//\_/g;
                   5881:   $namespace=~s/\W//g;
                   5882: 
1.620     albertel 5883:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5884:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5885:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  5886:       $stuname=&get_requestor_ip();
1.591     albertel 5887:   }
1.1117    foxr     5888:   my $path=LONCAPA::tempdir();
1.168     albertel 5889:   my %hash;
                   5890:   if (tie(%hash,'GDBM_File',
                   5891: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5892: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5893:     foreach my $key (keys(%hash)) {
1.180     albertel 5894:       if ($key=~ /:$symb/) {
1.168     albertel 5895: 	delete($hash{$key});
                   5896:       }
                   5897:     }
                   5898:   }
                   5899: }
                   5900: 
1.167     albertel 5901: sub tmpstore {
1.168     albertel 5902:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5903: 
                   5904:   if (!$symb) {
                   5905:     $symb=&symbread();
1.620     albertel 5906:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5907:   }
                   5908:   $symb=escape($symb);
                   5909: 
                   5910:   if (!$namespace) {
                   5911:     # I don't think we would ever want to store this for a course.
                   5912:     # it seems this will only be used if we don't have a course.
1.620     albertel 5913:     #$namespace=$env{'request.course.id'};
1.168     albertel 5914:     #if (!$namespace) {
1.620     albertel 5915:       $namespace=$env{'request.state'};
1.168     albertel 5916:     #}
                   5917:   }
                   5918:   $namespace=~s/\//\_/g;
                   5919:   $namespace=~s/\W//g;
1.620     albertel 5920:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5921:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5922:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  5923:       $stuname=&get_requestor_ip();
1.591     albertel 5924:   }
1.168     albertel 5925:   my $now=time;
                   5926:   my %hash;
1.1117    foxr     5927:   my $path=LONCAPA::tempdir();
1.168     albertel 5928:   if (tie(%hash,'GDBM_File',
                   5929: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5930: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5931:     $hash{"version:$symb"}++;
                   5932:     my $version=$hash{"version:$symb"};
                   5933:     my $allkeys=''; 
                   5934:     foreach my $key (keys(%$storehash)) {
                   5935:       $allkeys.=$key.':';
1.591     albertel 5936:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5937:     }
                   5938:     $hash{"$version:$symb:timestamp"}=$now;
                   5939:     $allkeys.='timestamp';
                   5940:     $hash{"$version:keys:$symb"}=$allkeys;
                   5941:     if (untie(%hash)) {
                   5942:       return 'ok';
                   5943:     } else {
                   5944:       return "error:$!";
                   5945:     }
                   5946:   } else {
                   5947:     return "error:$!";
                   5948:   }
                   5949: }
1.167     albertel 5950: 
1.168     albertel 5951: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5952: 
1.168     albertel 5953: sub tmprestore {
                   5954:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5955: 
1.168     albertel 5956:   if (!$symb) {
                   5957:     $symb=&symbread();
1.620     albertel 5958:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5959:   }
                   5960:   $symb=escape($symb);
                   5961: 
1.620     albertel 5962:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5963: 
1.620     albertel 5964:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5965:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5966:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  5967:       $stuname=&get_requestor_ip();
1.591     albertel 5968:   }
1.168     albertel 5969:   my %returnhash;
                   5970:   $namespace=~s/\//\_/g;
                   5971:   $namespace=~s/\W//g;
                   5972:   my %hash;
1.1117    foxr     5973:   my $path=LONCAPA::tempdir();
1.168     albertel 5974:   if (tie(%hash,'GDBM_File',
                   5975: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5976: 	  &GDBM_READER(),0640)) {
1.168     albertel 5977:     my $version=$hash{"version:$symb"};
                   5978:     $returnhash{'version'}=$version;
                   5979:     my $scope;
                   5980:     for ($scope=1;$scope<=$version;$scope++) {
                   5981:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5982:       my @keys=split(/:/,$vkeys);
                   5983:       my $key;
                   5984:       $returnhash{"$scope:keys"}=$vkeys;
                   5985:       foreach $key (@keys) {
1.591     albertel 5986: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5987: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5988:       }
                   5989:     }
1.168     albertel 5990:     if (!(untie(%hash))) {
                   5991:       return "error:$!";
                   5992:     }
                   5993:   } else {
                   5994:     return "error:$!";
                   5995:   }
                   5996:   return %returnhash;
1.167     albertel 5997: }
                   5998: 
1.9       www      5999: # ----------------------------------------------------------------------- Store
                   6000: 
                   6001: sub store {
1.1172.2.64  raeburn  6002:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6003:     my $home='';
                   6004: 
1.168     albertel 6005:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6006: 
1.213     www      6007:     $symb=&symbclean($symb);
1.122     albertel 6008:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6009: 
1.620     albertel 6010:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6011:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6012: 
                   6013:     &devalidate($symb,$stuname,$domain);
1.109     www      6014: 
                   6015:     $symb=escape($symb);
1.187     www      6016:     if (!$namespace) { 
1.620     albertel 6017:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6018:           return ''; 
                   6019:        } 
                   6020:     }
1.620     albertel 6021:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6022: 
1.1172.2.138  raeburn  6023:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6024:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6025: 
1.12      www      6026:     my $namevalue='';
1.800     albertel 6027:     foreach my $key (keys(%$storehash)) {
                   6028:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6029:     }
1.12      www      6030:     $namevalue=~s/\&$//;
1.187     www      6031:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  6032:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6033: }
                   6034: 
1.47      www      6035: # -------------------------------------------------------------- Critical Store
                   6036: 
                   6037: sub cstore {
1.1172.2.64  raeburn  6038:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6039:     my $home='';
                   6040: 
1.168     albertel 6041:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6042: 
1.213     www      6043:     $symb=&symbclean($symb);
1.122     albertel 6044:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6045: 
1.620     albertel 6046:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6047:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6048: 
                   6049:     &devalidate($symb,$stuname,$domain);
1.109     www      6050: 
                   6051:     $symb=escape($symb);
1.187     www      6052:     if (!$namespace) { 
1.620     albertel 6053:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6054:           return ''; 
                   6055:        } 
                   6056:     }
1.620     albertel 6057:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6058: 
1.1172.2.138  raeburn  6059:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6060:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6061: 
1.47      www      6062:     my $namevalue='';
1.800     albertel 6063:     foreach my $key (keys(%$storehash)) {
                   6064:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6065:     }
1.47      www      6066:     $namevalue=~s/\&$//;
1.187     www      6067:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6068:     return critical
1.1172.2.64  raeburn  6069:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6070: }
                   6071: 
1.9       www      6072: # --------------------------------------------------------------------- Restore
                   6073: 
                   6074: sub restore {
1.124     www      6075:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6076:     my $home='';
                   6077: 
1.168     albertel 6078:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6079: 
1.122     albertel 6080:     if (!$symb) {
1.1172.2.26  raeburn  6081:         return if ($namespace eq 'courserequests');
                   6082:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6083:     } else {
1.1172.2.26  raeburn  6084:         unless ($namespace eq 'courserequests') {
                   6085:             $symb=&escape(&symbclean($symb));
                   6086:         }
1.122     albertel 6087:     }
1.188     www      6088:     if (!$namespace) { 
1.620     albertel 6089:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6090:           return ''; 
                   6091:        } 
                   6092:     }
1.620     albertel 6093:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6094:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6095:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6096:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6097: 
1.12      www      6098:     my %returnhash=();
1.800     albertel 6099:     foreach my $line (split(/\&/,$answer)) {
                   6100: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6101:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6102:     }
1.75      www      6103:     my $version;
                   6104:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6105:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6106:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6107:        }
1.75      www      6108:     }
1.13      www      6109:     return %returnhash;
1.34      www      6110: }
                   6111: 
                   6112: # ---------------------------------------------------------- Course Description
1.1118    foxr     6113: #
                   6114: #  
1.34      www      6115: 
                   6116: sub coursedescription {
1.731     albertel 6117:     my ($courseid,$args)=@_;
1.34      www      6118:     $courseid=~s/^\///;
1.49      www      6119:     $courseid=~s/\_/\//g;
1.34      www      6120:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6121:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6122:     my $normalid=$cdomain.'_'.$cnum;
                   6123:     # need to always cache even if we get errors otherwise we keep 
                   6124:     # trying and trying and trying to get the course description.
                   6125:     my %envhash=();
                   6126:     my %returnhash=();
1.731     albertel 6127:     
                   6128:     my $expiretime=600;
                   6129:     if ($env{'request.course.id'} eq $normalid) {
                   6130: 	$expiretime=120;
                   6131:     }
                   6132: 
                   6133:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6134:     if (!$args->{'freshen_cache'}
                   6135: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6136: 	foreach my $key (keys(%env)) {
                   6137: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6138: 	    my ($setting) = $1;
                   6139: 	    $returnhash{$setting} = $env{$key};
                   6140: 	}
                   6141: 	return %returnhash;
                   6142:     }
                   6143: 
1.1118    foxr     6144:     # get the data again
                   6145: 
1.731     albertel 6146:     if (!$args->{'one_time'}) {
                   6147: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6148:     }
1.811     albertel 6149: 
1.34      www      6150:     if ($chome ne 'no_host') {
1.302     albertel 6151:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6152:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6153: 	   my $username = $env{'user.name'}; # Defult username
                   6154: 	   if(defined $args->{'user'}) {
                   6155: 	       $username = $args->{'user'};
                   6156: 	   }
1.129     albertel 6157:            $returnhash{'home'}= $chome;
                   6158: 	   $returnhash{'domain'} = $cdomain;
                   6159: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6160:            if (!defined($returnhash{'type'})) {
                   6161:                $returnhash{'type'} = 'Course';
                   6162:            }
1.130     albertel 6163:            while (my ($name,$value) = each %returnhash) {
1.53      www      6164:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6165:            }
1.270     www      6166:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6167:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6168: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6169:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6170:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6171:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6172:        }
                   6173:     }
1.731     albertel 6174:     if (!$args->{'one_time'}) {
1.949     raeburn  6175: 	&appenv(\%envhash);
1.731     albertel 6176:     }
1.302     albertel 6177:     return %returnhash;
1.461     www      6178: }
                   6179: 
1.1080    raeburn  6180: sub update_released_required {
                   6181:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6182:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6183:         $cid = $env{'request.course.id'};
                   6184:         $cdom = $env{'course.'.$cid.'.domain'};
                   6185:         $cnum = $env{'course.'.$cid.'.num'};
                   6186:         $chome = $env{'course.'.$cid.'.home'};
                   6187:     }
                   6188:     if ($needsrelease) {
                   6189:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6190:         my $needsupdate;
                   6191:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6192:             $needsupdate = 1;
                   6193:         } else {
                   6194:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6195:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6196:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6197:                 $needsupdate = 1;
                   6198:             }
                   6199:         }
                   6200:         if ($needsupdate) {
                   6201:             my %needshash = (
                   6202:                              'internal.releaserequired' => $needsrelease,
                   6203:                             );
                   6204:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6205:             if ($putresult eq 'ok') {
                   6206:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6207:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6208:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6209:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6210:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6211:                 }
                   6212:             }
                   6213:         }
                   6214:     }
                   6215:     return;
                   6216: }
                   6217: 
1.461     www      6218: # -------------------------------------------------See if a user is privileged
                   6219: 
                   6220: sub privileged {
1.1172.2.23  raeburn  6221:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6222:     my $now = time;
1.1172.2.23  raeburn  6223:     my $roles;
                   6224:     if (ref($possroles) eq 'ARRAY') {
                   6225:         $roles = $possroles;
                   6226:     } else {
                   6227:         $roles = ['dc','su'];
                   6228:     }
                   6229:     if (ref($possdomains) eq 'ARRAY') {
                   6230:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6231:         foreach my $dom (@{$possdomains}) {
                   6232:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6233:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6234:                 foreach my $role (@{$roles}) {
                   6235:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6236:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6237:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6238:                             return 1 unless (($end && $end < $now) ||
                   6239:                                              ($start && $start > $now));
                   6240:                         }
                   6241:                     }
                   6242:                 }
                   6243:             }
                   6244:         }
                   6245:     } else {
                   6246:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6247:         my $now = time;
1.1170    droeschl 6248: 
1.1172.2.58  raeburn  6249:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6250:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6251:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6252:                 return 1 unless ($tend && $tend < $now)
                   6253:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6254:             }
1.1172.2.23  raeburn  6255:         }
                   6256:     }
1.461     www      6257:     return 0;
1.9       www      6258: }
1.1       albertel 6259: 
1.1172.2.23  raeburn  6260: sub privileged_by_domain {
                   6261:     my ($domains,$roles) = @_;
                   6262:     my %privileged = ();
                   6263:     my $cachetime = 60*60*24;
                   6264:     my $now = time;
                   6265:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6266:         return %privileged;
                   6267:     }
                   6268:     foreach my $dom (@{$domains}) {
                   6269:         next if (ref($privileged{$dom}) eq 'HASH');
                   6270:         my $needroles;
                   6271:         foreach my $role (@{$roles}) {
                   6272:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6273:             if (defined($cached)) {
                   6274:                 if (ref($result) eq 'HASH') {
                   6275:                     $privileged{$dom}{$role} = $result;
                   6276:                 }
                   6277:             } else {
                   6278:                 $needroles = 1;
                   6279:             }
                   6280:         }
                   6281:         if ($needroles) {
                   6282:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6283:             $privileged{$dom} = {};
                   6284:             foreach my $server (keys(%dompersonnel)) {
                   6285:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6286:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6287:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6288:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6289:                         next if ($end && $end < $now);
                   6290:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6291:                             $dompersonnel{$server}{$item};
                   6292:                     }
                   6293:                 }
                   6294:             }
                   6295:             if (ref($privileged{$dom}) eq 'HASH') {
                   6296:                 foreach my $role (@{$roles}) {
                   6297:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6298:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6299:                     } else {
                   6300:                         my %hash = ();
                   6301:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6302:                     }
                   6303:                 }
                   6304:             }
                   6305:         }
                   6306:     }
                   6307:     return %privileged;
                   6308: }
                   6309: 
1.103     harris41 6310: # -------------------------------------------------------- Get user privileges
1.11      www      6311: 
                   6312: sub rolesinit {
1.1169    droeschl 6313:     my ($domain, $username) = @_;
                   6314:     my %userroles = ('user.login.time' => time);
                   6315:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6316: 
                   6317:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6318:     # also, blocking can be triggered by an activating timer
                   6319:     # it's saved in the user's %env.
                   6320:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6321:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6322:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6323:         %timerintchk, %timerintenv);
                   6324: 
1.1162    raeburn  6325:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6326:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6327:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6328:     }
1.1169    droeschl 6329: 
1.1162    raeburn  6330:     foreach my $key (keys(%timerinterval)) {
                   6331:         my ($cid,$rest) = split(/\0/,$key);
                   6332:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6333:     }
1.1169    droeschl 6334: 
1.11      www      6335:     my %allroles=();
1.1162    raeburn  6336:     my %allgroups=();
1.11      www      6337: 
1.1172.2.58  raeburn  6338:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6339:         my $role = $rolesdump{$area};
                   6340:         $area =~ s/\_\w\w$//;
                   6341: 
                   6342:         my ($trole, $tend, $tstart, $group_privs);
                   6343: 
                   6344:         if ($role =~ /^cr/) {
                   6345:         # Custom role, defined by a user 
                   6346:         # e.g., user.role.cr/msu/smith/mynewrole
                   6347:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6348:                 $trole = $1;
                   6349:                 ($tend, $tstart) = split('_', $2);
                   6350:             } else {
                   6351:                 $trole = $role;
                   6352:             }
                   6353:         } elsif ($role =~ m|^gr/|) {
                   6354:         # Role of member in a group, defined within a course/community
                   6355:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6356:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6357:             next if $tstart eq '-1';
                   6358:             ($trole, $group_privs) = split(/\//, $trole);
                   6359:             $group_privs = &unescape($group_privs);
                   6360:         } else {
                   6361:         # Just a normal role, defined in roles.tab
                   6362:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6363:         }
                   6364: 
                   6365:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6366:                  $username);
                   6367:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6368: 
                   6369:         # role expired or not available yet?
                   6370:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6371:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6372: 
                   6373:         next if $area eq '' or $trole eq '';
                   6374: 
                   6375:         my $spec = "$trole.$area";
                   6376:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6377: 
                   6378:         if ($trole =~ /^cr\//) {
                   6379:         # Custom role, defined by a user
                   6380:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6381:         } elsif ($trole eq 'gr') {
                   6382:         # Role of a member in a group, defined within a course/community
                   6383:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6384:             next;
                   6385:         } else {
                   6386:         # Normal role, defined in roles.tab
                   6387:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6388:         }
                   6389: 
                   6390:         my $cid = $tdomain.'_'.$trest;
                   6391:         unless ($firstaccchk{$cid}) {
                   6392:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6393:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6394:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6395:                         $coursetimerstarts{$cid}{$item}; 
                   6396:                 }
                   6397:             }
                   6398:             $firstaccchk{$cid} = 1;
                   6399:         }
                   6400:         unless ($timerintchk{$cid}) {
                   6401:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6402:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6403:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6404:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6405:                 }
1.12      www      6406:             }
1.1169    droeschl 6407:             $timerintchk{$cid} = 1;
1.191     harris41 6408:         }
1.11      www      6409:     }
1.1169    droeschl 6410: 
1.1172.2.91  raeburn  6411:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6412:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6413:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6414:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6415: 
1.1162    raeburn  6416:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6417: }
                   6418: 
1.567     raeburn  6419: sub set_arearole {
1.1172.2.19  raeburn  6420:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6421:     unless ($nolog) {
1.567     raeburn  6422: # log the associated role with the area
1.1172.2.19  raeburn  6423:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6424:     }
1.743     albertel 6425:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6426: }
                   6427: 
                   6428: sub custom_roleprivs {
                   6429:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6430:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6431:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6432:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6433:         my ($rdummy,$roledef)=
                   6434:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6435:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6436:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6437:             if (defined($syspriv)) {
1.1043    raeburn  6438:                 if ($trest =~ /^$match_community$/) {
                   6439:                     $syspriv =~ s/bre\&S//; 
                   6440:                 }
1.567     raeburn  6441:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6442:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6443:             }
                   6444:             if ($tdomain ne '') {
                   6445:                 if (defined($dompriv)) {
                   6446:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6447:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6448:                 }
                   6449:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6450:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6451:                         my $rolename = $1;
                   6452:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6453:                     }
1.567     raeburn  6454:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6455:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6456:                 }
                   6457:             }
                   6458:         }
                   6459:     }
                   6460: }
                   6461: 
1.1172.2.89  raeburn  6462: sub course_adhocrole_privs {
                   6463:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6464:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6465:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6466:         my (%currprivs,%storeprivs);
                   6467:         foreach my $item (split(/:/,$coursepriv)) {
                   6468:             my ($priv,$restrict) = split(/\&/,$item);
                   6469:             $currprivs{$priv} = $restrict;
                   6470:         }
                   6471:         my (%possadd,%possremove,%full);
                   6472:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6473:             my ($priv,$restrict)=split(/\&/,$item);
                   6474:             $full{$priv} = $restrict;
                   6475:         }
                   6476:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6477:              next if ($item eq '');
                   6478:              my ($rule,$rest) = split(/=/,$item);
                   6479:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6480:              foreach my $priv (split(/:/,$rest)) {
                   6481:                  if ($priv ne '') {
                   6482:                      if ($rule eq 'off') {
                   6483:                          $possremove{$priv} = 1;
                   6484:                      } else {
                   6485:                          $possadd{$priv} = 1;
                   6486:                      }
                   6487:                  }
                   6488:              }
                   6489:          }
                   6490:          foreach my $priv (sort(keys(%full))) {
                   6491:              if (exists($currprivs{$priv})) {
                   6492:                  unless (exists($possremove{$priv})) {
                   6493:                      $storeprivs{$priv} = $currprivs{$priv};
                   6494:                  }
                   6495:              } elsif (exists($possadd{$priv})) {
                   6496:                  $storeprivs{$priv} = $full{$priv};
                   6497:              }
                   6498:          }
                   6499:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6500:      }
                   6501:      return $coursepriv;
                   6502: }
                   6503: 
1.678     raeburn  6504: sub group_roleprivs {
                   6505:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6506:     my $access = 1;
                   6507:     my $now = time;
                   6508:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6509:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6510:     if ($access) {
1.811     albertel 6511:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6512:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6513:     }
                   6514: }
1.567     raeburn  6515: 
                   6516: sub standard_roleprivs {
                   6517:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6518:     if (defined($pr{$trole.':s'})) {
                   6519:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6520:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6521:     }
                   6522:     if ($tdomain ne '') {
                   6523:         if (defined($pr{$trole.':d'})) {
                   6524:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6525:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6526:         }
                   6527:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6528:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6529:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6530:         }
                   6531:     }
                   6532: }
                   6533: 
                   6534: sub set_userprivs {
1.1064    raeburn  6535:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6536:     my $author=0;
                   6537:     my $adv=0;
1.1172.2.91  raeburn  6538:     my $rar=0;
1.678     raeburn  6539:     my %grouproles = ();
                   6540:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6541:         my @groupkeys; 
1.1000    raeburn  6542:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6543:             push(@groupkeys,$role);
                   6544:         }
                   6545:         if (ref($groups_roles) eq 'HASH') {
                   6546:             foreach my $key (keys(%{$groups_roles})) {
                   6547:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6548:                     push(@groupkeys,$key);
                   6549:                 }
                   6550:             }
                   6551:         }
                   6552:         if (@groupkeys > 0) {
                   6553:             foreach my $role (@groupkeys) {
                   6554:                 my ($trole,$area,$sec,$extendedarea);
                   6555:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6556:                     $trole = $1;
                   6557:                     $area = $2;
                   6558:                     $sec = $3;
                   6559:                     $extendedarea = $area.$sec;
                   6560:                     if (exists($$allgroups{$area})) {
                   6561:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6562:                             my $spec = $trole.'.'.$extendedarea;
                   6563:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6564:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6565:                         }
1.678     raeburn  6566:                     }
                   6567:                 }
                   6568:             }
                   6569:         }
                   6570:     }
1.800     albertel 6571:     foreach my $group (keys(%grouproles)) {
                   6572:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6573:     }
1.800     albertel 6574:     foreach my $role (keys(%{$allroles})) {
                   6575:         my %thesepriv;
1.941     raeburn  6576:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6577:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6578:             if ($item ne '') {
                   6579:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6580:                 if ($restrictions eq '') {
                   6581:                     $thesepriv{$privilege}='F';
                   6582:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6583:                     $thesepriv{$privilege}.=$restrictions;
                   6584:                 }
                   6585:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6586:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6587:             }
                   6588:         }
                   6589:         my $thesestr='';
1.1104    raeburn  6590:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6591: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6592: 	}
                   6593:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6594:     }
1.1172.2.91  raeburn  6595:     return ($author,$adv,$rar);
1.567     raeburn  6596: }
                   6597: 
1.994     raeburn  6598: sub role_status {
1.1104    raeburn  6599:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6600:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6601:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6602:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6603:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6604:             $$where = '/'.$two;
1.994     raeburn  6605:             $$trolecode=$$role.'.'.$$where;
                   6606:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6607:             $$tstatus='is';
1.1104    raeburn  6608:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6609:                 $$tstatus='future';
1.1034    raeburn  6610:                 if ($$tstart<$now) {
                   6611:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6612:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6613:                             my (%allroles,%allgroups,$group_privs,
                   6614:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6615:                             my %userroles = (
                   6616:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6617:                             );
1.1064    raeburn  6618:                             @rolecodes = ('cm'); 
1.1002    raeburn  6619:                             my $spec=$$role.'.'.$$where;
                   6620:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6621:                             if ($$role =~ /^cr\//) {
                   6622:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6623:                                 push(@rolecodes,'cr');
1.1002    raeburn  6624:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6625:                                 push(@rolecodes,$$role);
1.1002    raeburn  6626:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6627:                                                     $env{'user.name'});
1.1064    raeburn  6628:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6629:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6630:                                 $group_privs = &unescape($group_privs);
                   6631:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6632:                                 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  6633:                                 &get_groups_roles($tdomain,$trest,
                   6634:                                                   \%course_roles,\@rolecodes,
                   6635:                                                   \%groups_roles);
1.1002    raeburn  6636:                             } else {
1.1064    raeburn  6637:                                 push(@rolecodes,$$role);
1.1002    raeburn  6638:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6639:                             }
1.1172.2.91  raeburn  6640:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6641:                                                                    \%groups_roles);
1.1064    raeburn  6642:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6643:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6644:                         }
                   6645:                     }
1.1034    raeburn  6646:                     $$tstatus = 'is';
1.1002    raeburn  6647:                 }
1.994     raeburn  6648:             }
                   6649:             if ($$tend) {
1.1104    raeburn  6650:                 if ($$tend<$update) {
1.994     raeburn  6651:                     $$tstatus='expired';
                   6652:                 } elsif ($$tend<$now) {
                   6653:                     $$tstatus='will_not';
                   6654:                 }
                   6655:             }
                   6656:         }
                   6657:     }
                   6658: }
                   6659: 
1.1104    raeburn  6660: sub get_groups_roles {
                   6661:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6662:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6663:                   (ref($rolecodes) eq 'ARRAY') && 
                   6664:                   (ref($groups_roles) eq 'HASH')); 
                   6665:     if (keys(%{$cdom_courseroles}) > 0) {
                   6666:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6667:         if ($cdom ne '' && $cnum ne '') {
                   6668:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6669:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6670:                     my $crsrole = $1;
                   6671:                     my $crssec = $2;
                   6672:                     if ($crsrole =~ /^cr/) {
                   6673:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6674:                             push(@{$rolecodes},'cr');
                   6675:                         }
                   6676:                     } else {
                   6677:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6678:                             push(@{$rolecodes},$crsrole);
                   6679:                         }
                   6680:                     }
                   6681:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6682:                     if ($crssec ne '') {
                   6683:                         $rolekey .= "/$crssec";
                   6684:                     }
                   6685:                     $rolekey .= './';
                   6686:                     $groups_roles->{$rolekey} = $rolecodes;
                   6687:                 }
                   6688:             }
                   6689:         }
                   6690:     }
                   6691:     return;
                   6692: }
                   6693: 
                   6694: sub delete_env_groupprivs {
                   6695:     my ($where,$courseroles,$possroles) = @_;
                   6696:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6697:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6698:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6699:         %{$courseroles->{$udom}} =
                   6700:             &get_my_roles('','','userroles',['active'],
                   6701:                           $possroles,[$udom],1);
                   6702:     }
                   6703:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6704:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6705:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6706:             my $area = '/'.$cdom.'/'.$cnum;
                   6707:             my $privkey = "user.priv.$crsrole.$area";
                   6708:             if ($crssec ne '') {
                   6709:                 $privkey .= '/'.$crssec;
                   6710:             }
                   6711:             $privkey .= ".$area/$group";
                   6712:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6713:         }
                   6714:     }
                   6715:     return;
                   6716: }
                   6717: 
1.994     raeburn  6718: sub check_adhoc_privs {
1.1172.2.86  raeburn  6719:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6720:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6721:     if ($sec) {
                   6722:         $cckey .= '/'.$sec;
                   6723:     }
1.1172.2.9  raeburn  6724:     my $setprivs;
1.994     raeburn  6725:     if ($env{$cckey}) {
                   6726:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6727:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6728:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6729:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6730:             $setprivs = 1;
1.994     raeburn  6731:         }
                   6732:     } else {
1.1172.2.87  raeburn  6733:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6734:         $setprivs = 1;
1.994     raeburn  6735:     }
1.1172.2.9  raeburn  6736:     return $setprivs;
1.994     raeburn  6737: }
                   6738: 
                   6739: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6740: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6741:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6742:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6743:     if ($sec ne '') {
                   6744:         $area .= '/'.$sec;
                   6745:     }
1.994     raeburn  6746:     my $spec = $role.'.'.$area;
                   6747:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6748:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6749:     my %rolehash = ();
1.1172.2.89  raeburn  6750:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6751:         my $rolename = $1;
1.1172.2.84  raeburn  6752:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6753:         my %domdef = &get_domain_defaults($dcdom);
                   6754:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6755:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6756:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6757:             }
                   6758:         }
1.1172.2.84  raeburn  6759:     } else {
                   6760:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6761:     }
1.1172.2.91  raeburn  6762:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6763:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6764:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6765:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6766:         &appenv( {'request.role'        => $spec,
                   6767:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6768:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6769:                  }
                   6770:                );
                   6771:         my $tadv=0;
                   6772:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6773:         &appenv({'request.role.adv'    => $tadv});
                   6774:     }
1.994     raeburn  6775: }
                   6776: 
1.12      www      6777: # --------------------------------------------------------------- get interface
                   6778: 
                   6779: sub get {
1.131     albertel 6780:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6781:    my $items='';
1.800     albertel 6782:    foreach my $item (@$storearr) {
                   6783:        $items.=&escape($item).'&';
1.191     harris41 6784:    }
1.12      www      6785:    $items=~s/\&$//;
1.620     albertel 6786:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6787:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6788:    my $uhome=&homeserver($uname,$udomain);
                   6789: 
1.133     albertel 6790:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6791:    my @pairs=split(/\&/,$rep);
1.273     albertel 6792:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6793:      return @pairs;
                   6794:    }
1.15      www      6795:    my %returnhash=();
1.42      www      6796:    my $i=0;
1.800     albertel 6797:    foreach my $item (@$storearr) {
                   6798:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6799:       $i++;
1.191     harris41 6800:    }
1.15      www      6801:    return %returnhash;
1.27      www      6802: }
                   6803: 
                   6804: # --------------------------------------------------------------- del interface
                   6805: 
                   6806: sub del {
1.133     albertel 6807:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6808:    my $items='';
1.800     albertel 6809:    foreach my $item (@$storearr) {
                   6810:        $items.=&escape($item).'&';
1.191     harris41 6811:    }
1.984     neumanie 6812: 
1.27      www      6813:    $items=~s/\&$//;
1.620     albertel 6814:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6815:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6816:    my $uhome=&homeserver($uname,$udomain);
                   6817:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6818: }
                   6819: 
                   6820: # -------------------------------------------------------------- dump interface
                   6821: 
1.1172.2.22  raeburn  6822: sub unserialize {
                   6823:     my ($rep, $escapedkeys) = @_;
                   6824: 
                   6825:     return {} if $rep =~ /^error/;
                   6826: 
                   6827:     my %returnhash=();
                   6828:     foreach my $item (split(/\&/,$rep)) {
                   6829:         my ($key, $value) = split(/=/, $item, 2);
                   6830:         $key = unescape($key) unless $escapedkeys;
                   6831:         next if $key =~ /^error: 2 /;
                   6832:         $returnhash{$key} = &thaw_unescape($value);
                   6833:     }
                   6834:     return \%returnhash;
                   6835: }
                   6836: 
                   6837: # see Lond::dump_with_regexp
                   6838: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6839: sub dump {
1.1172.2.22  raeburn  6840:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6841:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6842:     if (!$uname) { $uname=$env{'user.name'}; }
                   6843:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6844: 
1.1172.2.55  raeburn  6845:     if ($regexp) {
                   6846:         $regexp=&escape($regexp);
                   6847:     } else {
                   6848:         $regexp='.';
                   6849:     }
1.1172.2.22  raeburn  6850:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6851:         # user is hosted on this machine
1.1172.2.55  raeburn  6852:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6853:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6854:         return %{&unserialize($reply, $escapedkeys)};
                   6855:     }
1.1166    raeburn  6856:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6857:     my @pairs=split(/\&/,$rep);
                   6858:     my %returnhash=();
1.1098    foxr     6859:     if (!($rep =~ /^error/ )) {
                   6860: 	foreach my $item (@pairs) {
                   6861: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6862:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6863: 	    next if ($key =~ /^error: 2 /);
                   6864: 	    $returnhash{$key}=&thaw_unescape($value);
                   6865: 	}
1.755     albertel 6866:     }
                   6867:     return %returnhash;
1.407     www      6868: }
                   6869: 
1.1098    foxr     6870: 
1.717     albertel 6871: # --------------------------------------------------------- dumpstore interface
                   6872: 
                   6873: sub dumpstore {
                   6874:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6875:    # same as dump but keys must be escaped. They may contain colon separated
                   6876:    # lists of values that may themself contain colons (e.g. symbs).
                   6877:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6878: }
                   6879: 
1.407     www      6880: # -------------------------------------------------------------- keys interface
                   6881: 
                   6882: sub getkeys {
                   6883:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6884:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6885:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6886:    my $uhome=&homeserver($uname,$udomain);
                   6887:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6888:    my @keyarray=();
1.800     albertel 6889:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6890:       next if ($key =~ /^error: 2 /);
1.800     albertel 6891:       push(@keyarray,&unescape($key));
1.407     www      6892:    }
                   6893:    return @keyarray;
1.318     matthew  6894: }
                   6895: 
1.319     matthew  6896: # --------------------------------------------------------------- currentdump
                   6897: sub currentdump {
1.328     matthew  6898:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6899:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6900:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6901:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6902:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6903:    my $rep;
                   6904: 
                   6905:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6906:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6907:                    $courseid)));
                   6908:    } else {
                   6909:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6910:    }
                   6911: 
1.318     matthew  6912:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6913:    #
1.318     matthew  6914:    my %returnhash=();
1.319     matthew  6915:    #
                   6916:    if ($rep eq "unknown_cmd") { 
                   6917:        # an old lond will not know currentdump
                   6918:        # Do a dump and make it look like a currentdump
1.822     albertel 6919:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6920:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6921:        my %hash = @tmp;
                   6922:        @tmp=();
1.424     matthew  6923:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6924:    } else {
                   6925:        my @pairs=split(/\&/,$rep);
1.800     albertel 6926:        foreach my $pair (@pairs) {
                   6927:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6928:            my ($symb,$param) = split(/:/,$key);
                   6929:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6930:                                                         &thaw_unescape($value);
1.319     matthew  6931:        }
1.191     harris41 6932:    }
1.12      www      6933:    return %returnhash;
1.424     matthew  6934: }
                   6935: 
                   6936: sub convert_dump_to_currentdump{
                   6937:     my %hash = %{shift()};
                   6938:     my %returnhash;
                   6939:     # Code ripped from lond, essentially.  The only difference
                   6940:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6941:     # we might run in to problems with parameter names =~ /^v\./
                   6942:     while (my ($key,$value) = each(%hash)) {
                   6943:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6944: 	$symb  = &unescape($symb);
                   6945: 	$param = &unescape($param);
1.424     matthew  6946:         next if ($v eq 'version' || $symb eq 'keys');
                   6947:         next if (exists($returnhash{$symb}) &&
                   6948:                  exists($returnhash{$symb}->{$param}) &&
                   6949:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6950:         $returnhash{$symb}->{$param}=$value;
                   6951:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6952:     }
                   6953:     #
                   6954:     # Remove all of the keys in the hashes which keep track of
                   6955:     # the version of the parameter.
                   6956:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6957:         # use a foreach because we are going to delete from the hash.
                   6958:         foreach my $key (keys(%$param_hash)) {
                   6959:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6960:         }
                   6961:     }
                   6962:     return \%returnhash;
1.12      www      6963: }
                   6964: 
1.627     albertel 6965: # ------------------------------------------------------ critical inc interface
                   6966: 
                   6967: sub cinc {
                   6968:     return &inc(@_,'critical');
                   6969: }
                   6970: 
1.449     matthew  6971: # --------------------------------------------------------------- inc interface
                   6972: 
                   6973: sub inc {
1.627     albertel 6974:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6975:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6976:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6977:     my $uhome=&homeserver($uname,$udomain);
                   6978:     my $items='';
                   6979:     if (! ref($store)) {
                   6980:         # got a single value, so use that instead
                   6981:         $items = &escape($store).'=&';
                   6982:     } elsif (ref($store) eq 'SCALAR') {
                   6983:         $items = &escape($$store).'=&';        
                   6984:     } elsif (ref($store) eq 'ARRAY') {
                   6985:         $items = join('=&',map {&escape($_);} @{$store});
                   6986:     } elsif (ref($store) eq 'HASH') {
                   6987:         while (my($key,$value) = each(%{$store})) {
                   6988:             $items.= &escape($key).'='.&escape($value).'&';
                   6989:         }
                   6990:     }
                   6991:     $items=~s/\&$//;
1.627     albertel 6992:     if ($critical) {
                   6993: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6994:     } else {
                   6995: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6996:     }
1.449     matthew  6997: }
                   6998: 
1.12      www      6999: # --------------------------------------------------------------- put interface
                   7000: 
                   7001: sub put {
1.134     albertel 7002:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7003:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7004:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7005:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7006:    my $items='';
1.800     albertel 7007:    foreach my $item (keys(%$storehash)) {
                   7008:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7009:    }
1.12      www      7010:    $items=~s/\&$//;
1.134     albertel 7011:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      7012: }
                   7013: 
1.631     albertel 7014: # ------------------------------------------------------------ newput interface
                   7015: 
                   7016: sub newput {
                   7017:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7018:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7019:    if (!$uname) { $uname=$env{'user.name'}; }
                   7020:    my $uhome=&homeserver($uname,$udomain);
                   7021:    my $items='';
                   7022:    foreach my $key (keys(%$storehash)) {
                   7023:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7024:    }
                   7025:    $items=~s/\&$//;
                   7026:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7027: }
                   7028: 
                   7029: # ---------------------------------------------------------  putstore interface
                   7030: 
1.524     raeburn  7031: sub putstore {
1.1172.2.59  raeburn  7032:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7033:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7034:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7035:    my $uhome=&homeserver($uname,$udomain);
                   7036:    my $items='';
1.715     albertel 7037:    foreach my $key (keys(%$storehash)) {
                   7038:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7039:    }
1.715     albertel 7040:    $items=~s/\&$//;
1.716     albertel 7041:    my $esc_symb=&escape($symb);
                   7042:    my $esc_v=&escape($version);
1.715     albertel 7043:    my $reply =
1.716     albertel 7044:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7045: 	      $uhome);
1.1172.2.59  raeburn  7046:    if (($tolog) && ($reply eq 'ok')) {
                   7047:        my $namevalue='';
                   7048:        foreach my $key (keys(%{$storehash})) {
                   7049:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7050:        }
1.1172.2.134  raeburn  7051:        my $ip = &get_requestor_ip();
1.1172.2.135  raeburn  7052:        $namevalue .= 'ip='.&escape($ip).
1.1172.2.59  raeburn  7053:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7054:                      '&version='.$esc_v.
                   7055:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7056:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7057:    }
1.715     albertel 7058:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7059:        # gfall back to way things use to be done
1.715     albertel 7060:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7061: 			    $uname);
1.524     raeburn  7062:    }
1.715     albertel 7063:    return $reply;
                   7064: }
                   7065: 
                   7066: sub old_putstore {
1.716     albertel 7067:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7068:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7069:     if (!$uname) { $uname=$env{'user.name'}; }
                   7070:     my $uhome=&homeserver($uname,$udomain);
                   7071:     my %newstorehash;
1.800     albertel 7072:     foreach my $item (keys(%$storehash)) {
                   7073: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7074: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7075:     }
                   7076:     my $items='';
                   7077:     my %allitems = ();
1.800     albertel 7078:     foreach my $item (keys(%newstorehash)) {
                   7079: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7080: 	    my $key = $1.':keys:'.$2;
                   7081: 	    $allitems{$key} .= $3.':';
                   7082: 	}
1.800     albertel 7083: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7084:     }
1.800     albertel 7085:     foreach my $item (keys(%allitems)) {
                   7086: 	$allitems{$item} =~ s/\:$//;
                   7087: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7088:     }
                   7089:     $items=~s/\&$//;
                   7090:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7091: }
                   7092: 
1.47      www      7093: # ------------------------------------------------------ critical put interface
                   7094: 
                   7095: sub cput {
1.134     albertel 7096:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7097:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7098:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7099:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7100:    my $items='';
1.800     albertel 7101:    foreach my $item (keys(%$storehash)) {
                   7102:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7103:    }
1.47      www      7104:    $items=~s/\&$//;
1.134     albertel 7105:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7106: }
                   7107: 
                   7108: # -------------------------------------------------------------- eget interface
                   7109: 
                   7110: sub eget {
1.133     albertel 7111:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7112:    my $items='';
1.800     albertel 7113:    foreach my $item (@$storearr) {
                   7114:        $items.=&escape($item).'&';
1.191     harris41 7115:    }
1.12      www      7116:    $items=~s/\&$//;
1.620     albertel 7117:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7118:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7119:    my $uhome=&homeserver($uname,$udomain);
                   7120:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7121:    my @pairs=split(/\&/,$rep);
                   7122:    my %returnhash=();
1.42      www      7123:    my $i=0;
1.800     albertel 7124:    foreach my $item (@$storearr) {
                   7125:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7126:       $i++;
1.191     harris41 7127:    }
1.12      www      7128:    return %returnhash;
                   7129: }
                   7130: 
1.667     albertel 7131: # ------------------------------------------------------------ tmpput interface
                   7132: sub tmpput {
1.802     raeburn  7133:     my ($storehash,$server,$context)=@_;
1.667     albertel 7134:     my $items='';
1.800     albertel 7135:     foreach my $item (keys(%$storehash)) {
                   7136: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7137:     }
                   7138:     $items=~s/\&$//;
1.802     raeburn  7139:     if (defined($context)) {
                   7140:         $items .= ':'.&escape($context);
                   7141:     }
1.667     albertel 7142:     return &reply("tmpput:$items",$server);
                   7143: }
                   7144: 
                   7145: # ------------------------------------------------------------ tmpget interface
                   7146: sub tmpget {
1.688     albertel 7147:     my ($token,$server)=@_;
                   7148:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7149:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7150:     my %returnhash;
1.1172.2.85  raeburn  7151:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7152:         return %returnhash;
                   7153:     }
1.667     albertel 7154:     foreach my $item (split(/\&/,$rep)) {
                   7155: 	my ($key,$value)=split(/=/,$item);
                   7156: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7157:     }
                   7158:     return %returnhash;
                   7159: }
                   7160: 
1.1113    raeburn  7161: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7162: sub tmpdel {
                   7163:     my ($token,$server)=@_;
                   7164:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7165:     return &reply("tmpdel:$token",$server);
                   7166: }
                   7167: 
1.1172.2.13  raeburn  7168: # ------------------------------------------------------------ get_timebased_id
                   7169: 
                   7170: sub get_timebased_id {
                   7171:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7172:         $maxtries) = @_;
                   7173:     my ($newid,$error,$dellock);
                   7174:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7175:         return ('','ok','invalid call to get suffix');
                   7176:     }
                   7177: 
                   7178: # set defaults for any optional args for which values were not supplied
                   7179:     if ($who eq '') {
                   7180:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7181:     }
                   7182:     if (!$locktries) {
                   7183:         $locktries = 3;
                   7184:     }
                   7185:     if (!$maxtries) {
                   7186:         $maxtries = 10;
                   7187:     }
                   7188: 
                   7189:     if (($cdom eq '') || ($cnum eq '')) {
                   7190:         if ($env{'request.course.id'}) {
                   7191:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7192:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7193:         }
                   7194:         if (($cdom eq '') || ($cnum eq '')) {
                   7195:             return ('','ok','call to get suffix not in course context');
                   7196:         }
                   7197:     }
                   7198: 
                   7199: # construct locking item
                   7200:     my $lockhash = {
                   7201:                       $prefix."\0".'locked_'.$keyid => $who,
                   7202:                    };
                   7203:     my $tries = 0;
                   7204: 
                   7205: # attempt to get lock on nohist_$namespace file
                   7206:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7207:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7208:         $tries ++;
                   7209:         sleep 1;
                   7210:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7211:     }
                   7212: 
                   7213: # attempt to get unique identifier, based on current timestamp
                   7214:     if ($gotlock eq 'ok') {
                   7215:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7216:         my $id = time;
                   7217:         $newid = $id;
1.1172.2.56  raeburn  7218:         if ($idtype eq 'addcode') {
                   7219:             $newid .= &sixnum_code();
                   7220:         }
1.1172.2.13  raeburn  7221:         my $idtries = 0;
                   7222:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7223:             if ($idtype eq 'concat') {
                   7224:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7225:             } elsif ($idtype eq 'addcode') {
                   7226:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7227:             } else {
                   7228:                 $newid ++;
                   7229:             }
                   7230:             $idtries ++;
                   7231:         }
                   7232:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7233:             my %new_item =  (
                   7234:                               $prefix."\0".$newid => $who,
                   7235:                             );
                   7236:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7237:                                                  $cdom,$cnum);
                   7238:             if ($putresult ne 'ok') {
                   7239:                 undef($newid);
                   7240:                 $error = 'error saving new item: '.$putresult;
                   7241:             }
                   7242:         } else {
1.1172.2.56  raeburn  7243:              undef($newid);
1.1172.2.13  raeburn  7244:              $error = ('error: no unique suffix available for the new item ');
                   7245:         }
                   7246: #  remove lock
                   7247:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7248:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7249:     } else {
                   7250:         $error = "error: could not obtain lockfile\n";
                   7251:         $dellock = 'ok';
1.1172.2.58  raeburn  7252:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7253:             $dellock = 'nolock';
                   7254:         }
1.1172.2.13  raeburn  7255:     }
                   7256:     return ($newid,$dellock,$error);
                   7257: }
                   7258: 
1.1172.2.56  raeburn  7259: sub sixnum_code {
                   7260:     my $code;
                   7261:     for (0..6) {
                   7262:         $code .= int( rand(9) );
                   7263:     }
                   7264:     return $code;
                   7265: }
                   7266: 
1.765     albertel 7267: # -------------------------------------------------- portfolio access checking
                   7268: 
                   7269: sub portfolio_access {
1.1172.2.77  raeburn  7270:     my ($requrl,$clientip) = @_;
1.765     albertel 7271:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7272:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7273:     if ($result) {
                   7274:         my %setters;
                   7275:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7276:             my ($startblock,$endblock) =
                   7277:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7278:             if ($startblock && $endblock) {
                   7279:                 return 'B';
                   7280:             }
                   7281:         } else {
                   7282:             my ($startblock,$endblock) =
                   7283:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7284:             if ($startblock && $endblock) {
                   7285:                 return 'B';
                   7286:             }
                   7287:         }
                   7288:     }
1.765     albertel 7289:     if ($result eq 'ok') {
1.766     albertel 7290:        return 'F';
1.765     albertel 7291:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7292:        return 'A';
1.765     albertel 7293:     }
1.766     albertel 7294:     return '';
1.765     albertel 7295: }
                   7296: 
                   7297: sub get_portfolio_access {
1.1172.2.77  raeburn  7298:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7299: 
                   7300:     if (!ref($access_hash)) {
                   7301: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7302: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7303: 						   $file_name);
                   7304: 	$access_hash = $access_controls{$file_name};
                   7305:     }
                   7306: 
1.1172.2.77  raeburn  7307:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7308:     my $now = time;
                   7309:     if (ref($access_hash) eq 'HASH') {
                   7310:         foreach my $key (keys(%{$access_hash})) {
                   7311:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7312:             if ($start > $now) {
                   7313:                 next;
                   7314:             }
                   7315:             if ($end && $end<$now) {
                   7316:                 next;
                   7317:             }
                   7318:             if ($scope eq 'public') {
                   7319:                 $public = $key;
                   7320:                 last;
                   7321:             } elsif ($scope eq 'guest') {
                   7322:                 $guest = $key;
                   7323:             } elsif ($scope eq 'domains') {
                   7324:                 push(@domains,$key);
                   7325:             } elsif ($scope eq 'users') {
                   7326:                 push(@users,$key);
                   7327:             } elsif ($scope eq 'course') {
                   7328:                 push(@courses,$key);
                   7329:             } elsif ($scope eq 'group') {
                   7330:                 push(@groups,$key);
1.1172.2.77  raeburn  7331:             } elsif ($scope eq 'ip') {
                   7332:                 push(@ips,$key);
1.765     albertel 7333:             }
                   7334:         }
                   7335:         if ($public) {
                   7336:             return 'ok';
1.1172.2.77  raeburn  7337:         } elsif (@ips > 0) {
                   7338:             my $allowed;
                   7339:             foreach my $ipkey (@ips) {
                   7340:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7341:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7342:                         $allowed = 1;
                   7343:                         last;
                   7344:                     }
                   7345:                 }
                   7346:             }
                   7347:             if ($allowed) {
                   7348:                 return 'ok';
                   7349:             }
1.765     albertel 7350:         }
                   7351:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7352:             if ($guest) {
                   7353:                 return $guest;
                   7354:             }
                   7355:         } else {
                   7356:             if (@domains > 0) {
                   7357:                 foreach my $domkey (@domains) {
                   7358:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7359:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7360:                             return 'ok';
                   7361:                         }
                   7362:                     }
                   7363:                 }
                   7364:             }
                   7365:             if (@users > 0) {
                   7366:                 foreach my $userkey (@users) {
1.865     raeburn  7367:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7368:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7369:                             if (ref($item) eq 'HASH') {
                   7370:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7371:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7372:                                     return 'ok';
                   7373:                                 }
                   7374:                             }
                   7375:                         }
                   7376:                     } 
1.765     albertel 7377:                 }
                   7378:             }
                   7379:             my %roleshash;
                   7380:             my @courses_and_groups = @courses;
                   7381:             push(@courses_and_groups,@groups); 
                   7382:             if (@courses_and_groups > 0) {
                   7383:                 my (%allgroups,%allroles); 
                   7384:                 my ($start,$end,$role,$sec,$group);
                   7385:                 foreach my $envkey (%env) {
1.1060    raeburn  7386:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7387:                         my $cid = $2.'_'.$3; 
                   7388:                         if ($1 eq 'gr') {
                   7389:                             $group = $4;
                   7390:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7391:                         } else {
                   7392:                             if ($4 eq '') {
                   7393:                                 $sec = 'none';
                   7394:                             } else {
                   7395:                                 $sec = $4;
                   7396:                             }
                   7397:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7398:                         }
1.811     albertel 7399:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7400:                         my $cid = $2.'_'.$3;
                   7401:                         if ($4 eq '') {
                   7402:                             $sec = 'none';
                   7403:                         } else {
                   7404:                             $sec = $4;
                   7405:                         }
                   7406:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7407:                     }
                   7408:                 }
                   7409:                 if (keys(%allroles) == 0) {
                   7410:                     return;
                   7411:                 }
                   7412:                 foreach my $key (@courses_and_groups) {
                   7413:                     my %content = %{$$access_hash{$key}};
                   7414:                     my $cnum = $content{'number'};
                   7415:                     my $cdom = $content{'domain'};
                   7416:                     my $cid = $cdom.'_'.$cnum;
                   7417:                     if (!exists($allroles{$cid})) {
                   7418:                         next;
                   7419:                     }    
                   7420:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7421:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7422:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7423:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7424:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7425:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7426:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7427:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7428:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7429:                                         if (grep/^all$/,@sections) {
                   7430:                                             return 'ok';
                   7431:                                         } else {
                   7432:                                             if (grep/^$sec$/,@sections) {
                   7433:                                                 return 'ok';
                   7434:                                             }
                   7435:                                         }
                   7436:                                     }
                   7437:                                 }
                   7438:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7439:                                     if (grep/^none$/,@groups) {
                   7440:                                         return 'ok';
                   7441:                                     }
                   7442:                                 } else {
                   7443:                                     if (grep/^all$/,@groups) {
                   7444:                                         return 'ok';
                   7445:                                     } 
                   7446:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7447:                                         if (grep/^$group$/,@groups) {
                   7448:                                             return 'ok';
                   7449:                                         }
                   7450:                                     }
                   7451:                                 } 
                   7452:                             }
                   7453:                         }
                   7454:                     }
                   7455:                 }
                   7456:             }
                   7457:             if ($guest) {
                   7458:                 return $guest;
                   7459:             }
                   7460:         }
                   7461:     }
                   7462:     return;
                   7463: }
                   7464: 
                   7465: sub course_group_datechecker {
                   7466:     my ($dates,$now,$status) = @_;
                   7467:     my ($start,$end) = split(/\./,$dates);
                   7468:     if (!$start && !$end) {
                   7469:         return 'ok';
                   7470:     }
                   7471:     if (grep/^active$/,@{$status}) {
                   7472:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7473:             return 'ok';
                   7474:         }
                   7475:     }
                   7476:     if (grep/^previous$/,@{$status}) {
                   7477:         if ($end > $now ) {
                   7478:             return 'ok';
                   7479:         }
                   7480:     }
                   7481:     if (grep/^future$/,@{$status}) {
                   7482:         if ($start > $now) {
                   7483:             return 'ok';
                   7484:         }
                   7485:     }
                   7486:     return; 
                   7487: }
                   7488: 
                   7489: sub parse_portfolio_url {
                   7490:     my ($url) = @_;
                   7491: 
                   7492:     my ($type,$udom,$unum,$group,$file_name);
                   7493:     
1.823     albertel 7494:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7495: 	$type = 1;
                   7496:         $udom = $1;
                   7497:         $unum = $2;
                   7498:         $file_name = $3;
1.823     albertel 7499:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7500: 	$type = 2;
                   7501:         $udom = $1;
                   7502:         $unum = $2;
                   7503:         $group = $3;
                   7504:         $file_name = $3.'/'.$4;
                   7505:     }
                   7506:     if (wantarray) {
                   7507: 	return ($type,$udom,$unum,$file_name,$group);
                   7508:     }
                   7509:     return $type;
                   7510: }
                   7511: 
                   7512: sub is_portfolio_url {
                   7513:     my ($url) = @_;
                   7514:     return scalar(&parse_portfolio_url($url));
                   7515: }
                   7516: 
1.798     raeburn  7517: sub is_portfolio_file {
                   7518:     my ($file) = @_;
1.820     raeburn  7519:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7520:         return 1;
                   7521:     }
                   7522:     return;
                   7523: }
                   7524: 
1.976     raeburn  7525: sub usertools_access {
1.1084    raeburn  7526:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7527:     my ($access,%tools);
                   7528:     if ($context eq '') {
                   7529:         $context = 'tools';
                   7530:     }
                   7531:     if ($context eq 'requestcourses') {
                   7532:         %tools = (
                   7533:                       official   => 1,
                   7534:                       unofficial => 1,
1.1006    raeburn  7535:                       community  => 1,
1.1172.2.37  raeburn  7536:                       textbook   => 1,
1.985     raeburn  7537:                  );
1.1172.2.9  raeburn  7538:     } elsif ($context eq 'requestauthor') {
                   7539:         %tools = (
                   7540:                       requestauthor => 1,
                   7541:                  );
1.985     raeburn  7542:     } else {
                   7543:         %tools = (
                   7544:                       aboutme   => 1,
                   7545:                       blog      => 1,
1.1172.2.6  raeburn  7546:                       webdav    => 1,
1.985     raeburn  7547:                       portfolio => 1,
                   7548:                  );
                   7549:     }
1.976     raeburn  7550:     return if (!defined($tools{$tool}));
                   7551: 
1.1172.2.35  raeburn  7552:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7553:         $udom = $env{'user.domain'};
                   7554:         $uname = $env{'user.name'};
                   7555:     }
                   7556: 
1.978     raeburn  7557:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7558:         if ($action ne 'reload') {
1.985     raeburn  7559:             if ($context eq 'requestcourses') {
                   7560:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7561:             } elsif ($context eq 'requestauthor') {
                   7562:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7563:             } else {
                   7564:                 return $env{'environment.availabletools.'.$tool};
                   7565:             }
                   7566:         }
1.976     raeburn  7567:     }
                   7568: 
1.1172.2.9  raeburn  7569:     my ($toolstatus,$inststatus,$envkey);
                   7570:     if ($context eq 'requestauthor') {
                   7571:         $envkey = $context;
                   7572:     } else {
                   7573:         $envkey = $context.'.'.$tool;
                   7574:     }
1.976     raeburn  7575: 
1.985     raeburn  7576:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7577:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7578:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7579:         $inststatus = $env{'environment.inststatus'};
                   7580:     } else {
1.1084    raeburn  7581:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7582:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7583:             $inststatus = $userenvref->{'inststatus'};
                   7584:         } else {
1.1172.2.9  raeburn  7585:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7586:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7587:             $inststatus = $userenv{'inststatus'};
                   7588:         }
1.976     raeburn  7589:     }
                   7590: 
                   7591:     if ($toolstatus ne '') {
                   7592:         if ($toolstatus) {
                   7593:             $access = 1;
                   7594:         } else {
                   7595:             $access = 0;
                   7596:         }
                   7597:         return $access;
                   7598:     }
                   7599: 
1.1084    raeburn  7600:     my ($is_adv,%domdef);
                   7601:     if (ref($is_advref) eq 'HASH') {
                   7602:         $is_adv = $is_advref->{'is_adv'};
                   7603:     } else {
                   7604:         $is_adv = &is_advanced_user($udom,$uname);
                   7605:     }
                   7606:     if (ref($domdefref) eq 'HASH') {
                   7607:         %domdef = %{$domdefref};
                   7608:     } else {
                   7609:         %domdef = &get_domain_defaults($udom);
                   7610:     }
1.976     raeburn  7611:     if (ref($domdef{$tool}) eq 'HASH') {
                   7612:         if ($is_adv) {
                   7613:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7614:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7615:                     $access = 1;
                   7616:                 } else {
                   7617:                     $access = 0;
                   7618:                 }
                   7619:                 return $access;
                   7620:             }
                   7621:         }
                   7622:         if ($inststatus ne '') {
                   7623:             my ($hasaccess,$hasnoaccess);
                   7624:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7625:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7626:                     if ($domdef{$tool}{$affiliation}) {
                   7627:                         $hasaccess = 1;
                   7628:                     } else {
                   7629:                         $hasnoaccess = 1;
                   7630:                     }
                   7631:                 }
                   7632:             }
                   7633:             if ($hasaccess || $hasnoaccess) {
                   7634:                 if ($hasaccess) {
                   7635:                     $access = 1;
                   7636:                 } elsif ($hasnoaccess) {
                   7637:                     $access = 0; 
                   7638:                 }
                   7639:                 return $access;
                   7640:             }
                   7641:         } else {
                   7642:             if ($domdef{$tool}{'default'} ne '') {
                   7643:                 if ($domdef{$tool}{'default'}) {
                   7644:                     $access = 1;
                   7645:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7646:                     $access = 0;
                   7647:                 }
                   7648:                 return $access;
                   7649:             }
                   7650:         }
                   7651:     } else {
1.1172.2.6  raeburn  7652:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7653:             $access = 1;
                   7654:         } else {
                   7655:             $access = 0;
                   7656:         }
1.976     raeburn  7657:         return $access;
                   7658:     }
                   7659: }
                   7660: 
1.1050    raeburn  7661: sub is_course_owner {
                   7662:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7663:     if (($udom eq '') || ($uname eq '')) {
                   7664:         $udom = $env{'user.domain'};
                   7665:         $uname = $env{'user.name'};
                   7666:     }
                   7667:     unless (($udom eq '') || ($uname eq '')) {
                   7668:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7669:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7670:                 return 1;
                   7671:             } else {
                   7672:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7673:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7674:                     return 1;
                   7675:                 }
                   7676:             }
                   7677:         }
                   7678:     }
                   7679:     return;
                   7680: }
                   7681: 
1.976     raeburn  7682: sub is_advanced_user {
                   7683:     my ($udom,$uname) = @_;
1.1085    raeburn  7684:     if ($udom ne '' && $uname ne '') {
                   7685:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7686:             if (wantarray) {
                   7687:                 return ($env{'user.adv'},$env{'user.author'});
                   7688:             } else {
                   7689:                 return $env{'user.adv'};
                   7690:             }
1.1085    raeburn  7691:         }
                   7692:     }
1.976     raeburn  7693:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7694:     my %allroles;
1.1128    raeburn  7695:     my ($is_adv,$is_author);
1.976     raeburn  7696:     foreach my $role (keys(%roleshash)) {
                   7697:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7698:         my $area = '/'.$tdomain.'/'.$trest;
                   7699:         if ($sec ne '') {
                   7700:             $area .= '/'.$sec;
                   7701:         }
                   7702:         if (($area ne '') && ($trole ne '')) {
                   7703:             my $spec=$trole.'.'.$area;
                   7704:             if ($trole =~ /^cr\//) {
                   7705:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7706:             } elsif ($trole ne 'gr') {
                   7707:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7708:             }
1.1128    raeburn  7709:             if ($trole eq 'au') {
                   7710:                 $is_author = 1;
                   7711:             }
1.976     raeburn  7712:         }
                   7713:     }
                   7714:     foreach my $role (keys(%allroles)) {
                   7715:         last if ($is_adv);
                   7716:         foreach my $item (split(/:/,$allroles{$role})) {
                   7717:             if ($item ne '') {
                   7718:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7719:                 if ($privilege eq 'adv') {
                   7720:                     $is_adv = 1;
                   7721:                     last;
                   7722:                 }
                   7723:             }
                   7724:         }
                   7725:     }
1.1128    raeburn  7726:     if (wantarray) {
                   7727:         return ($is_adv,$is_author);
                   7728:     }
1.976     raeburn  7729:     return $is_adv;
                   7730: }
1.798     raeburn  7731: 
1.1035    raeburn  7732: sub check_can_request {
1.1036    raeburn  7733:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7734:     my $canreq = 0;
                   7735:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7736:     my @options = ('approval','validate','autolimit');
                   7737:     my $optregex = join('|',@options);
                   7738:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7739:         foreach my $type (@{$types}) {
                   7740:             if (&usertools_access($env{'user.name'},
                   7741:                                   $env{'user.domain'},
                   7742:                                   $type,undef,'requestcourses')) {
                   7743:                 $canreq ++;
1.1036    raeburn  7744:                 if (ref($request_domains) eq 'HASH') {
                   7745:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7746:                 }
1.1035    raeburn  7747:                 if ($dom eq $env{'user.domain'}) {
                   7748:                     $can_request->{$type} = 1;
                   7749:                 }
                   7750:             }
                   7751:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7752:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7753:                 if (@curr > 0) {
1.1036    raeburn  7754:                     foreach my $item (@curr) {
                   7755:                         if (ref($request_domains) eq 'HASH') {
                   7756:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7757:                             if ($otherdom ne '') {
                   7758:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7759:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7760:                                         push(@{$request_domains->{$type}},$otherdom);
                   7761:                                     }
                   7762:                                 } else {
                   7763:                                     push(@{$request_domains->{$type}},$otherdom);
                   7764:                                 }
                   7765:                             }
                   7766:                         }
                   7767:                     }
                   7768:                     unless($dom eq $env{'user.domain'}) {
                   7769:                         $canreq ++;
1.1035    raeburn  7770:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7771:                             $can_request->{$type} = 1;
                   7772:                         }
                   7773:                     }
                   7774:                 }
                   7775:             }
                   7776:         }
                   7777:     }
                   7778:     return $canreq;
                   7779: }
                   7780: 
1.341     www      7781: # ---------------------------------------------- Custom access rule evaluation
                   7782: 
                   7783: sub customaccess {
                   7784:     my ($priv,$uri)=@_;
1.807     albertel 7785:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7786:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7787:     $udom = &LONCAPA::clean_domain($udom);
                   7788:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7789:     my $access=0;
1.800     albertel 7790:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7791: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7792: 	if ($type eq 'user') {
                   7793: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7794: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7795: 		if ($tdom) {
                   7796: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7797: 		}
1.896     albertel 7798: 		if ($tuname) {
                   7799: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7800: 		}
                   7801: 		$access=($effect eq 'allow');
                   7802: 		last;
                   7803: 	    }
                   7804: 	} else {
                   7805: 	    if ($role) {
                   7806: 		if ($role ne $urole) { next; }
                   7807: 	    }
                   7808: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7809: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7810: 		if ($tdom) {
                   7811: 		    if ($tdom ne $udom) { next; }
                   7812: 		}
                   7813: 		if ($tcrs) {
                   7814: 		    if ($tcrs ne $ucrs) { next; }
                   7815: 		}
                   7816: 		if ($tsec) {
                   7817: 		    if ($tsec ne $usec) { next; }
                   7818: 		}
                   7819: 		$access=($effect eq 'allow');
                   7820: 		last;
                   7821: 	    }
                   7822: 	    if ($realm eq '' && $role eq '') {
                   7823: 		$access=($effect eq 'allow');
                   7824: 	    }
1.402     bowersj2 7825: 	}
1.341     www      7826:     }
                   7827:     return $access;
                   7828: }
                   7829: 
1.103     harris41 7830: # ------------------------------------------------- Check for a user privilege
1.12      www      7831: 
                   7832: sub allowed {
1.1172.2.126  raeburn  7833:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
1.705     albertel 7834:     my $ver_orguri=$uri;
1.439     www      7835:     $uri=&deversion($uri);
1.152     www      7836:     my $orguri=$uri;
1.52      www      7837:     $uri=&declutter($uri);
1.809     raeburn  7838: 
1.810     raeburn  7839:     if ($priv eq 'evb') {
                   7840: # Evade communication block restrictions for specified role in a course
                   7841:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7842:             return $1;
                   7843:         } else {
                   7844:             return;
                   7845:         }
                   7846:     }
                   7847: 
1.620     albertel 7848:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7849: # Free bre access to adm and meta resources
1.1172.2.133  raeburn  7850:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme)$})) 
1.769     albertel 7851: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7852: 	&& ($priv eq 'bre')) {
1.14      www      7853: 	return 'F';
1.159     www      7854:     }
                   7855: 
1.545     banghart 7856: # Free bre access to user's own portfolio contents
1.714     raeburn  7857:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7858:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7859: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7860:         my %setters;
                   7861:         my ($startblock,$endblock) = 
                   7862:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7863:         if ($startblock && $endblock) {
                   7864:             return 'B';
                   7865:         } else {
                   7866:             return 'F';
                   7867:         }
1.545     banghart 7868:     }
                   7869: 
1.762     raeburn  7870: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7871:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7872:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7873:         if (exists($env{'request.course.id'})) {
                   7874:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7875:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7876:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7877:                 my $courseprivid=$env{'request.course.id'};
                   7878:                 $courseprivid=~s/\_/\//;
                   7879:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7880:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7881:                     return $1; 
1.762     raeburn  7882:                 } else {
                   7883:                     if ($env{'request.course.sec'}) {
                   7884:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7885:                     }
                   7886:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7887:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7888:                         return $2;
                   7889:                     }
1.714     raeburn  7890:                 }
                   7891:             }
                   7892:         }
                   7893:     }
                   7894: 
1.159     www      7895: # Free bre to public access
                   7896: 
                   7897:     if ($priv eq 'bre') {
1.238     www      7898:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7899: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7900:            return 'F'; 
                   7901:         }
1.238     www      7902:         if ($copyright eq 'priv') {
                   7903:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7904: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7905: 		return '';
                   7906:             }
                   7907:         }
                   7908:         if ($copyright eq 'domain') {
                   7909:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7910: 	    unless (($env{'user.domain'} eq $1) ||
                   7911:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7912: 		return '';
                   7913:             }
1.262     matthew  7914:         }
1.620     albertel 7915:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7916:             # Library role, so allow browsing of resources in this domain.
                   7917:             return 'F';
1.238     www      7918:         }
1.341     www      7919:         if ($copyright eq 'custom') {
                   7920: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7921:         }
1.14      www      7922:     }
1.264     matthew  7923:     # Domain coordinator is trying to create a course
1.620     albertel 7924:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7925:         # uri is the requested domain in this case.
                   7926:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7927:         # a role of dc for the domain in question.
1.620     albertel 7928:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7929:     }
1.29      www      7930: 
1.52      www      7931:     my $thisallowed='';
                   7932:     my $statecond=0;
                   7933:     my $courseprivid='';
                   7934: 
1.1039    raeburn  7935:     my $ownaccess;
1.1043    raeburn  7936:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7937:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7938:         if ($uri eq '') {
                   7939:             $ownaccess = 1;
                   7940:         } else {
                   7941:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7942:                 my $udom = $env{'user.domain'};
                   7943:                 my $uname = $env{'user.name'};
                   7944:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7945:                     $ownaccess = 1;
1.1040    raeburn  7946:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7947:                     unless ($uri =~ m{\.\./}) {
                   7948:                         $ownaccess = 1;
                   7949:                     }
                   7950:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7951:                     my $now = time;
                   7952:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7953:                         my $adom = $1;
                   7954:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7955:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7956:                                 my ($start,$end) = split('.',$env{$key});
                   7957:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7958:                                     $ownaccess = 1;
                   7959:                                     last;
                   7960:                                 }
                   7961:                             }
                   7962:                         }
                   7963:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7964:                         my $adom = $1;
                   7965:                         my $aname = $2;
1.1042    raeburn  7966:                         foreach my $role ('ca','aa') { 
                   7967:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7968:                                 my ($start,$end) =
                   7969:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7970:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7971:                                     $ownaccess = 1;
                   7972:                                     last;
                   7973:                                 }
1.1039    raeburn  7974:                             }
                   7975:                         }
                   7976:                     }
                   7977:                 }
                   7978:             }
                   7979:         }
                   7980:     }
                   7981: 
1.52      www      7982: # Course
                   7983: 
1.620     albertel 7984:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7985:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7986:             $thisallowed.=$1;
                   7987:         }
1.52      www      7988:     }
1.29      www      7989: 
1.52      www      7990: # Domain
                   7991: 
1.620     albertel 7992:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7993:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7994:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7995:             $thisallowed.=$1;
                   7996:         }
1.12      www      7997:     }
1.52      www      7998: 
1.1141    raeburn  7999: # User who is not author or co-author might still be able to edit
                   8000: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8001:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8002:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8003:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8004:             $thisallowed.=$1;
                   8005:         }
                   8006:     }
                   8007: 
1.52      www      8008: # Course: uri itself is a course
1.66      www      8009:     my $courseuri=$uri;
                   8010:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8011:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8012: 
1.620     albertel 8013:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8014:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  8015:         if ($priv eq 'mip') {
                   8016:             my $rem = $1;
                   8017:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8018:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8019:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8020:                 if ($cdom ne '') {
                   8021:                     my %passwdconf = &get_passwdconf($cdom);
                   8022:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8023:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8024:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8025:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8026:                                 unless (@inststatuses) {
                   8027:                                     @inststatuses = ('default');
                   8028:                                 }
                   8029:                                 foreach my $status (@inststatuses) {
                   8030:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8031:                                         $thisallowed.=$rem;
                   8032:                                     }
                   8033:                                 }
                   8034:                             }
                   8035:                         }
                   8036:                     }
                   8037:                 }
                   8038:             }
                   8039:         } else {
                   8040:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8041:                 $thisallowed.=$1;
                   8042:             }
1.1039    raeburn  8043:         }
1.12      www      8044:     }
1.29      www      8045: 
1.665     albertel 8046: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8047: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8048:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8049: 	$thisallowed='';
1.671     raeburn  8050:         my ($match)=&is_on_map($uri);
                   8051:         if ($match) {
                   8052:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8053:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  8054:                 my $value = $1;
                   8055:                 if ($noblockcheck) {
                   8056:                     $thisallowed.=$value;
1.1162    raeburn  8057:                 } else {
1.1172.2.126  raeburn  8058:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8059:                     if (@blockers > 0) {
                   8060:                         $thisallowed = 'B';
                   8061:                     } else {
                   8062:                         $thisallowed.=$value;
                   8063:                     }
1.1162    raeburn  8064:                 }
1.671     raeburn  8065:             }
                   8066:         } else {
1.705     albertel 8067:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8068:             if ($refuri) {
                   8069:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8070:                     $thisallowed='F';
1.671     raeburn  8071:                 } else {
                   8072:                     $refuri=&declutter($refuri);
                   8073:                     my ($match) = &is_on_map($refuri);
                   8074:                     if ($match) {
1.1172.2.65  raeburn  8075:                         if ($noblockcheck) {
1.1162    raeburn  8076:                             $thisallowed='F';
1.1172.2.65  raeburn  8077:                         } else {
1.1172.2.127  raeburn  8078:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8079:                             if (@blockers > 0) {
                   8080:                                 $thisallowed = 'B';
                   8081:                             } else {
                   8082:                                 $thisallowed='F';
                   8083:                             }
1.1162    raeburn  8084:                         }
1.671     raeburn  8085:                     }
1.669     raeburn  8086:                 }
1.671     raeburn  8087:             }
                   8088:         }
1.314     www      8089:     }
1.492     albertel 8090: 
1.766     albertel 8091:     if ($priv eq 'bre'
                   8092: 	&& $thisallowed ne 'F' 
                   8093: 	&& $thisallowed ne '2'
                   8094: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8095: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8096:     }
                   8097:     
1.52      www      8098: # Full access at system, domain or course-wide level? Exit.
1.29      www      8099:     if ($thisallowed=~/F/) {
                   8100: 	return 'F';
                   8101:     }
                   8102: 
1.52      www      8103: # If this is generating or modifying users, exit with special codes
1.29      www      8104: 
1.643     www      8105:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8106: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8107: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8108: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8109: 	    unless ($auname) { return $thisallowed; }
                   8110: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8111: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8112: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8113: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8114: 	}
1.52      www      8115: 	return $thisallowed;
                   8116:     }
                   8117: #
1.103     harris41 8118: # Gathered so far: system, domain and course wide privileges
1.52      www      8119: #
                   8120: # Course: See if uri or referer is an individual resource that is part of 
                   8121: # the course
                   8122: 
1.620     albertel 8123:     if ($env{'request.course.id'}) {
1.232     www      8124: 
1.1172.2.115  raeburn  8125: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8126: 
                   8127:         if ($priv eq 'mip') {
                   8128:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8129:                 return $thisallowed;
                   8130:             } else {
                   8131:                 return '';
                   8132:             }
                   8133:         }
                   8134: 
1.620     albertel 8135:        $courseprivid=$env{'request.course.id'};
                   8136:        if ($env{'request.course.sec'}) {
                   8137:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8138:        }
                   8139:        $courseprivid=~s/\_/\//;
                   8140:        my $checkreferer=1;
1.232     www      8141:        my ($match,$cond)=&is_on_map($uri);
                   8142:        if ($match) {
                   8143:            $statecond=$cond;
1.620     albertel 8144:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8145:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8146:                my $value = $1;
                   8147:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  8148:                    if ($noblockcheck) {
1.1162    raeburn  8149:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8150:                    } else {
1.1172.2.126  raeburn  8151:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8152:                        if (@blockers > 0) {
                   8153:                            $thisallowed = 'B';
                   8154:                        } else {
                   8155:                            $thisallowed.=$value;
                   8156:                        }
1.1162    raeburn  8157:                    }
                   8158:                } else {
                   8159:                    $thisallowed.=$value;
                   8160:                }
1.52      www      8161:                $checkreferer=0;
                   8162:            }
1.29      www      8163:        }
1.1172.2.126  raeburn  8164: 
1.148     www      8165:        if ($checkreferer) {
1.620     albertel 8166: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8167:             unless ($refuri) {
1.800     albertel 8168:                 foreach my $key (keys(%env)) {
                   8169: 		    if ($key=~/^httpref\..*\*/) {
                   8170: 			my $pattern=$key;
1.156     www      8171:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8172:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8173:                         $pattern=~s/\//\\\//g;
1.152     www      8174:                         if ($orguri=~/$pattern/) {
1.800     albertel 8175: 			    $refuri=$env{$key};
1.148     www      8176:                         }
                   8177:                     }
1.191     harris41 8178:                 }
1.148     www      8179:             }
1.232     www      8180: 
1.148     www      8181:          if ($refuri) { 
1.152     www      8182: 	  $refuri=&declutter($refuri);
1.232     www      8183:           my ($match,$cond)=&is_on_map($refuri);
                   8184:             if ($match) {
                   8185:               my $refstatecond=$cond;
1.620     albertel 8186:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8187:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8188:                   my $value = $1;
                   8189:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  8190:                       if ($noblockcheck) {
1.1162    raeburn  8191:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8192:                       } else {
1.1172.2.127  raeburn  8193:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8194:                           if (@blockers > 0) {
                   8195:                               $thisallowed = 'B';
                   8196:                           } else {
                   8197:                               $thisallowed.=$value;
                   8198:                           }
1.1162    raeburn  8199:                       }
                   8200:                   } else {
                   8201:                       $thisallowed.=$value;
                   8202:                   }
1.53      www      8203:                   $uri=$refuri;
                   8204:                   $statecond=$refstatecond;
1.52      www      8205:               }
                   8206:           }
1.148     www      8207:         }
1.29      www      8208:        }
1.52      www      8209:    }
1.29      www      8210: 
1.52      www      8211: #
1.103     harris41 8212: # Gathered now: all privileges that could apply, and condition number
1.52      www      8213: # 
                   8214: #
                   8215: # Full or no access?
                   8216: #
1.29      www      8217: 
1.52      www      8218:     if ($thisallowed=~/F/) {
                   8219: 	return 'F';
                   8220:     }
1.29      www      8221: 
1.52      www      8222:     unless ($thisallowed) {
                   8223:         return '';
                   8224:     }
1.29      www      8225: 
1.52      www      8226: # Restrictions exist, deal with them
                   8227: #
                   8228: #   C:according to course preferences
                   8229: #   R:according to resource settings
                   8230: #   L:unless locked
                   8231: #   X:according to user session state
                   8232: #
                   8233: 
                   8234: # Possibly locked functionality, check all courses
1.54      www      8235: # Locks might take effect only after 10 minutes cache expiration for other
                   8236: # courses, and 2 minutes for current course
1.52      www      8237: 
                   8238:     my $envkey;
                   8239:     if ($thisallowed=~/L/) {
1.1000    raeburn  8240:         foreach $envkey (keys(%env)) {
1.54      www      8241:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8242:                my $courseid=$2;
                   8243:                my $roleid=$1.'.'.$2;
1.92      www      8244:                $courseid=~s/^\///;
1.54      www      8245:                my $expiretime=600;
1.620     albertel 8246:                if ($env{'request.role'} eq $roleid) {
1.54      www      8247: 		  $expiretime=120;
                   8248:                }
                   8249: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8250:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8251:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8252: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8253:                }
1.620     albertel 8254:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8255:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8256: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8257:                        &log($env{'user.domain'},$env{'user.name'},
                   8258:                             $env{'user.home'},
1.57      www      8259:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8260:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8261:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8262: 		       return '';
                   8263:                    }
                   8264:                }
1.620     albertel 8265:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8266:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   8267: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   8268:                        &log($env{'user.domain'},$env{'user.name'},
                   8269:                             $env{'user.home'},
1.57      www      8270:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8271:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8272:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8273: 		       return '';
                   8274:                    }
                   8275:                }
                   8276: 	   }
1.29      www      8277:        }
1.52      www      8278:     }
1.1172.2.126  raeburn  8279: 
1.52      www      8280: #
                   8281: # Rest of the restrictions depend on selected course
                   8282: #
                   8283: 
1.620     albertel 8284:     unless ($env{'request.course.id'}) {
1.766     albertel 8285: 	if ($thisallowed eq 'A') {
                   8286: 	    return 'A';
1.814     raeburn  8287:         } elsif ($thisallowed eq 'B') {
                   8288:             return 'B';
1.766     albertel 8289: 	} else {
                   8290: 	    return '1';
                   8291: 	}
1.52      www      8292:     }
1.29      www      8293: 
1.52      www      8294: #
                   8295: # Now user is definitely in a course
                   8296: #
1.53      www      8297: 
                   8298: 
                   8299: # Course preferences
                   8300: 
                   8301:    if ($thisallowed=~/C/) {
1.620     albertel 8302:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8303:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8304:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8305: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8306: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8307: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8308: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8309: 			$env{'request.course.id'});
                   8310: 	   }
1.237     www      8311:            return '';
                   8312:        }
                   8313: 
1.620     albertel 8314:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8315: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8316: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8317: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8318: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8319: 			$env{'request.course.id'});
                   8320: 	   }
1.54      www      8321:            return '';
                   8322:        }
1.53      www      8323:    }
                   8324: 
                   8325: # Resource preferences
                   8326: 
                   8327:    if ($thisallowed=~/R/) {
1.620     albertel 8328:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8329:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8330: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8331: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8332: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8333: 	   }
                   8334: 	   return '';
1.54      www      8335:        }
1.53      www      8336:    }
1.30      www      8337: 
1.246     www      8338: # Restricted by state or randomout?
1.30      www      8339: 
1.52      www      8340:    if ($thisallowed=~/X/) {
1.620     albertel 8341:       if ($env{'acc.randomout'}) {
1.579     albertel 8342: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8343:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8344:             return ''; 
                   8345:          }
1.247     www      8346:       }
                   8347:       if (&condval($statecond)) {
1.52      www      8348: 	 return '2';
                   8349:       } else {
                   8350:          return '';
                   8351:       }
                   8352:    }
1.30      www      8353: 
1.766     albertel 8354:     if ($thisallowed eq 'A') {
                   8355: 	return 'A';
1.814     raeburn  8356:     } elsif ($thisallowed eq 'B') {
                   8357:         return 'B';
1.766     albertel 8358:     }
1.52      www      8359:    return 'F';
1.232     www      8360: }
1.1162    raeburn  8361: 
1.1172.2.13  raeburn  8362: # ------------------------------------------- Check construction space access
                   8363: 
                   8364: sub constructaccess {
                   8365:     my ($url,$setpriv)=@_;
                   8366: 
                   8367: # We do not allow editing of previous versions of files
                   8368:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8369: 
                   8370: # Get username and domain from URL
                   8371:     my ($ownername,$ownerdomain,$ownerhome);
                   8372: 
                   8373:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8374:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8375: 
                   8376: # The URL does not really point to any authorspace, forget it
                   8377:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8378: 
                   8379: # Now we need to see if the user has access to the authorspace of
                   8380: # $ownername at $ownerdomain
                   8381: 
                   8382:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8383: # Real author for this?
                   8384:        $ownerhome = $env{'user.home'};
                   8385:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8386:           return ($ownername,$ownerdomain,$ownerhome);
                   8387:        }
                   8388:     } else {
                   8389: # Co-author for this?
                   8390:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8391:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8392:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8393:             return ($ownername,$ownerdomain,$ownerhome);
                   8394:         }
                   8395:     }
                   8396: 
                   8397: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8398: # we might as well leave
                   8399:    unless ($setpriv) { return ''; }
                   8400: 
                   8401: # Backdoor access?
                   8402:     my $allowed=&allowed('eco',$ownerdomain);
                   8403: # Nope
                   8404:     unless ($allowed) { return ''; }
                   8405: # Looks like we may have access, but could be locked by the owner of the construction space
                   8406:     if ($allowed eq 'U') {
                   8407:         my %blocked=&get('environment',['domcoord.author'],
                   8408:                          $ownerdomain,$ownername);
                   8409: # Is blocked by owner
                   8410:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8411:     }
                   8412:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8413: # Grant temporary access
                   8414:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8415:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8416:         if (!$update) { $update = $then; }
                   8417:         my $refresh=$env{'user.refresh.time'};
                   8418:         if (!$refresh) { $refresh = $update; }
                   8419:         my $now = time;
                   8420:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8421:                            $now,'ca','constructaccess');
                   8422:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8423:         return($ownername,$ownerdomain,$ownerhome);
                   8424:     }
                   8425: # No business here
                   8426:     return '';
                   8427: }
                   8428: 
1.1172.2.66  raeburn  8429: # ----------------------------------------------------------- Content Blocking
                   8430: 
                   8431: {
                   8432: # Caches for faster Course Contents display where content blocking
                   8433: # is in operation (i.e., interval param set) for timed quiz.
                   8434: #
                   8435: # User for whom data are being temporarily cached.
                   8436: my $cacheduser='';
1.1172.2.126  raeburn  8437: # Course for which data are being temporarily cached.
                   8438: my $cachedcid='';
1.1172.2.66  raeburn  8439: # Cached blockers for this user (a hash of blocking items).
                   8440: my %cachedblockers=();
                   8441: # When the data were last cached.
                   8442: my $cachedlast='';
                   8443: 
                   8444: sub load_all_blockers {
1.1172.2.128  raeburn  8445:     my ($uname,$udom)=@_;
1.1172.2.66  raeburn  8446:     if (($uname ne '') && ($udom ne '')) {
                   8447:         if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126  raeburn  8448:             ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128  raeburn  8449:             (abs($cachedlast-time)<5)) {
1.1172.2.66  raeburn  8450:             return;
                   8451:         }
                   8452:     }
                   8453:     $cachedlast=time;
                   8454:     $cacheduser=$uname.':'.$udom;
1.1172.2.126  raeburn  8455:     $cachedcid=$env{'request.course.id'};
1.1172.2.128  raeburn  8456:     %cachedblockers = &get_commblock_resources();
1.1172.2.126  raeburn  8457:     return;
1.1172.2.66  raeburn  8458: }
                   8459: 
1.1162    raeburn  8460: sub get_comm_blocks {
                   8461:     my ($cdom,$cnum) = @_;
                   8462:     if ($cdom eq '' || $cnum eq '') {
                   8463:         return unless ($env{'request.course.id'});
                   8464:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8465:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8466:     }
                   8467:     my %commblocks;
                   8468:     my $hashid=$cdom.'_'.$cnum;
                   8469:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8470:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8471:         %commblocks = %{$blocksref};
                   8472:     } else {
                   8473:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8474:         my $cachetime = 600;
                   8475:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8476:     }
                   8477:     return %commblocks;
                   8478: }
                   8479: 
1.1172.2.66  raeburn  8480: sub get_commblock_resources {
                   8481:     my ($blocks) = @_;
                   8482:     my %blockers = ();
                   8483:     return %blockers unless ($env{'request.course.id'});
1.1172.2.140.  .2(raebu 8484:21):     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8485:21):     if ($env{'request.course.sec'}) {
                   8486:21):         $courseurl .= '/'.$env{'request.course.sec'};
                   8487:21):     }
                   8488:21):     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162    raeburn  8489:     my %commblocks;
                   8490:     if (ref($blocks) eq 'HASH') {
                   8491:         %commblocks = %{$blocks};
                   8492:     } else {
                   8493:         %commblocks = &get_comm_blocks();
                   8494:     }
1.1172.2.66  raeburn  8495:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8496:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8497:     return %blockers unless (ref($navmap));
                   8498:     my $now = time;
1.1162    raeburn  8499:     foreach my $block (keys(%commblocks)) {
                   8500:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8501:             my ($start,$end) = ($1,$2);
                   8502:             if ($start <= $now && $end >= $now) {
                   8503:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8504:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8505:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8506:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8507:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8508:                             }
                   8509:                         }
                   8510:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8511:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8512:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8513:                             }
                   8514:                         }
                   8515:                     }
                   8516:                 }
                   8517:             }
                   8518:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8519:             my $item = $1;
1.1163    raeburn  8520:             my @to_test;
1.1162    raeburn  8521:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8522:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  8523:                     my @interval;
                   8524:                     my $type = 'map';
                   8525:                     if ($item eq 'course') {
                   8526:                         $type = 'course';
                   8527:                         @interval=&EXT("resource.0.interval");
                   8528:                     } else {
                   8529:                         if ($item =~ /___\d+___/) {
                   8530:                             $type = 'resource';
                   8531:                             @interval=&EXT("resource.0.interval",$item);
                   8532:                             if (ref($navmap)) {
                   8533:                                 my $res = $navmap->getBySymb($item);
                   8534:                                 push(@to_test,$res);
                   8535:                             }
1.1162    raeburn  8536:                         } else {
1.1172.2.66  raeburn  8537:                             my $mapsymb = &symbread($item,1);
                   8538:                             if ($mapsymb) {
                   8539:                                 if (ref($navmap)) {
                   8540:                                     my $mapres = $navmap->getBySymb($mapsymb);
1.1172.2.129  raeburn  8541:                                     if (ref($mapres)) {
                   8542:                                         my $first = $mapres->map_start();
                   8543:                                         my $finish = $mapres->map_finish();
                   8544:                                         my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   8545:                                         if (ref($it)) {
                   8546:                                             my $res;
                   8547:                                             while ($res = $it->next(undef,1)) {
                   8548:                                                 next unless (ref($res));
                   8549:                                                 my $symb = $res->symb();
                   8550:                                                 next if (($symb eq $mapsymb) || ($symb eq ''));
                   8551:                                                 @interval=&EXT("resource.0.interval",$symb);
                   8552:                                                 if ($interval[1] eq 'map') {
                   8553:                                                     if ($res->answerable()) {
                   8554:                                                         push(@to_test,$res);
                   8555:                                                         last;
                   8556:                                                     }
                   8557:                                                 }
1.1162    raeburn  8558:                                             }
                   8559:                                         }
                   8560:                                     }
                   8561:                                 }
                   8562:                             }
                   8563:                         }
1.1172.2.66  raeburn  8564:                     }
1.1172.2.140.  .1(raebu 8565:21):                     if ($interval[0] =~ /^(\d+)/) {
                   8566:21):                         my $timelimit = $1;
1.1172.2.66  raeburn  8567:                         my $first_access;
                   8568:                         if ($type eq 'resource') {
                   8569:                             $first_access=&get_first_access($interval[1],$item);
                   8570:                         } elsif ($type eq 'map') {
                   8571:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8572:                         } else {
                   8573:                             $first_access=&get_first_access($interval[1]);
                   8574:                         }
                   8575:                         if ($first_access) {
1.1172.2.140.  .1(raebu 8576:21):                             my $timesup = $first_access+$timelimit;
1.1172.2.66  raeburn  8577:                             if ($timesup > $now) {
                   8578:                                 my $activeblock;
                   8579:                                 foreach my $res (@to_test) {
                   8580:                                     if ($res->answerable()) {
                   8581:                                         $activeblock = 1;
                   8582:                                         last;
                   8583:                                     }
                   8584:                                 }
                   8585:                                 if ($activeblock) {
                   8586:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8587:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8588:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8589:                                          }
                   8590:                                     }
                   8591:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8592:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8593:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8594:                                         }
1.1162    raeburn  8595:                                     }
                   8596:                                 }
                   8597:                             }
                   8598:                         }
                   8599:                     }
                   8600:                 }
                   8601:             }
                   8602:         }
                   8603:     }
1.1172.2.66  raeburn  8604:     return %blockers;
1.1162    raeburn  8605: }
                   8606: 
1.1172.2.66  raeburn  8607: sub has_comm_blocking {
1.1172.2.128  raeburn  8608:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66  raeburn  8609:     my @blockers;
                   8610:     return unless ($env{'request.course.id'});
                   8611:     return unless ($priv eq 'bre');
                   8612:     return if ($env{'request.state'} eq 'construct');
1.1172.2.140.  .2(raebu 8613:21):     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8614:21):     if ($env{'request.course.sec'}) {
                   8615:21):         $courseurl .= '/'.$env{'request.course.sec'};
                   8616:21):     }
                   8617:21):     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1172.2.128  raeburn  8618:     my %blockinfo;
                   8619:     if (ref($blocks) eq 'HASH') {
                   8620:         %blockinfo = &get_commblock_resources($blocks);
                   8621:     } else {
                   8622:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   8623:         %blockinfo = %cachedblockers;
                   8624:     }
                   8625:     return unless (keys(%blockinfo) > 0);
1.1172.2.66  raeburn  8626:     my (%possibles,@symbs);
                   8627:     if (!$symb) {
1.1172.2.128  raeburn  8628:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  8629:     }
1.1172.2.66  raeburn  8630:     if ($symb) {
                   8631:         @symbs = ($symb);
                   8632:     } elsif (keys(%possibles)) {
                   8633:         @symbs = keys(%possibles);
                   8634:     }
                   8635:     my $noblock;
                   8636:     foreach my $symb (@symbs) {
                   8637:         last if ($noblock);
                   8638:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128  raeburn  8639:         foreach my $block (keys(%blockinfo)) {
1.1172.2.66  raeburn  8640:             if ($block =~ /^firstaccess____(.+)$/) {
                   8641:                 my $item = $1;
1.1172.2.126  raeburn  8642:                 unless ($blocked) {
                   8643:                     if (($item eq $map) || ($item eq $symb)) {
                   8644:                         $noblock = 1;
                   8645:                         last;
                   8646:                     }
1.1172.2.66  raeburn  8647:                 }
1.1162    raeburn  8648:             }
1.1172.2.128  raeburn  8649:             if (ref($blockinfo{$block}) eq 'HASH') {
                   8650:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   8651:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66  raeburn  8652:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8653:                             push(@blockers,$block);
                   8654:                         }
                   8655:                     }
                   8656:                 }
1.1172.2.128  raeburn  8657:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   8658:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126  raeburn  8659:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8660:                             push(@blockers,$block);
                   8661:                         }
1.1172.2.66  raeburn  8662:                     }
                   8663:                 }
1.1162    raeburn  8664:             }
                   8665:         }
                   8666:     }
1.1172.2.126  raeburn  8667:     unless ($noblock) {
                   8668:         return @blockers;
                   8669:     }
                   8670:     return;
1.1172.2.66  raeburn  8671: }
1.1162    raeburn  8672: }
                   8673: 
1.1172.2.66  raeburn  8674: # -------------------------------- Deversion and split uri into path an filename
                   8675: 
1.1133    foxr     8676: #
1.1172.2.66  raeburn  8677: #   Removes the version from a URI and
1.1133    foxr     8678: #   splits it in to its filename and path to the filename.
                   8679: #   Seems like File::Basename could have done this more clearly.
                   8680: #   Parameters:
                   8681: #      $uri   - input URI
                   8682: #   Returns:
                   8683: #     Two element list consisting of 
                   8684: #     $pathname  - the URI up to and excluding the trailing /
                   8685: #     $filename  - The part of the URI following the last /
                   8686: #  NOTE:
                   8687: #    Another realization of this is simply:
                   8688: #    use File::Basename;
                   8689: #    ...
                   8690: #    $uri = shift;
                   8691: #    $filename = basename($uri);
                   8692: #    $path     = dirname($uri);
                   8693: #    return ($filename, $path);
                   8694: #
                   8695: #     The implementation below is probably faster however.
                   8696: #
1.710     albertel 8697: sub split_uri_for_cond {
                   8698:     my $uri=&deversion(&declutter(shift));
                   8699:     my @uriparts=split(/\//,$uri);
                   8700:     my $filename=pop(@uriparts);
                   8701:     my $pathname=join('/',@uriparts);
                   8702:     return ($pathname,$filename);
                   8703: }
1.232     www      8704: # --------------------------------------------------- Is a resource on the map?
                   8705: 
                   8706: sub is_on_map {
1.710     albertel 8707:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8708:     #Trying to find the conditional for the file
1.620     albertel 8709:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8710: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8711:     if ($match) {
1.289     bowersj2 8712: 	return (1,$1);
                   8713:     } else {
1.434     www      8714: 	return (0,0);
1.289     bowersj2 8715:     }
1.12      www      8716: }
                   8717: 
1.427     www      8718: # --------------------------------------------------------- Get symb from alias
                   8719: 
                   8720: sub get_symb_from_alias {
                   8721:     my $symb=shift;
                   8722:     my ($map,$resid,$url)=&decode_symb($symb);
                   8723: # Already is a symb
                   8724:     if ($url) { return $symb; }
                   8725: # Must be an alias
                   8726:     my $aliassymb='';
                   8727:     my %bighash;
1.620     albertel 8728:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8729:                             &GDBM_READER(),0640)) {
                   8730:         my $rid=$bighash{'mapalias_'.$symb};
                   8731: 	if ($rid) {
                   8732: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8733: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8734: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8735: 	}
                   8736:         untie %bighash;
                   8737:     }
                   8738:     return $aliassymb;
                   8739: }
                   8740: 
1.12      www      8741: # ----------------------------------------------------------------- Define Role
                   8742: 
                   8743: sub definerole {
                   8744:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8745:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8746:     foreach my $role (split(':',$sysrole)) {
                   8747: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8748:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8749:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8750: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8751:                return "refused:s:$crole&$cqual"; 
                   8752:             }
                   8753:         }
1.191     harris41 8754:     }
1.800     albertel 8755:     foreach my $role (split(':',$domrole)) {
                   8756: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8757:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8758:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8759: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8760:                return "refused:d:$crole&$cqual"; 
                   8761:             }
                   8762:         }
1.191     harris41 8763:     }
1.800     albertel 8764:     foreach my $role (split(':',$courole)) {
                   8765: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8766:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8767:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8768: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8769:                return "refused:c:$crole&$cqual"; 
                   8770:             }
                   8771:         }
1.191     harris41 8772:     }
1.1172.2.84  raeburn  8773:     my $uhome;
                   8774:     if (($uname ne '') && ($udom ne '')) {
                   8775:         $uhome = &homeserver($uname,$udom);
                   8776:         return $uhome if ($uhome eq 'no_host');
                   8777:     } else {
                   8778:         $uname = $env{'user.name'};
                   8779:         $udom = $env{'user.domain'};
                   8780:         $uhome = $env{'user.home'};
                   8781:     }
1.620     albertel 8782:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8783:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8784:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8785:     return reply($command,$uhome);
1.12      www      8786:   } else {
                   8787:     return 'refused';
                   8788:   }
1.105     harris41 8789: }
                   8790: 
                   8791: # ---------------- Make a metadata query against the network of library servers
                   8792: 
                   8793: sub metadata_query {
1.1172.2.33  raeburn  8794:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8795:     my %rhash;
1.845     albertel 8796:     my %libserv = &all_library();
1.244     matthew  8797:     my @server_list = (defined($server_array) ? @$server_array
                   8798:                                               : keys(%libserv) );
                   8799:     for my $server (@server_list) {
1.1172.2.33  raeburn  8800:         my $domains = '';
                   8801:         if (ref($domains_hash) eq 'HASH') {
                   8802:             $domains = $domains_hash->{$server};    
                   8803:         }
1.118     harris41 8804: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8805: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8806: 	    $rhash{$server}=$reply;
                   8807: 	}
                   8808: 	else {
                   8809: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8810: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8811: 			     $server);
                   8812: 	    $rhash{$server}=$reply;
                   8813: 	}
1.112     harris41 8814:     }
1.118     harris41 8815:     return \%rhash;
1.240     www      8816: }
                   8817: 
                   8818: # ----------------------------------------- Send log queries and wait for reply
                   8819: 
                   8820: sub log_query {
                   8821:     my ($uname,$udom,$query,%filters)=@_;
                   8822:     my $uhome=&homeserver($uname,$udom);
                   8823:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8824:     my $uhost=&hostname($uhome);
1.800     albertel 8825:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8826:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8827:                        $uhome);
1.479     albertel 8828:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8829:     return get_query_reply($queryid);
                   8830: }
                   8831: 
1.818     raeburn  8832: # -------------------------- Update MySQL table for portfolio file
                   8833: 
                   8834: sub update_portfolio_table {
1.821     raeburn  8835:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8836:     if ($group ne '') {
                   8837:         $file_name =~s /^\Q$group\E//;
                   8838:     }
1.818     raeburn  8839:     my $homeserver = &homeserver($uname,$udom);
                   8840:     my $queryid=
1.821     raeburn  8841:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8842:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8843:     my $reply = &get_query_reply($queryid);
                   8844:     return $reply;
                   8845: }
                   8846: 
1.899     raeburn  8847: # -------------------------- Update MySQL allusers table
                   8848: 
                   8849: sub update_allusers_table {
                   8850:     my ($uname,$udom,$names) = @_;
                   8851:     my $homeserver = &homeserver($uname,$udom);
                   8852:     my $queryid=
                   8853:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8854:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8855:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8856:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8857:                'generation='.&escape($names->{'generation'}).'%%'.
                   8858:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8859:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8860:     return;
1.899     raeburn  8861: }
                   8862: 
1.508     raeburn  8863: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8864: 
                   8865: sub fetch_enrollment_query {
1.511     raeburn  8866:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8867:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8868:     my $maxtries = 1;
1.508     raeburn  8869:     if ($context eq 'automated') {
                   8870:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8871:         $sleep = 2;
                   8872:         $loopmax = 100;
1.547     raeburn  8873:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8874:     } else {
                   8875:         $homeserver = &homeserver($cnum,$dom);
                   8876:     }
1.838     albertel 8877:     my $host=&hostname($homeserver);
1.506     raeburn  8878:     my $cmd = '';
1.1000    raeburn  8879:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8880:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8881:     }
                   8882:     $cmd =~ s/%%$//;
                   8883:     $cmd = &escape($cmd);
                   8884:     my $query = 'fetchenrollment';
1.620     albertel 8885:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8886:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8887:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8888:         return 'error: '.$queryid;
                   8889:     }
1.1172.2.93  raeburn  8890:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8891:     my $tries = 1;
                   8892:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8893:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8894:         $tries ++;
                   8895:     }
1.526     raeburn  8896:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8897:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8898:     } else {
1.901     albertel 8899:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8900:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8901:             foreach my $line (@responses) {
                   8902:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8903:                 $$replyref{$key} = $value;
                   8904:             }
                   8905:         } else {
1.1117    foxr     8906:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8907:             foreach my $line (@responses) {
                   8908:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8909:                 $$replyref{$key} = $value;
                   8910:                 if ($value > 0) {
1.800     albertel 8911:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8912:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8913:                         my $destname = $pathname.'/'.$filename;
                   8914:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8915:                         if ($xml_classlist =~ /^error/) {
                   8916:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8917:                         } else {
1.1172.2.96  raeburn  8918:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8919:                                 print FILE &unescape($xml_classlist);
                   8920:                                 close(FILE);
1.526     raeburn  8921:                             } else {
                   8922:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8923:                             }
                   8924:                         }
                   8925:                     }
                   8926:                 }
                   8927:             }
                   8928:         }
                   8929:         return 'ok';
                   8930:     }
                   8931:     return 'error';
                   8932: }
                   8933: 
1.242     www      8934: sub get_query_reply {
1.1172.2.79  raeburn  8935:     my ($queryid,$sleep,$loopmax) = @_;
                   8936:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8937:         $sleep = 0.2;
                   8938:     }
                   8939:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8940:         $loopmax = 100;
                   8941:     }
1.1117    foxr     8942:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8943:     my $reply='';
1.1172.2.79  raeburn  8944:     for (1..$loopmax) {
                   8945: 	sleep($sleep);
1.240     www      8946:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  8947: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8948: 		$reply = join('',<$fh>);
                   8949: 		close($fh);
1.240     www      8950: 	   } else { return 'error: reply_file_error'; }
1.242     www      8951:            return &unescape($reply);
                   8952: 	}
1.240     www      8953:     }
1.242     www      8954:     return 'timeout:'.$queryid;
1.240     www      8955: }
                   8956: 
                   8957: sub courselog_query {
1.241     www      8958: #
                   8959: # possible filters:
                   8960: # url: url or symb
                   8961: # username
                   8962: # domain
                   8963: # action: view, submit, grade
                   8964: # start: timestamp
                   8965: # end: timestamp
                   8966: #
1.240     www      8967:     my (%filters)=@_;
1.620     albertel 8968:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8969:     if ($filters{'url'}) {
                   8970: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8971:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8972:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8973:     }
1.620     albertel 8974:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8975:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8976:     return &log_query($cname,$cdom,'courselog',%filters);
                   8977: }
                   8978: 
                   8979: sub userlog_query {
1.858     raeburn  8980: #
                   8981: # possible filters:
                   8982: # action: log check role
                   8983: # start: timestamp
                   8984: # end: timestamp
                   8985: #
1.240     www      8986:     my ($uname,$udom,%filters)=@_;
                   8987:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8988: }
                   8989: 
1.506     raeburn  8990: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8991: 
                   8992: sub auto_run {
1.508     raeburn  8993:     my ($cnum,$cdom) = @_;
1.876     raeburn  8994:     my $response = 0;
                   8995:     my $settings;
                   8996:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8997:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8998:         $settings = $domconfig{'autoenroll'};
                   8999:         if ($settings->{'run'} eq '1') {
                   9000:             $response = 1;
                   9001:         }
                   9002:     } else {
1.934     raeburn  9003:         my $homeserver;
                   9004:         if (&is_course($cdom,$cnum)) {
                   9005:             $homeserver = &homeserver($cnum,$cdom);
                   9006:         } else {
                   9007:             $homeserver = &domain($cdom,'primary');
                   9008:         }
                   9009:         if ($homeserver ne 'no_host') {
                   9010:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9011:         }
1.876     raeburn  9012:     }
1.506     raeburn  9013:     return $response;
                   9014: }
1.776     albertel 9015: 
1.506     raeburn  9016: sub auto_get_sections {
1.508     raeburn  9017:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9018:     my $homeserver;
                   9019:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9020:         $homeserver = &homeserver($cnum,$cdom);
                   9021:     }
                   9022:     if (!defined($homeserver)) { 
                   9023:         if ($cdom =~ /^$match_domain$/) {
                   9024:             $homeserver = &domain($cdom,'primary');
                   9025:         }
                   9026:     }
                   9027:     my @secs;
                   9028:     if (defined($homeserver)) {
                   9029:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9030:         unless ($response eq 'refused') {
                   9031:             @secs = split(/:/,$response);
                   9032:         }
1.506     raeburn  9033:     }
                   9034:     return @secs;
                   9035: }
1.776     albertel 9036: 
1.506     raeburn  9037: sub auto_new_course {
1.1099    raeburn  9038:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9039:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9040:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9041:     return $response;
                   9042: }
1.776     albertel 9043: 
1.506     raeburn  9044: sub auto_validate_courseID {
1.508     raeburn  9045:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9046:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9047:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9048:     return $response;
                   9049: }
1.776     albertel 9050: 
1.1007    raeburn  9051: sub auto_validate_instcode {
1.1020    raeburn  9052:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9053:     my ($homeserver,$response);
                   9054:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9055:         $homeserver = &homeserver($cnum,$cdom);
                   9056:     }
                   9057:     if (!defined($homeserver)) {
                   9058:         if ($cdom =~ /^$match_domain$/) {
                   9059:             $homeserver = &domain($cdom,'primary');
                   9060:         }
                   9061:     }
1.1065    raeburn  9062:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9063:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  9064:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9065:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9066: }
                   9067: 
1.506     raeburn  9068: sub auto_create_password {
1.873     raeburn  9069:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9070:     my ($homeserver,$response);
1.506     raeburn  9071:     my $create_passwd = 0;
                   9072:     my $authchk = '';
1.873     raeburn  9073:     if ($udom =~ /^$match_domain$/) {
                   9074:         $homeserver = &domain($udom,'primary');
                   9075:     }
                   9076:     if ($homeserver eq '') {
                   9077:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9078:             $homeserver = &homeserver($cnum,$cdom);
                   9079:         }
                   9080:     }
                   9081:     if ($homeserver eq '') {
                   9082:         $authchk = 'nodomain';
1.506     raeburn  9083:     } else {
1.873     raeburn  9084:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9085:         if ($response eq 'refused') {
                   9086:             $authchk = 'refused';
                   9087:         } else {
1.901     albertel 9088:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9089:         }
1.506     raeburn  9090:     }
                   9091:     return ($authparam,$create_passwd,$authchk);
                   9092: }
                   9093: 
1.706     raeburn  9094: sub auto_photo_permission {
                   9095:     my ($cnum,$cdom,$students) = @_;
                   9096:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9097:     my ($outcome,$perm_reqd,$conditions) = 
                   9098: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9099:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9100: 	return (undef,undef);
                   9101:     }
1.706     raeburn  9102:     return ($outcome,$perm_reqd,$conditions);
                   9103: }
                   9104: 
                   9105: sub auto_checkphotos {
                   9106:     my ($uname,$udom,$pid) = @_;
                   9107:     my $homeserver = &homeserver($uname,$udom);
                   9108:     my ($result,$resulttype);
                   9109:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9110: 				   &escape($uname).':'.&escape($pid),
                   9111: 				   $homeserver));
1.709     albertel 9112:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9113: 	return (undef,undef);
                   9114:     }
1.706     raeburn  9115:     if ($outcome) {
                   9116:         ($result,$resulttype) = split(/:/,$outcome);
                   9117:     } 
                   9118:     return ($result,$resulttype);
                   9119: }
                   9120: 
                   9121: sub auto_photochoice {
                   9122:     my ($cnum,$cdom) = @_;
                   9123:     my $homeserver = &homeserver($cnum,$cdom);
                   9124:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9125: 						       &escape($cdom),
                   9126: 						       $homeserver)));
1.709     albertel 9127:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9128: 	return (undef,undef);
                   9129:     }
1.706     raeburn  9130:     return ($update,$comment);
                   9131: }
                   9132: 
                   9133: sub auto_photoupdate {
                   9134:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9135:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9136:     my $host=&hostname($homeserver);
1.706     raeburn  9137:     my $cmd = '';
                   9138:     my $maxtries = 1;
1.800     albertel 9139:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9140:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9141:     }
                   9142:     $cmd =~ s/%%$//;
                   9143:     $cmd = &escape($cmd);
                   9144:     my $query = 'institutionalphotos';
                   9145:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9146:     unless ($queryid=~/^\Q$host\E\_/) {
                   9147:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9148:         return 'error: '.$queryid;
                   9149:     }
                   9150:     my $reply = &get_query_reply($queryid);
                   9151:     my $tries = 1;
                   9152:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9153:         $reply = &get_query_reply($queryid);
                   9154:         $tries ++;
                   9155:     }
                   9156:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9157:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9158:     } else {
                   9159:         my @responses = split(/:/,$reply);
                   9160:         my $outcome = shift(@responses); 
                   9161:         foreach my $item (@responses) {
                   9162:             my ($key,$value) = split(/=/,$item);
                   9163:             $$photo{$key} = $value;
                   9164:         }
                   9165:         return $outcome;
                   9166:     }
                   9167:     return 'error';
                   9168: }
                   9169: 
1.521     raeburn  9170: sub auto_instcode_format {
1.793     albertel 9171:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9172: 	$cat_order) = @_;
1.521     raeburn  9173:     my $courses = '';
1.772     raeburn  9174:     my @homeservers;
1.521     raeburn  9175:     if ($caller eq 'global') {
1.841     albertel 9176: 	my %servers = &get_servers($codedom,'library');
                   9177: 	foreach my $tryserver (keys(%servers)) {
                   9178: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9179: 		push(@homeservers,$tryserver);
                   9180: 	    }
1.584     raeburn  9181:         }
1.1022    raeburn  9182:     } elsif ($caller eq 'requests') {
                   9183:         if ($codedom =~ /^$match_domain$/) {
                   9184:             my $chome = &domain($codedom,'primary');
                   9185:             unless ($chome eq 'no_host') {
                   9186:                 push(@homeservers,$chome);
                   9187:             }
                   9188:         }
1.521     raeburn  9189:     } else {
1.772     raeburn  9190:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9191:     }
1.793     albertel 9192:     foreach my $code (keys(%{$instcodes})) {
                   9193:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9194:     }
                   9195:     chop($courses);
1.772     raeburn  9196:     my $ok_response = 0;
                   9197:     my $response;
                   9198:     while (@homeservers > 0 && $ok_response == 0) {
                   9199:         my $server = shift(@homeservers); 
                   9200:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9201:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9202:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9203: 		split(/:/,$response);
1.772     raeburn  9204:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9205:             push(@{$codetitles},&str2array($codetitles_str));
                   9206:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9207:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9208:             $ok_response = 1;
                   9209:         }
                   9210:     }
                   9211:     if ($ok_response) {
1.521     raeburn  9212:         return 'ok';
1.772     raeburn  9213:     } else {
                   9214:         return $response;
1.521     raeburn  9215:     }
                   9216: }
                   9217: 
1.792     raeburn  9218: sub auto_instcode_defaults {
                   9219:     my ($domain,$returnhash,$code_order) = @_;
                   9220:     my @homeservers;
1.841     albertel 9221: 
                   9222:     my %servers = &get_servers($domain,'library');
                   9223:     foreach my $tryserver (keys(%servers)) {
                   9224: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9225: 	    push(@homeservers,$tryserver);
                   9226: 	}
1.792     raeburn  9227:     }
1.841     albertel 9228: 
1.792     raeburn  9229:     my $response;
1.841     albertel 9230:     foreach my $server (@homeservers) {
1.792     raeburn  9231:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9232:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9233: 	
                   9234: 	foreach my $pair (split(/\&/,$response)) {
                   9235: 	    my ($name,$value)=split(/\=/,$pair);
                   9236: 	    if ($name eq 'code_order') {
                   9237: 		@{$code_order} = split(/\&/,&unescape($value));
                   9238: 	    } else {
                   9239: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9240: 	    }
                   9241: 	}
                   9242: 	return 'ok';
1.792     raeburn  9243:     }
1.841     albertel 9244: 
                   9245:     return $response;
1.1003    raeburn  9246: }
                   9247: 
                   9248: sub auto_possible_instcodes {
1.1007    raeburn  9249:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9250:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9251:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9252:         return;
                   9253:     }
1.1003    raeburn  9254:     my (@homeservers,$uhome);
                   9255:     if (defined(&domain($domain,'primary'))) {
                   9256:         $uhome=&domain($domain,'primary');
                   9257:         push(@homeservers,&domain($domain,'primary'));
                   9258:     } else {
                   9259:         my %servers = &get_servers($domain,'library');
                   9260:         foreach my $tryserver (keys(%servers)) {
                   9261:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9262:                 push(@homeservers,$tryserver);
                   9263:             }
                   9264:         }
                   9265:     }
                   9266:     my $response;
                   9267:     foreach my $server (@homeservers) {
                   9268:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9269:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9270:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9271:             split(':',$response);
                   9272:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9273:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9274:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9275:             my ($name,$value)=split('=',$item);
                   9276:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9277:         }
                   9278:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9279:             my ($name,$value)=split('=',$item);
                   9280:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9281:         }
                   9282:         return 'ok';
                   9283:     }
                   9284:     return $response;
                   9285: }
1.792     raeburn  9286: 
1.1010    raeburn  9287: sub auto_courserequest_checks {
                   9288:     my ($dom) = @_;
1.1020    raeburn  9289:     my ($homeserver,%validations);
                   9290:     if ($dom =~ /^$match_domain$/) {
                   9291:         $homeserver = &domain($dom,'primary');
                   9292:     }
                   9293:     unless ($homeserver eq 'no_host') {
                   9294:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9295:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9296:             my @items = split(/&/,$response);
                   9297:             foreach my $item (@items) {
                   9298:                 my ($key,$value) = split('=',$item);
                   9299:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9300:             }
                   9301:         }
                   9302:     }
1.1010    raeburn  9303:     return %validations; 
                   9304: }
                   9305: 
1.1020    raeburn  9306: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9307:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9308:     my ($homeserver,$response);
                   9309:     if ($dom =~ /^$match_domain$/) {
                   9310:         $homeserver = &domain($dom,'primary');
                   9311:     }
1.1172.2.43  raeburn  9312:     unless ($homeserver eq 'no_host') {
                   9313:         my $customdata;
                   9314:         if (ref($custominfo) eq 'HASH') {
                   9315:             $customdata = &freeze_escape($custominfo);
                   9316:         }
1.1020    raeburn  9317:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9318:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9319:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9320:                                     $customdata,$homeserver));
1.1020    raeburn  9321:     }
                   9322:     return $response;
                   9323: }
                   9324: 
1.777     albertel 9325: sub auto_validate_class_sec {
1.918     raeburn  9326:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9327:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9328:     my $ownerlist;
                   9329:     if (ref($owners) eq 'ARRAY') {
                   9330:         $ownerlist = join(',',@{$owners});
                   9331:     } else {
                   9332:         $ownerlist = $owners;
                   9333:     }
1.773     raeburn  9334:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9335:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9336:     return $response;
                   9337: }
                   9338: 
1.1172.2.94  raeburn  9339: sub auto_validate_instclasses {
                   9340:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9341:     my ($homeserver,%validations);
                   9342:     $homeserver = &homeserver($cnum,$cdom);
                   9343:     unless ($homeserver eq 'no_host') {
                   9344:         my $ownerlist;
                   9345:         if (ref($owners) eq 'ARRAY') {
                   9346:             $ownerlist = join(',',@{$owners});
                   9347:         } else {
                   9348:             $ownerlist = $owners;
                   9349:         }
                   9350:         if (ref($classesref) eq 'HASH') {
                   9351:             my $classes = &freeze_escape($classesref);
                   9352:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9353:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9354:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9355:                 my @items = split(/&/,$response);
                   9356:                 foreach my $item (@items) {
                   9357:                     my ($key,$value) = split('=',$item);
                   9358:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9359:                 }
                   9360:             }
                   9361:         }
                   9362:     }
                   9363:     return %validations;
                   9364: }
                   9365: 
1.1172.2.38  raeburn  9366: sub auto_crsreq_update {
                   9367:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9368:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9369:     my ($homeserver,%crsreqresponse);
                   9370:     if ($cdom =~ /^$match_domain$/) {
                   9371:         $homeserver = &domain($cdom,'primary');
                   9372:     }
                   9373:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9374:         my $info;
                   9375:         if (ref($inbound) eq 'HASH') {
                   9376:             $info = &freeze_escape($inbound);
                   9377:         }
                   9378:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9379:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9380:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9381:                             &escape($title).':'.&escape($code).':'.
                   9382:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9383:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9384:             my @items = split(/&/,$response);
                   9385:             foreach my $item (@items) {
                   9386:                 my ($key,$value) = split('=',$item);
                   9387:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9388:             }
                   9389:         }
                   9390:     }
                   9391:     return \%crsreqresponse;
                   9392: }
                   9393: 
1.1172.2.78  raeburn  9394: sub auto_export_grades {
                   9395:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9396:     my ($homeserver,%exportresponse);
                   9397:     if ($cdom =~ /^$match_domain$/) {
                   9398:         $homeserver = &domain($cdom,'primary');
                   9399:     }
                   9400:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9401:         my $info;
                   9402:         if (ref($inforef) eq 'HASH') {
                   9403:             $info = &freeze_escape($inforef);
                   9404:         }
                   9405:         if (ref($gradesref) eq 'HASH') {
                   9406:             my $grades = &freeze_escape($gradesref);
                   9407:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9408:                                 $info.':'.$grades,$homeserver);
                   9409:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9410:                 my @items = split(/&/,$response);
                   9411:                 foreach my $item (@items) {
                   9412:                     my ($key,$value) = split('=',$item);
                   9413:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9414:                 }
                   9415:             }
                   9416:         }
                   9417:     }
                   9418:     return \%exportresponse;
                   9419: }
                   9420: 
1.1172.2.68  raeburn  9421: sub check_instcode_cloning {
                   9422:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9423:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9424:         return;
                   9425:     }
                   9426:     my $canclone;
                   9427:     if (@{$code_order} > 0) {
                   9428:         my $instcoderegexp ='^';
                   9429:         my @clonecodes = split(/\&/,$cloner);
                   9430:         foreach my $item (@{$code_order}) {
                   9431:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9432:                 foreach my $pair (@clonecodes) {
                   9433:                     my ($key,$val) = split(/\=/,$pair,2);
                   9434:                     $val = &unescape($val);
                   9435:                     if ($key eq $item) {
                   9436:                         $instcoderegexp .= '('.$val.')';
                   9437:                         last;
                   9438:                     }
                   9439:                 }
                   9440:             } else {
                   9441:                 $instcoderegexp .= $codedefaults->{$item};
                   9442:             }
                   9443:         }
                   9444:         $instcoderegexp .= '$';
                   9445:         my (@from,@to);
                   9446:         eval {
                   9447:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9448:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9449:         };
                   9450:         if ((@from > 0) && (@to > 0)) {
                   9451:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9452:             if (!@diffs) {
                   9453:                 $canclone = 1;
                   9454:             }
                   9455:         }
                   9456:     }
                   9457:     return $canclone;
                   9458: }
                   9459: 
                   9460: sub default_instcode_cloning {
                   9461:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9462:     my (%codedefaults,@code_order,$canclone);
                   9463:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9464:         %codedefaults = %{$codedefaultsref};
                   9465:         @code_order = @{$codeorderref};
                   9466:     } elsif ($clonedom) {
                   9467:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9468:     }
                   9469:     if (($domdefclone) && (@code_order)) {
                   9470:         my @clonecodes = split(/\+/,$domdefclone);
                   9471:         my $instcoderegexp ='^';
                   9472:         foreach my $item (@code_order) {
                   9473:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9474:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9475:             } else {
                   9476:                 $instcoderegexp .= $codedefaults{$item};
                   9477:             }
                   9478:         }
                   9479:         $instcoderegexp .= '$';
                   9480:         my (@from,@to);
                   9481:         eval {
                   9482:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9483:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9484:         };
                   9485:         if ((@from > 0) && (@to > 0)) {
                   9486:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9487:             if (!@diffs) {
                   9488:                 $canclone = 1;
                   9489:             }
                   9490:         }
                   9491:     }
                   9492:     return $canclone;
                   9493: }
                   9494: 
1.679     raeburn  9495: # ------------------------------------------------------- Course Group routines
                   9496: 
                   9497: sub get_coursegroups {
1.809     raeburn  9498:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9499:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9500: }
                   9501: 
1.679     raeburn  9502: sub modify_coursegroup {
                   9503:     my ($cdom,$cnum,$groupsettings) = @_;
                   9504:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9505: }
                   9506: 
1.809     raeburn  9507: sub toggle_coursegroup_status {
                   9508:     my ($cdom,$cnum,$group,$action) = @_;
                   9509:     my ($from_namespace,$to_namespace);
                   9510:     if ($action eq 'delete') {
                   9511:         $from_namespace = 'coursegroups';
                   9512:         $to_namespace = 'deleted_groups';
                   9513:     } else {
                   9514:         $from_namespace = 'deleted_groups';
                   9515:         $to_namespace = 'coursegroups';
                   9516:     }
                   9517:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9518:     if (my $tmp = &error(%curr_group)) {
                   9519:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9520:         return ('read error',$tmp);
                   9521:     } else {
                   9522:         my %savedsettings = %curr_group; 
1.809     raeburn  9523:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9524:         my $deloutcome;
                   9525:         if ($result eq 'ok') {
1.809     raeburn  9526:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9527:         } else {
                   9528:             return ('write error',$result);
                   9529:         }
                   9530:         if ($deloutcome eq 'ok') {
                   9531:             return 'ok';
                   9532:         } else {
                   9533:             return ('delete error',$deloutcome);
                   9534:         }
                   9535:     }
                   9536: }
                   9537: 
1.679     raeburn  9538: sub modify_group_roles {
1.957     raeburn  9539:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9540:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9541:     my $role = 'gr/'.&escape($userprivs);
                   9542:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9543:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9544:     if ($result eq 'ok') {
                   9545:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9546:     }
1.679     raeburn  9547:     return $result;
                   9548: }
                   9549: 
                   9550: sub modify_coursegroup_membership {
                   9551:     my ($cdom,$cnum,$membership) = @_;
                   9552:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9553:     return $result;
                   9554: }
                   9555: 
1.682     raeburn  9556: sub get_active_groups {
                   9557:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9558:     my $now = time;
                   9559:     my %groups = ();
                   9560:     foreach my $key (keys(%env)) {
1.811     albertel 9561:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9562:             my ($start,$end) = split(/\./,$env{$key});
                   9563:             if (($end!=0) && ($end<$now)) { next; }
                   9564:             if (($start!=0) && ($start>$now)) { next; }
                   9565:             if ($1 eq $cdom && $2 eq $cnum) {
                   9566:                 $groups{$3} = $env{$key} ;
                   9567:             }
                   9568:         }
                   9569:     }
                   9570:     return %groups;
                   9571: }
                   9572: 
1.683     raeburn  9573: sub get_group_membership {
                   9574:     my ($cdom,$cnum,$group) = @_;
                   9575:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9576: }
                   9577: 
                   9578: sub get_users_groups {
                   9579:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9580:     my @usersgroups;
1.683     raeburn  9581:     my $cachetime=1800;
                   9582: 
                   9583:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9584:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9585:     if (defined($cached)) {
1.734     albertel 9586:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9587:     } else {  
                   9588:         $grouplist = '';
1.816     raeburn  9589:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9590:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9591:         my $access_end = $env{'course.'.$courseid.
                   9592:                               '.default_enrollment_end_date'};
                   9593:         my $now = time;
                   9594:         foreach my $key (keys(%roleshash)) {
                   9595:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9596:                 my $group = $1;
                   9597:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9598:                     my $start = $2;
                   9599:                     my $end = $1;
                   9600:                     if ($start == -1) { next; } # deleted from group
                   9601:                     if (($start!=0) && ($start>$now)) { next; }
                   9602:                     if (($end!=0) && ($end<$now)) {
                   9603:                         if ($access_end && $access_end < $now) {
                   9604:                             if ($access_end - $end < 86400) {
                   9605:                                 push(@usersgroups,$group);
1.733     raeburn  9606:                             }
                   9607:                         }
1.817     raeburn  9608:                         next;
1.733     raeburn  9609:                     }
1.817     raeburn  9610:                     push(@usersgroups,$group);
1.683     raeburn  9611:                 }
                   9612:             }
                   9613:         }
1.817     raeburn  9614:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9615:         $grouplist = join(':',@usersgroups);
                   9616:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9617:     }
1.733     raeburn  9618:     return @usersgroups;
1.683     raeburn  9619: }
                   9620: 
                   9621: sub devalidate_getgroups_cache {
                   9622:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9623:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9624: 
1.683     raeburn  9625:     my $hashid="$udom:$uname:$courseid";
                   9626:     &devalidate_cache_new('getgroups',$hashid);
                   9627: }
                   9628: 
1.12      www      9629: # ------------------------------------------------------------------ Plain Text
                   9630: 
                   9631: sub plaintext {
1.988     raeburn  9632:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9633:     if ($short =~ m{^cr/}) {
1.758     albertel 9634: 	return (split('/',$short))[-1];
                   9635:     }
1.742     raeburn  9636:     if (!defined($cid)) {
                   9637:         $cid = $env{'request.course.id'};
                   9638:     }
                   9639:     my %rolenames = (
1.1008    raeburn  9640:                       Course    => 'std',
                   9641:                       Community => 'alt1',
1.742     raeburn  9642:                     );
1.1037    raeburn  9643:     if ($cid ne '') {
                   9644:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9645:             unless ($forcedefault) {
                   9646:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9647:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9648:                 return &Apache::lonlocal::mt($roletext);
                   9649:             }
                   9650:         }
                   9651:     }
                   9652:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9653:         (defined($rolenames{$type})) && 
                   9654:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9655:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9656:     } elsif ($cid ne '') {
                   9657:         my $crstype = $env{'course.'.$cid.'.type'};
                   9658:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9659:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9660:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9661:         }
1.742     raeburn  9662:     }
1.1037    raeburn  9663:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9664: }
                   9665: 
                   9666: # ----------------------------------------------------------------- Assign Role
                   9667: 
                   9668: sub assignrole {
1.957     raeburn  9669:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9670:         $context)=@_;
1.21      www      9671:     my $mrole;
                   9672:     if ($role =~ /^cr\//) {
1.393     www      9673:         my $cwosec=$url;
1.811     albertel 9674:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9675: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9676:            my $refused = 1;
                   9677:            if ($context eq 'requestcourses') {
                   9678:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9679:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9680:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9681:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9682:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9683:                            if ($crsenv{'internal.courseowner'} eq
                   9684:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9685:                                $refused = '';
                   9686:                            }
                   9687:                        }
                   9688:                    }
                   9689:                }
                   9690:            }
                   9691:            if ($refused) {
                   9692:                &logthis('Refused custom assignrole: '.
                   9693:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9694:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9695:                return 'refused';
                   9696:            }
1.104     www      9697:         }
1.21      www      9698:         $mrole='cr';
1.678     raeburn  9699:     } elsif ($role =~ /^gr\//) {
                   9700:         my $cwogrp=$url;
1.811     albertel 9701:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9702:         unless (&allowed('mdg',$cwogrp)) {
                   9703:             &logthis('Refused group assignrole: '.
                   9704:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9705:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9706:             return 'refused';
                   9707:         }
                   9708:         $mrole='gr';
1.21      www      9709:     } else {
1.82      www      9710:         my $cwosec=$url;
1.811     albertel 9711:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9712:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9713:             my $refused;
                   9714:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9715:                 if (!(&allowed('c'.$role,$url))) {
                   9716:                     $refused = 1;
                   9717:                 }
                   9718:             } else {
                   9719:                 $refused = 1;
                   9720:             }
1.947     raeburn  9721:             if ($refused) {
1.1045    raeburn  9722:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9723:                 if (!$selfenroll && $context eq 'course') {
                   9724:                     my %crsenv;
                   9725:                     if ($role eq 'cc' || $role eq 'co') {
                   9726:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9727:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9728:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9729:                                 if ($crsenv{'internal.courseowner'} eq 
                   9730:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9731:                                     $refused = '';
                   9732:                                 }
                   9733:                             }
                   9734:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9735:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9736:                                 if ($crsenv{'internal.courseowner'} eq 
                   9737:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9738:                                     $refused = '';
                   9739:                                 }
                   9740:                             }
                   9741:                         }
                   9742:                     }
                   9743:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9744:                     $refused = '';
1.1017    raeburn  9745:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9746:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9747:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9748:                         my $wrongcc;
                   9749:                         if ($cnum =~ /^$match_community$/) {
                   9750:                             $wrongcc = 1 if ($role eq 'cc');
                   9751:                         } else {
                   9752:                             $wrongcc = 1 if ($role eq 'co');
                   9753:                         }
                   9754:                         unless ($wrongcc) {
                   9755:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9756:                             if ($crsenv{'internal.courseowner'} eq 
                   9757:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9758:                                 $refused = '';
                   9759:                             }
1.1017    raeburn  9760:                         }
                   9761:                     }
1.1172.2.9  raeburn  9762:                 } elsif ($context eq 'requestauthor') {
                   9763:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9764:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9765:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9766:                             $refused = '';
                   9767:                         } else {
                   9768:                             my %domdefaults = &get_domain_defaults($udom);
                   9769:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9770:                                 my $checkbystatus;
                   9771:                                 if ($env{'user.adv'}) {
                   9772:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9773:                                     if ($disposition eq 'automatic') {
                   9774:                                         $refused = '';
                   9775:                                     } elsif ($disposition eq '') {
                   9776:                                         $checkbystatus = 1;
                   9777:                                     }
                   9778:                                 } else {
                   9779:                                     $checkbystatus = 1;
                   9780:                                 }
                   9781:                                 if ($checkbystatus) {
                   9782:                                     if ($env{'environment.inststatus'}) {
                   9783:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9784:                                         foreach my $type (@inststatuses) {
                   9785:                                             if (($type ne '') &&
                   9786:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9787:                                                 $refused = '';
                   9788:                                             }
                   9789:                                         }
                   9790:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9791:                                         $refused = '';
                   9792:                                     }
                   9793:                                 }
                   9794:                             }
                   9795:                         }
                   9796:                     }
1.1017    raeburn  9797:                 }
                   9798:                 if ($refused) {
1.947     raeburn  9799:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9800:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9801: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9802:                     return 'refused';
                   9803:                 }
1.932     raeburn  9804:             }
1.1131    raeburn  9805:         } elsif ($role eq 'au') {
                   9806:             if ($url ne '/'.$udom.'/') {
                   9807:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9808:                          ' to assign author role for '.$uname.':'.$udom.
                   9809:                          ' in domain: '.$url.' refused (wrong domain).');
                   9810:                 return 'refused';
                   9811:             }
1.104     www      9812:         }
1.21      www      9813:         $mrole=$role;
                   9814:     }
1.620     albertel 9815:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9816:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9817:     if ($end) { $command.='_'.$end; }
1.21      www      9818:     if ($start) {
                   9819: 	if ($end) { 
1.81      www      9820:            $command.='_'.$start; 
1.21      www      9821:         } else {
1.81      www      9822:            $command.='_0_'.$start;
1.21      www      9823:         }
                   9824:     }
1.739     raeburn  9825:     my $origstart = $start;
                   9826:     my $origend = $end;
1.957     raeburn  9827:     my $delflag;
1.357     www      9828: # actually delete
                   9829:     if ($deleteflag) {
1.373     www      9830: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9831: # modify command to delete the role
1.620     albertel 9832:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9833:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9834: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9835: # set start and finish to negative values for userrolelog
                   9836:            $start=-1;
                   9837:            $end=-1;
1.957     raeburn  9838:            $delflag = 1;
1.357     www      9839:         }
                   9840:     }
                   9841: # send command
1.349     www      9842:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9843: # log new user role if status is ok
1.349     www      9844:     if ($answer eq 'ok') {
1.663     raeburn  9845: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9846:         if (($role eq 'cc') || ($role eq 'in') ||
                   9847:             ($role eq 'ep') || ($role eq 'ad') ||
                   9848:             ($role eq 'ta') || ($role eq 'st') ||
                   9849:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9850:             ($role eq 'co')) {
1.1172.2.13  raeburn  9851: # for course roles, perform group memberships changes triggered by role change.
                   9852:             unless ($role =~ /^gr/) {
                   9853:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9854:                                                  $origstart,$selfenroll,$context);
                   9855:             }
1.1172.2.9  raeburn  9856:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9857:                            $selfenroll,$context);
                   9858:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9859:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9860:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9861:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9862:                            $context);
                   9863:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9864:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9865:                              $context);
                   9866:         }
1.1053    raeburn  9867:         if ($role eq 'cc') {
                   9868:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9869:         }
1.349     www      9870:     }
                   9871:     return $answer;
1.169     harris41 9872: }
                   9873: 
1.1053    raeburn  9874: sub autoupdate_coowners {
                   9875:     my ($url,$end,$start,$uname,$udom) = @_;
                   9876:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9877:     if (($cdom ne '') && ($cnum ne '')) {
                   9878:         my $now = time;
                   9879:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9880:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9881:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9882:             my $instcode = $coursehash{'internal.coursecode'};
                   9883:             if ($instcode ne '') {
1.1056    raeburn  9884:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9885:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9886:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9887:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9888:                         if ($result eq 'valid') {
                   9889:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9890:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9891:                                     push(@newcoowners,$coowner);
                   9892:                                 }
                   9893:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9894:                                     push(@newcoowners,$uname.':'.$udom);
                   9895:                                 }
                   9896:                                 @newcoowners = sort(@newcoowners);
                   9897:                             } else {
                   9898:                                 push(@newcoowners,$uname.':'.$udom);
                   9899:                             }
                   9900:                         } else {
                   9901:                             if ($coursehash{'internal.co-owners'}) {
                   9902:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9903:                                     unless ($coowner eq $uname.':'.$udom) {
                   9904:                                         push(@newcoowners,$coowner);
                   9905:                                     }
                   9906:                                 }
                   9907:                                 unless (@newcoowners > 0) {
                   9908:                                     $delcoowners = 1;
                   9909:                                     $coowners = '';
                   9910:                                 }
                   9911:                             }
                   9912:                         }
                   9913:                         if (@newcoowners || $delcoowners) {
                   9914:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9915:                                             $delcoowners,@newcoowners);
                   9916:                         }
                   9917:                     }
                   9918:                 }
                   9919:             }
                   9920:         }
                   9921:     }
                   9922: }
                   9923: 
                   9924: sub store_coowners {
                   9925:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9926:     my $cid = $cdom.'_'.$cnum;
                   9927:     my ($coowners,$delresult,$putresult);
                   9928:     if (@newcoowners) {
                   9929:         $coowners = join(',',@newcoowners);
                   9930:         my %coownershash = (
                   9931:                             'internal.co-owners' => $coowners,
                   9932:                            );
                   9933:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9934:         if ($putresult eq 'ok') {
                   9935:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9936:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9937:             }
                   9938:         }
                   9939:     }
                   9940:     if ($delcoowners) {
                   9941:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9942:         if ($delresult eq 'ok') {
                   9943:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9944:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9945:             }
                   9946:         }
                   9947:     }
                   9948:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9949:         my %crsinfo =
                   9950:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9951:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9952:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9953:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9954:         }
                   9955:     }
                   9956: }
                   9957: 
1.169     harris41 9958: # -------------------------------------------------- Modify user authentication
1.197     www      9959: # Overrides without validation
                   9960: 
1.169     harris41 9961: sub modifyuserauth {
                   9962:     my ($udom,$uname,$umode,$upass)=@_;
                   9963:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  9964:     my $allowed;
                   9965:     if (&allowed('mau',$udom)) {
                   9966:         $allowed = 1;
                   9967:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   9968:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   9969:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   9970:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9971:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9972:         if (($cdom ne '') && ($cnum ne '')) {
                   9973:             my $is_owner = &is_course_owner($cdom,$cnum);
                   9974:             if ($is_owner) {
                   9975:                 $allowed = 1;
                   9976:             }
                   9977:         }
                   9978:     }
                   9979:     unless ($allowed) { return 'refused'; }
1.197     www      9980:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9981:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9982:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9983:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9984: 		     &escape($upass),$uhome);
1.1172.2.134  raeburn  9985:     my $ip = &get_requestor_ip();
1.620     albertel 9986:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9987:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.134  raeburn  9988:          '(Remote '.$ip.'): '.$reply);
1.197     www      9989:     &log($udom,,$uname,$uhome,
1.620     albertel 9990:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9991:                                      $env{'user.name'}.', '.$umode.
1.1172.2.134  raeburn  9992:          '(Remote '.$ip.'): '.$reply);
1.169     harris41 9993:     unless ($reply eq 'ok') {
1.197     www      9994:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9995: 	return 'error: '.$reply;
                   9996:     }   
1.170     harris41 9997:     return 'ok';
1.80      www      9998: }
                   9999: 
1.81      www      10000: # --------------------------------------------------------------- Modify a user
1.80      www      10001: 
1.81      www      10002: sub modifyuser {
1.206     matthew  10003:     my ($udom,    $uname, $uid,
                   10004:         $umode,   $upass, $first,
                   10005:         $middle,  $last,  $gene,
1.1058    raeburn  10006:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10007:     $udom= &LONCAPA::clean_domain($udom);
                   10008:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10009:     my $showcandelete = 'none';
                   10010:     if (ref($candelete) eq 'ARRAY') {
                   10011:         if (@{$candelete} > 0) {
                   10012:             $showcandelete = join(', ',@{$candelete});
                   10013:         }
                   10014:     }
1.81      www      10015:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10016:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10017: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10018:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10019:                                      ' desiredhome not specified'). 
1.620     albertel 10020:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10021:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10022:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10023:     my $newuser;
                   10024:     if ($uhome eq 'no_host') {
                   10025:         $newuser = 1;
                   10026:     }
1.80      www      10027: # ----------------------------------------------------------------- Create User
1.406     albertel 10028:     if (($uhome eq 'no_host') && 
                   10029: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      10030:         my $unhome='';
1.844     albertel 10031:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10032:             $unhome = $desiredhome;
1.620     albertel 10033: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10034: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10035:         } else { # load balancing routine for determining $unhome
1.81      www      10036:             my $loadm=10000000;
1.841     albertel 10037: 	    my %servers = &get_servers($udom,'library');
                   10038: 	    foreach my $tryserver (keys(%servers)) {
                   10039: 		my $answer=reply('load',$tryserver);
                   10040: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10041: 		    $loadm=$answer;
                   10042: 		    $unhome=$tryserver;
                   10043: 		}
1.80      www      10044: 	    }
                   10045:         }
                   10046:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10047: 	    return 'error: unable to find a home server for '.$uname.
                   10048:                    ' in domain '.$udom;
1.80      www      10049:         }
                   10050:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10051:                          &escape($upass),$unhome);
                   10052: 	unless ($reply eq 'ok') {
                   10053:             return 'error: '.$reply;
                   10054:         }   
1.230     stredwic 10055:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10056:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10057: 	    return 'error: unable verify users home machine.';
1.80      www      10058:         }
1.209     matthew  10059:     }   # End of creation of new user
1.80      www      10060: # ---------------------------------------------------------------------- Add ID
                   10061:     if ($uid) {
                   10062:        $uid=~tr/A-Z/a-z/;
                   10063:        my %uidhash=&idrget($udom,$uname);
1.196     www      10064:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10065:          && (!$forceid)) {
1.80      www      10066: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10067: 	      return 'error: user id "'.$uid.'" does not match '.
                   10068:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10069:           }
                   10070:        } else {
                   10071: 	  &idput($udom,($uname => $uid));
                   10072:        }
                   10073:     }
                   10074: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10075:     my @tmp=&get('environment',
1.899     raeburn  10076: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10077:                     'permanentemail','inststatus'],
1.134     albertel 10078: 		   $udom,$uname);
1.1075    raeburn  10079:     my (%names,%oldnames);
1.313     matthew  10080:     if ($tmp[0] =~ m/^error:.*/) { 
                   10081:         %names=(); 
                   10082:     } else {
                   10083:         %names = @tmp;
1.1075    raeburn  10084:         %oldnames = %names;
1.313     matthew  10085:     }
1.388     www      10086: #
1.1058    raeburn  10087: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10088: # of users did not contain them), do not overwrite existing values
                   10089: # unless field is in $candelete array ref.  
                   10090: #
                   10091: 
                   10092:     my @fields = ('firstname','middlename','lastname','generation',
                   10093:                   'permanentemail','id');
                   10094:     my %newvalues;
                   10095:     if (ref($candelete) eq 'ARRAY') {
                   10096:         foreach my $field (@fields) {
                   10097:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10098:                 if ($field eq 'firstname') {
                   10099:                     $names{$field} = $first;
                   10100:                 } elsif ($field eq 'middlename') {
                   10101:                     $names{$field} = $middle;
                   10102:                 } elsif ($field eq 'lastname') {
                   10103:                     $names{$field} = $last;
                   10104:                 } elsif ($field eq 'generation') { 
                   10105:                     $names{$field} = $gene;
                   10106:                 } elsif ($field eq 'permanentemail') {
                   10107:                     $names{$field} = $email;
                   10108:                 } elsif ($field eq 'id') {
                   10109:                     $names{$field}  = $uid;
                   10110:                 }
                   10111:             }
                   10112:         }
                   10113:     }
1.388     www      10114:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10115:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10116:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10117:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10118:     if ($email) {
                   10119:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10120:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10121:     }
1.899     raeburn  10122:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10123:     if (defined($inststatus)) {
                   10124:         $names{'inststatus'} = '';
                   10125:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10126:         if (ref($usertypes) eq 'HASH') {
                   10127:             my @okstatuses; 
                   10128:             foreach my $item (split(/:/,$inststatus)) {
                   10129:                 if (defined($usertypes->{$item})) {
                   10130:                     push(@okstatuses,$item);  
                   10131:                 }
                   10132:             }
                   10133:             if (@okstatuses) {
                   10134:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10135:             }
                   10136:         }
                   10137:     }
1.1075    raeburn  10138:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10139:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10140:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10141:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10142:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10143:     } else {
                   10144:         $logmsg .= ' during self creation';
                   10145:     }
1.1075    raeburn  10146:     my $changed;
                   10147:     if ($newuser) {
                   10148:         $changed = 1;
                   10149:     } else {
                   10150:         foreach my $field (@fields) {
                   10151:             if ($names{$field} ne $oldnames{$field}) {
                   10152:                 $changed = 1;
                   10153:                 last;
                   10154:             }
                   10155:         }
                   10156:     }
                   10157:     unless ($changed) {
                   10158:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10159:         &logthis($logmsg);
                   10160:         return 'ok';
                   10161:     }
                   10162:     my $reply = &put('environment', \%names, $udom,$uname);
                   10163:     if ($reply ne 'ok') { 
                   10164:         return 'error: '.$reply;
                   10165:     }
1.1087    raeburn  10166:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10167:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10168:     }
1.1075    raeburn  10169:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10170:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10171:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10172:     &logthis($logmsg);
1.134     albertel 10173:     return 'ok';
1.80      www      10174: }
                   10175: 
1.81      www      10176: # -------------------------------------------------------------- Modify student
1.80      www      10177: 
1.81      www      10178: sub modifystudent {
                   10179:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10180:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10181:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10182:     if (!$cid) {
1.620     albertel 10183: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10184: 	    return 'not_in_class';
                   10185: 	}
1.80      www      10186:     }
                   10187: # --------------------------------------------------------------- Make the user
1.81      www      10188:     my $reply=&modifyuser
1.209     matthew  10189: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10190:          $desiredhome,$email,$inststatus);
1.80      www      10191:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10192:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10193:     # student's environment
1.297     matthew  10194:     $uid = undef if (!$forceid);
1.455     albertel 10195:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10196: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10197:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10198:     return $reply;
                   10199: }
                   10200: 
                   10201: sub modify_student_enrollment {
1.1172.2.23  raeburn  10202:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10203:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10204:     my ($cdom,$cnum,$chome);
                   10205:     if (!$cid) {
1.620     albertel 10206: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10207: 	    return 'not_in_class';
                   10208: 	}
1.620     albertel 10209: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10210: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10211:     } else {
                   10212: 	($cdom,$cnum)=split(/_/,$cid);
                   10213:     }
1.620     albertel 10214:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10215:     if (!$chome) {
1.457     raeburn  10216: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10217:     }
1.455     albertel 10218:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10219:     # Make sure the user exists
1.81      www      10220:     my $uhome=&homeserver($uname,$udom);
                   10221:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10222: 	return 'error: no such user';
                   10223:     }
1.297     matthew  10224:     # Get student data if we were not given enough information
                   10225:     if (!defined($first)  || $first  eq '' || 
                   10226:         !defined($last)   || $last   eq '' || 
                   10227:         !defined($uid)    || $uid    eq '' || 
                   10228:         !defined($middle) || $middle eq '' || 
                   10229:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10230:         # They did not supply us with enough data to enroll the student, so
                   10231:         # we need to pick up more information.
1.297     matthew  10232:         my %tmp = &get('environment',
1.294     matthew  10233:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10234:                        ,$udom,$uname);
                   10235: 
1.800     albertel 10236:         #foreach my $key (keys(%tmp)) {
                   10237:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10238:         #}
1.294     matthew  10239:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10240:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10241:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10242:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10243:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10244:     }
1.556     albertel 10245:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10246:     my $user = "$uname:$udom";
                   10247:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10248:     my $reply=cput('classlist',
1.1148    raeburn  10249: 		   {$user => 
1.1172.2.76  raeburn  10250: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10251: 		   $cdom,$cnum);
1.1148    raeburn  10252:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10253:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10254:     } else { 
1.81      www      10255: 	return 'error: '.$reply;
                   10256:     }
1.297     matthew  10257:     # Add student role to user
1.83      www      10258:     my $uurl='/'.$cid;
1.81      www      10259:     $uurl=~s/\_/\//g;
                   10260:     if ($usec) {
                   10261: 	$uurl.='/'.$usec;
                   10262:     }
1.1148    raeburn  10263:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10264:                              $selfenroll,$context);
                   10265:     if ($result ne 'ok') {
                   10266:         if ($old_entry{$user} ne '') {
                   10267:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10268:         } else {
                   10269:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10270:         }
                   10271:     }
                   10272:     return $result; 
1.21      www      10273: }
                   10274: 
1.556     albertel 10275: sub format_name {
                   10276:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10277:     my $name;
                   10278:     if ($first ne 'lastname') {
                   10279: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10280:     } else {
                   10281: 	if ($lastname=~/\S/) {
                   10282: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10283: 	    $name=~s/\s+,/,/;
                   10284: 	} else {
                   10285: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10286: 	}
                   10287:     }
                   10288:     $name=~s/^\s+//;
                   10289:     $name=~s/\s+$//;
                   10290:     $name=~s/\s+/ /g;
                   10291:     return $name;
                   10292: }
                   10293: 
1.84      www      10294: # ------------------------------------------------- Write to course preferences
                   10295: 
                   10296: sub writecoursepref {
                   10297:     my ($courseid,%prefs)=@_;
                   10298:     $courseid=~s/^\///;
                   10299:     $courseid=~s/\_/\//g;
                   10300:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10301:     my $chome=homeserver($cnum,$cdomain);
                   10302:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10303: 	return 'error: no such course';
                   10304:     }
                   10305:     my $cstring='';
1.800     albertel 10306:     foreach my $pref (keys(%prefs)) {
                   10307: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10308:     }
1.84      www      10309:     $cstring=~s/\&$//;
                   10310:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10311: }
                   10312: 
                   10313: # ---------------------------------------------------------- Make/modify course
                   10314: 
                   10315: sub createcourse {
1.741     raeburn  10316:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  10317:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      10318:     $url=&declutter($url);
                   10319:     my $cid='';
1.1028    raeburn  10320:     if ($context eq 'requestcourses') {
                   10321:         my $can_create = 0;
                   10322:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10323:         if ($udom eq $ownerdom) {
                   10324:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   10325:                                   $context)) {
                   10326:                 $can_create = 1;
                   10327:             }
                   10328:         } else {
                   10329:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10330:                                            $category);
                   10331:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10332:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10333:                 if (@curr > 0) {
                   10334:                     my @options = qw(approval validate autolimit);
                   10335:                     my $optregex = join('|',@options);
                   10336:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10337:                         $can_create = 1;
                   10338:                     }
                   10339:                 }
                   10340:             }
                   10341:         }
                   10342:         if ($can_create) {
                   10343:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10344:                 unless (&allowed('ccc',$udom)) {
                   10345:                     return 'refused'; 
                   10346:                 }
1.1017    raeburn  10347:             }
                   10348:         } else {
                   10349:             return 'refused';
                   10350:         }
1.1028    raeburn  10351:     } elsif (!&allowed('ccc',$udom)) {
                   10352:         return 'refused';
1.84      www      10353:     }
1.1011    raeburn  10354: # --------------------------------------------------------------- Get Unique ID
                   10355:     my $uname;
                   10356:     if ($cnum =~ /^$match_courseid$/) {
                   10357:         my $chome=&homeserver($cnum,$udom,'true');
                   10358:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10359:             $uname = $cnum;
                   10360:         } else {
1.1038    raeburn  10361:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10362:         }
                   10363:     } else {
1.1038    raeburn  10364:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10365:     }
                   10366:     return $uname if ($uname =~ /^error/);
                   10367: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10368:     if (!defined($course_server)) {
                   10369:         if (defined(&domain($udom,'primary'))) {
                   10370:             $course_server = &domain($udom,'primary');
                   10371:         } else {
                   10372:             $course_server = $env{'user.home'}; 
                   10373:         }
                   10374:     }
                   10375:     my %host_servers =
                   10376:         &Apache::lonnet::get_servers($udom,'library');
                   10377:     unless ($host_servers{$course_server}) {
                   10378:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10379:     }
1.84      www      10380: # ------------------------------------------------------------- Make the course
                   10381:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10382:                       $course_server);
1.84      www      10383:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10384:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10385:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10386: 	return 'error: no such course';
                   10387:     }
1.271     www      10388: # ----------------------------------------------------------------- Course made
1.516     raeburn  10389: # log existence
1.1029    raeburn  10390:     my $now = time;
1.918     raeburn  10391:     my $newcourse = {
                   10392:                     $udom.'_'.$uname => {
1.921     raeburn  10393:                                      description => $description,
                   10394:                                      inst_code   => $inst_code,
                   10395:                                      owner       => $course_owner,
                   10396:                                      type        => $crstype,
1.1029    raeburn  10397:                                      creator     => $env{'user.name'}.':'.
                   10398:                                                     $env{'user.domain'},
                   10399:                                      created     => $now,
                   10400:                                      context     => $context,
1.918     raeburn  10401:                                                 },
                   10402:                     };
1.921     raeburn  10403:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10404: # set toplevel url
1.271     www      10405:     my $topurl=$url;
                   10406:     unless ($nonstandard) {
                   10407: # ------------------------------------------ For standard courses, make top url
                   10408:         my $mapurl=&clutter($url);
1.278     www      10409:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10410:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10411: <map>
                   10412: <resource id="1" type="start"></resource>
                   10413: <resource id="2" src="$mapurl"></resource>
                   10414: <resource id="3" type="finish"></resource>
                   10415: <link index="1" from="1" to="2"></link>
                   10416: <link index="2" from="2" to="3"></link>
                   10417: </map>
                   10418: ENDINITMAP
                   10419:         $topurl=&declutter(
1.638     albertel 10420:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10421:                           );
                   10422:     }
                   10423: # ----------------------------------------------------------- Write preferences
1.84      www      10424:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10425:                      ('description'              => $description,
                   10426:                       'url'                      => $topurl,
                   10427:                       'internal.creator'         => $env{'user.name'}.':'.
                   10428:                                                     $env{'user.domain'},
                   10429:                       'internal.created'         => $now,
                   10430:                       'internal.creationcontext' => $context)
                   10431:                     );
1.84      www      10432:     return '/'.$udom.'/'.$uname;
                   10433: }
                   10434: 
1.1011    raeburn  10435: # ------------------------------------------------------------------- Create ID
                   10436: sub generate_coursenum {
1.1038    raeburn  10437:     my ($udom,$crstype) = @_;
1.1011    raeburn  10438:     my $domdesc = &domain($udom);
                   10439:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10440:     my $first;
                   10441:     if ($crstype eq 'Community') {
                   10442:         $first = '0';
                   10443:     } else {
                   10444:         $first = int(1+rand(9)); 
                   10445:     } 
                   10446:     my $uname=$first.
1.1011    raeburn  10447:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10448:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10449:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10450: # ----------------------------------------------- Make sure that does not exist
                   10451:     my $uhome=&homeserver($uname,$udom,'true');
                   10452:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10453:         if ($crstype eq 'Community') {
                   10454:             $first = '0';
                   10455:         } else {
                   10456:             $first = int(1+rand(9));
                   10457:         }
                   10458:         $uname=$first.
1.1011    raeburn  10459:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10460:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10461:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10462:         $uhome=&homeserver($uname,$udom,'true');
                   10463:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10464:             return 'error: unable to generate unique course-ID';
                   10465:         }
                   10466:     }
                   10467:     return $uname;
                   10468: }
                   10469: 
1.813     albertel 10470: sub is_course {
1.1167    droeschl 10471:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10472:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10473:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10474:     my $uhome=&homeserver($cnum,$cdom);
                   10475:     my $iscourse;
                   10476:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10477:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10478:     } else {
                   10479:         my $hashid = $cdom.':'.$cnum;
                   10480:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10481:         unless (defined($cached)) {
                   10482:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10483:                                         $cnum,undef,undef,'.');
                   10484:             $iscourse = 0;
                   10485:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10486:                 $iscourse = 1;
                   10487:             }
                   10488:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10489:         }
                   10490:     }
                   10491:     return unless($iscourse);
1.1167    droeschl 10492:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10493: }
                   10494: 
1.1015    raeburn  10495: sub store_userdata {
                   10496:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10497:     my $result;
1.1016    raeburn  10498:     if ($datakey ne '') {
1.1013    raeburn  10499:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10500:             if ($udom eq '' || $uname eq '') {
                   10501:                 $udom = $env{'user.domain'};
                   10502:                 $uname = $env{'user.name'};
                   10503:             }
                   10504:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10505:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10506:                 $result = 'error: no_host';
                   10507:             } else {
1.1172.2.138  raeburn  10508:                 $storehash->{'ip'} = &get_requestor_ip();
1.1013    raeburn  10509:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10510: 
                   10511:                 my $namevalue='';
                   10512:                 foreach my $key (keys(%{$storehash})) {
                   10513:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10514:                 }
                   10515:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10516:                 unless ($namespace eq 'courserequests') {
                   10517:                     $datakey = &escape($datakey);
                   10518:                 }
1.1105    raeburn  10519:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10520:                                   $namevalue,$uhome);
1.1013    raeburn  10521:             }
                   10522:         } else {
                   10523:             $result = 'error: data to store was not a hash reference'; 
                   10524:         }
                   10525:     } else {
                   10526:         $result= 'error: invalid requestkey'; 
                   10527:     }
                   10528:     return $result;
                   10529: }
                   10530: 
1.21      www      10531: # ---------------------------------------------------------- Assign Custom Role
                   10532: 
                   10533: sub assigncustomrole {
1.957     raeburn  10534:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10535:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10536:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10537: }
                   10538: 
                   10539: # ----------------------------------------------------------------- Revoke Role
                   10540: 
                   10541: sub revokerole {
1.957     raeburn  10542:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10543:     my $now=time;
1.965     raeburn  10544:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10545: }
                   10546: 
                   10547: # ---------------------------------------------------------- Revoke Custom Role
                   10548: 
                   10549: sub revokecustomrole {
1.957     raeburn  10550:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10551:     my $now=time;
1.357     www      10552:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10553:            $deleteflag,$selfenroll,$context);
1.17      www      10554: }
                   10555: 
1.533     banghart 10556: # ------------------------------------------------------------ Disk usage
1.535     albertel 10557: sub diskusage {
1.955     raeburn  10558:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10559:     $directorypath =~ s/\/$//;
                   10560:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10561:                        .&escape($getpropath).':'.&escape($uname).':'
                   10562:                        .&escape($udom),homeserver($uname,$udom));
                   10563:     if ($listing eq 'unknown_cmd') {
                   10564:         if ($getpropath) {
                   10565:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10566:         }
                   10567:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10568:     }
1.514     albertel 10569:     return $listing;
1.512     banghart 10570: }
                   10571: 
1.566     banghart 10572: sub is_locked {
1.1096    raeburn  10573:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10574:     my @check;
                   10575:     my $is_locked;
1.1093    raeburn  10576:     push (@check,$file_name);
1.613     albertel 10577:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10578: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10579:     my ($tmp)=keys(%locked);
                   10580:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10581:     
1.566     banghart 10582:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10583:         $is_locked = 'false';
                   10584:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10585:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10586:                $is_locked = 'true';
1.1096    raeburn  10587:                if (ref($which) eq 'ARRAY') {
                   10588:                    push(@{$which},$entry);
                   10589:                } else {
                   10590:                    last;
                   10591:                }
1.745     raeburn  10592:            }
                   10593:        }
1.566     banghart 10594:     } else {
                   10595:         $is_locked = 'false';
                   10596:     }
1.1093    raeburn  10597:     return $is_locked;
1.566     banghart 10598: }
                   10599: 
1.759     albertel 10600: sub declutter_portfile {
                   10601:     my ($file) = @_;
1.833     albertel 10602:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10603:     return $file;
                   10604: }
                   10605: 
1.559     banghart 10606: # ------------------------------------------------------------- Mark as Read Only
                   10607: 
                   10608: sub mark_as_readonly {
                   10609:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10610:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10611:     my ($tmp)=keys(%current_permissions);
                   10612:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10613:     foreach my $file (@{$files}) {
1.759     albertel 10614: 	$file = &declutter_portfile($file);
1.561     banghart 10615:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10616:     }
1.613     albertel 10617:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10618:     return;
                   10619: }
                   10620: 
1.572     banghart 10621: # ------------------------------------------------------------Save Selected Files
                   10622: 
                   10623: sub save_selected_files {
                   10624:     my ($user, $path, @files) = @_;
                   10625:     my $filename = $user."savedfiles";
1.573     banghart 10626:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  10627:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10628:     foreach my $file (@files) {
1.620     albertel 10629:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10630:     }
                   10631:     foreach my $file (@other_files) {
1.574     banghart 10632:         print (OUT $file."\n");
1.572     banghart 10633:     }
1.574     banghart 10634:     close (OUT);
1.572     banghart 10635:     return 'ok';
                   10636: }
                   10637: 
1.574     banghart 10638: sub clear_selected_files {
                   10639:     my ($user) = @_;
                   10640:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  10641:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10642:     print (OUT undef);
                   10643:     close (OUT);
                   10644:     return ("ok");    
                   10645: }
                   10646: 
1.572     banghart 10647: sub files_in_path {
                   10648:     my ($user, $path) = @_;
                   10649:     my $filename = $user."savedfiles";
                   10650:     my %return_files;
1.1172.2.96  raeburn  10651:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10652:     while (my $line_in = <IN>) {
1.574     banghart 10653:         chomp ($line_in);
                   10654:         my @paths_and_file = split (m!/!, $line_in);
                   10655:         my $file_part = pop (@paths_and_file);
                   10656:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10657:         $path_part.='/';
                   10658:         my $path_and_file = $path_part.$file_part;
                   10659:         if ($path_part eq $path) {
                   10660:             $return_files{$file_part}= 'selected';
                   10661:         }
                   10662:     }
1.574     banghart 10663:     close (IN);
                   10664:     return (\%return_files);
1.572     banghart 10665: }
                   10666: 
                   10667: # called in portfolio select mode, to show files selected NOT in current directory
                   10668: sub files_not_in_path {
                   10669:     my ($user, $path) = @_;
                   10670:     my $filename = $user."savedfiles";
                   10671:     my @return_files;
                   10672:     my $path_part;
1.1172.2.96  raeburn  10673:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10674:     while (my $line = <IN>) {
1.572     banghart 10675:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10676:         my @paths_and_file = split(m|/|, $line);
                   10677:         my $file_part = pop(@paths_and_file);
                   10678:         chomp($file_part);
                   10679:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10680:         $path_part .= '/';
                   10681:         my $path_and_file = $path_part.$file_part;
                   10682:         if ($path_part ne $path) {
1.800     albertel 10683:             push(@return_files, ($path_and_file));
1.572     banghart 10684:         }
                   10685:     }
1.800     albertel 10686:     close(OUT);
1.574     banghart 10687:     return (@return_files);
1.572     banghart 10688: }
                   10689: 
1.745     raeburn  10690: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10691: 
1.745     raeburn  10692: sub get_portfile_permissions {
                   10693:     my ($domain,$user) = @_;
1.613     albertel 10694:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10695:     my ($tmp)=keys(%current_permissions);
                   10696:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10697:     return \%current_permissions;
                   10698: }
                   10699: 
                   10700: #---------------------------------------------Get portfolio file access controls
                   10701: 
1.749     raeburn  10702: sub get_access_controls {
1.745     raeburn  10703:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10704:     my %access;
                   10705:     my $real_file = $file;
                   10706:     $file =~ s/\.meta$//;
1.745     raeburn  10707:     if (defined($file)) {
1.749     raeburn  10708:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10709:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10710:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10711:             }
                   10712:         }
1.745     raeburn  10713:     } else {
1.749     raeburn  10714:         foreach my $key (keys(%{$current_permissions})) {
                   10715:             if ($key =~ /\0accesscontrol$/) {
                   10716:                 if (defined($group)) {
                   10717:                     if ($key !~ m-^\Q$group\E/-) {
                   10718:                         next;
                   10719:                     }
                   10720:                 }
                   10721:                 my ($fullpath) = split(/\0/,$key);
                   10722:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10723:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10724:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10725:                     }
                   10726:                 }
                   10727:             }
                   10728:         }
                   10729:     }
                   10730:     return %access;
                   10731: }
                   10732: 
                   10733: sub modify_access_controls {
                   10734:     my ($file_name,$changes,$domain,$user)=@_;
                   10735:     my ($outcome,$deloutcome);
                   10736:     my %store_permissions;
                   10737:     my %new_values;
                   10738:     my %new_control;
                   10739:     my %translation;
                   10740:     my @deletions = ();
                   10741:     my $now = time;
                   10742:     if (exists($$changes{'activate'})) {
                   10743:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10744:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10745:             my $numnew = scalar(@newitems);
                   10746:             for (my $i=0; $i<$numnew; $i++) {
                   10747:                 my $newkey = $newitems[$i];
                   10748:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10749:                 if ($newkey =~ /^\d+:/) { 
                   10750:                     $newkey =~ s/^(\d+)/$newid/;
                   10751:                     $translation{$1} = $newid;
                   10752:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10753:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10754:                     $translation{$1} = $newid;
                   10755:                 }
1.749     raeburn  10756:                 $new_values{$file_name."\0".$newkey} = 
                   10757:                                           $$changes{'activate'}{$newitems[$i]};
                   10758:                 $new_control{$newkey} = $now;
                   10759:             }
                   10760:         }
                   10761:     }
                   10762:     my %todelete;
                   10763:     my %changed_items;
                   10764:     foreach my $action ('delete','update') {
                   10765:         if (exists($$changes{$action})) {
                   10766:             if (ref($$changes{$action}) eq 'HASH') {
                   10767:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10768:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10769:                     if ($action eq 'delete') { 
                   10770:                         $todelete{$itemnum} = 1;
                   10771:                     } else {
                   10772:                         $changed_items{$itemnum} = $key;
                   10773:                     }
                   10774:                 }
1.745     raeburn  10775:             }
                   10776:         }
1.749     raeburn  10777:     }
                   10778:     # get lock on access controls for file.
                   10779:     my $lockhash = {
                   10780:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10781:                                                        ':'.$env{'user.domain'},
                   10782:                    }; 
                   10783:     my $tries = 0;
                   10784:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10785:    
1.1172.2.79  raeburn  10786:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10787:         $tries ++;
1.1172.2.79  raeburn  10788:         sleep(0.1);
1.749     raeburn  10789:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10790:     }
                   10791:     if ($gotlock eq 'ok') {
                   10792:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10793:         my ($tmp)=keys(%curr_permissions);
                   10794:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10795:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10796:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10797:             if (ref($curr_controls) eq 'HASH') {
                   10798:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10799:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10800:                     if (defined($todelete{$itemnum})) {
                   10801:                         push(@deletions,$file_name."\0".$control_item);
                   10802:                     } else {
                   10803:                         if (defined($changed_items{$itemnum})) {
                   10804:                             $new_control{$changed_items{$itemnum}} = $now;
                   10805:                             push(@deletions,$file_name."\0".$control_item);
                   10806:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10807:                         } else {
                   10808:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10809:                         }
                   10810:                     }
1.745     raeburn  10811:                 }
                   10812:             }
                   10813:         }
1.970     raeburn  10814:         my ($group);
                   10815:         if (&is_course($domain,$user)) {
                   10816:             ($group,my $file) = split(/\//,$file_name,2);
                   10817:         }
1.749     raeburn  10818:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10819:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10820:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10821:         #  remove lock
                   10822:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10823:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10824:         my $sqlresult =
1.970     raeburn  10825:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10826:                                     $group);
1.749     raeburn  10827:     } else {
                   10828:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10829:     }
1.749     raeburn  10830:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10831: }
                   10832: 
1.827     raeburn  10833: sub make_public_indefinitely {
                   10834:     my ($requrl) = @_;
                   10835:     my $now = time;
                   10836:     my $action = 'activate';
                   10837:     my $aclnum = 0;
                   10838:     if (&is_portfolio_url($requrl)) {
                   10839:         my (undef,$udom,$unum,$file_name,$group) =
                   10840:             &parse_portfolio_url($requrl);
                   10841:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10842:         my %access_controls = &get_access_controls($current_perms,
                   10843:                                                    $group,$file_name);
                   10844:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10845:             my ($num,$scope,$end,$start) = 
                   10846:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10847:             if ($scope eq 'public') {
                   10848:                 if ($start <= $now && $end == 0) {
                   10849:                     $action = 'none';
                   10850:                 } else {
                   10851:                     $action = 'update';
                   10852:                     $aclnum = $num;
                   10853:                 }
                   10854:                 last;
                   10855:             }
                   10856:         }
                   10857:         if ($action eq 'none') {
                   10858:              return 'ok';
                   10859:         } else {
                   10860:             my %changes;
                   10861:             my $newend = 0;
                   10862:             my $newstart = $now;
                   10863:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10864:             $changes{$action}{$newkey} = {
                   10865:                 type => 'public',
                   10866:                 time => {
                   10867:                     start => $newstart,
                   10868:                     end   => $newend,
                   10869:                 },
                   10870:             };
                   10871:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10872:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10873:             return $outcome;
                   10874:         }
                   10875:     } else {
                   10876:         return 'invalid';
                   10877:     }
                   10878: }
                   10879: 
1.745     raeburn  10880: #------------------------------------------------------Get Marked as Read Only
                   10881: 
                   10882: sub get_marked_as_readonly {
                   10883:     my ($domain,$user,$what,$group) = @_;
                   10884:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10885:     my @readonly_files;
1.629     banghart 10886:     my $cmp1=$what;
                   10887:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10888:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10889:         if (defined($group)) {
                   10890:             if ($file_name !~ m-^\Q$group\E/-) {
                   10891:                 next;
                   10892:             }
                   10893:         }
1.561     banghart 10894:         if (ref($value) eq "ARRAY"){
                   10895:             foreach my $stored_what (@{$value}) {
1.629     banghart 10896:                 my $cmp2=$stored_what;
1.759     albertel 10897:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10898:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10899:                 }
1.629     banghart 10900:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10901:                     push(@readonly_files, $file_name);
1.745     raeburn  10902:                     last;
1.563     banghart 10903:                 } elsif (!defined($what)) {
                   10904:                     push(@readonly_files, $file_name);
1.745     raeburn  10905:                     last;
1.561     banghart 10906:                 }
                   10907:             }
1.745     raeburn  10908:         }
1.561     banghart 10909:     }
                   10910:     return @readonly_files;
                   10911: }
1.577     banghart 10912: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10913: 
1.577     banghart 10914: sub get_marked_as_readonly_hash {
1.745     raeburn  10915:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10916:     my %readonly_files;
1.745     raeburn  10917:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10918:         if (defined($group)) {
                   10919:             if ($file_name !~ m-^\Q$group\E/-) {
                   10920:                 next;
                   10921:             }
                   10922:         }
1.577     banghart 10923:         if (ref($value) eq "ARRAY"){
                   10924:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10925:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10926:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10927:                         if ($lock_descriptor eq 'graded') {
                   10928:                             $readonly_files{$file_name} = 'graded';
                   10929:                         } elsif ($lock_descriptor eq 'handback') {
                   10930:                             $readonly_files{$file_name} = 'handback';
                   10931:                         } else {
                   10932:                             if (!exists($readonly_files{$file_name})) {
                   10933:                                 $readonly_files{$file_name} = 'locked';
                   10934:                             }
                   10935:                         }
1.745     raeburn  10936:                     }
1.750     banghart 10937:                 } 
1.577     banghart 10938:             }
                   10939:         } 
                   10940:     }
                   10941:     return %readonly_files;
                   10942: }
1.559     banghart 10943: # ------------------------------------------------------------ Unmark as Read Only
                   10944: 
                   10945: sub unmark_as_readonly {
1.629     banghart 10946:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10947:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10948:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10949:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10950:     my $symb_crs = $what;
                   10951:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10952:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10953:     my ($tmp)=keys(%current_permissions);
                   10954:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10955:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10956:     foreach my $file (@readonly_files) {
1.759     albertel 10957: 	my $clean_file = &declutter_portfile($file);
                   10958: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10959: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10960:         my @new_locks;
                   10961:         my @del_keys;
                   10962:         if (ref($current_locks) eq "ARRAY"){
                   10963:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10964:                 my $compare=$locker;
1.749     raeburn  10965:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10966:                     $compare=join('',@{$locker});
1.746     raeburn  10967:                     if ($compare ne $symb_crs) {
                   10968:                         push(@new_locks, $locker);
                   10969:                     }
1.563     banghart 10970:                 }
                   10971:             }
1.650     albertel 10972:             if (scalar(@new_locks) > 0) {
1.563     banghart 10973:                 $current_permissions{$file} = \@new_locks;
                   10974:             } else {
                   10975:                 push(@del_keys, $file);
1.613     albertel 10976:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10977:                 delete($current_permissions{$file});
1.563     banghart 10978:             }
                   10979:         }
1.561     banghart 10980:     }
1.613     albertel 10981:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10982:     return;
                   10983: }
1.512     banghart 10984: 
1.17      www      10985: # ------------------------------------------------------------ Directory lister
                   10986: 
                   10987: sub dirlist {
1.955     raeburn  10988:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10989:     $uri=~s/^\///;
                   10990:     $uri=~s/\/$//;
1.253     stredwic 10991:     my ($udom, $uname);
1.955     raeburn  10992:     if ($getuserdir) {
1.253     stredwic 10993:         $udom = $userdomain;
                   10994:         $uname = $username;
1.955     raeburn  10995:     } else {
                   10996:         (undef,$udom,$uname)=split(/\//,$uri);
                   10997:         if(defined($userdomain)) {
                   10998:             $udom = $userdomain;
                   10999:         }
                   11000:         if(defined($username)) {
                   11001:             $uname = $username;
                   11002:         }
1.253     stredwic 11003:     }
1.955     raeburn  11004:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11005: 
1.955     raeburn  11006:     $dirRoot = $perlvar{'lonDocRoot'};
                   11007:     if (defined($getpropath)) {
                   11008:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11009:         $dirRoot =~ s/\/$//;
1.955     raeburn  11010:     } elsif (defined($getuserdir)) {
                   11011:         my $subdir=$uname.'__';
                   11012:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11013:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11014:                    ."/$udom/$subdir/$uname";
                   11015:     } elsif (defined($alternateRoot)) {
                   11016:         $dirRoot = $alternateRoot;
1.751     banghart 11017:     }
1.253     stredwic 11018: 
                   11019:     if($udom) {
                   11020:         if($uname) {
1.1135    raeburn  11021:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11022:             if ($uhome eq 'no_host') {
                   11023:                 return ([],'no_host');
                   11024:             }
1.955     raeburn  11025:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11026:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11027:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11028:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11029:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11030:             } else {
                   11031:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11032:             }
1.605     matthew  11033:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11034:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11035:                 @listing_results = split(/:/,$listing);
                   11036:             } else {
                   11037:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11038:             }
1.1135    raeburn  11039:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11040:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11041:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11042:                 return ([],$listing);
                   11043:             } else {
                   11044:                 return (\@listing_results);
1.1135    raeburn  11045:             }
1.955     raeburn  11046:         } elsif(!$alternateRoot) {
1.1136    raeburn  11047:             my (%allusers,%listerror);
1.841     albertel 11048: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11049:  	    foreach my $tryserver (keys(%servers)) {
                   11050:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11051:                                   &escape($udom),$tryserver);
                   11052:                 if ($listing eq 'unknown_cmd') {
                   11053: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11054: 				      $udom, $tryserver);
                   11055:                 } else {
                   11056:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11057:                 }
1.841     albertel 11058: 		if ($listing eq 'unknown_cmd') {
                   11059: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11060: 				      $udom, $tryserver);
                   11061: 		    @listing_results = split(/:/,$listing);
                   11062: 		} else {
                   11063: 		    @listing_results =
                   11064: 			map { &unescape($_); } split(/:/,$listing);
                   11065: 		}
1.1136    raeburn  11066:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11067:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11068:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11069:                     $listerror{$tryserver} = $listing;
                   11070:                 } else {
1.841     albertel 11071: 		    foreach my $line (@listing_results) {
                   11072: 			my ($entry) = split(/&/,$line,2);
                   11073: 			$allusers{$entry} = 1;
                   11074: 		    }
                   11075: 		}
1.253     stredwic 11076:             }
1.1136    raeburn  11077:             my @alluserslist=();
1.800     albertel 11078:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11079:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11080:             }
1.1172.2.80  raeburn  11081:             if (!%listerror) {
                   11082:                 # no errors
                   11083:                 return (\@alluserslist);
                   11084:             } elsif (scalar(keys(%servers)) == 1) {
                   11085:                 # one library server, one error
                   11086:                 my ($key) = keys(%listerror);
                   11087:                 return (\@alluserslist, $listerror{$key});
                   11088:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11089:                 # con_lost indicates that we might miss data from at least one
                   11090:                 # library server
                   11091:                 return (\@alluserslist, 'con_lost');
                   11092:             } else {
                   11093:                 # multiple library servers and no con_lost -> data should be
                   11094:                 # complete.
                   11095:                 return (\@alluserslist);
                   11096:             }
                   11097: 
1.253     stredwic 11098:         } else {
1.1136    raeburn  11099:             return ([],'missing username');
1.253     stredwic 11100:         }
1.955     raeburn  11101:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11102:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11103:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11104:         return (\@all_domains);
1.955     raeburn  11105:     } else {
1.1136    raeburn  11106:         return ([],'missing domain');
1.275     stredwic 11107:     }
                   11108: }
                   11109: 
                   11110: # --------------------------------------------- GetFileTimestamp
                   11111: # This function utilizes dirlist and returns the date stamp for
                   11112: # when it was last modified.  It will also return an error of -1
                   11113: # if an error occurs
                   11114: 
                   11115: sub GetFileTimestamp {
1.955     raeburn  11116:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11117:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11118:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11119:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11120:                                     undef,$getuserdir);
                   11121:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11122:         return -1;
                   11123:     }
                   11124:     if (ref($fileref) eq 'ARRAY') {
                   11125:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11126:         # @stats contains first the filename, then the stat output
                   11127:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11128:     } else {
                   11129:         return -1;
1.253     stredwic 11130:     }
1.26      www      11131: }
                   11132: 
1.712     albertel 11133: sub stat_file {
                   11134:     my ($uri) = @_;
1.787     albertel 11135:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11136: 
1.955     raeburn  11137:     my ($udom,$uname,$file);
1.712     albertel 11138:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11139: 	($udom,$uname,$file) =
1.811     albertel 11140: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11141: 	$file = 'userfiles/'.$file;
                   11142:     }
                   11143:     if ($uri =~ m-^/res/-) {
                   11144: 	($udom,$uname) = 
1.807     albertel 11145: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11146: 	$file = $uri;
                   11147:     }
                   11148: 
                   11149:     if (!$udom || !$uname || !$file) {
                   11150: 	# unable to handle the uri
                   11151: 	return ();
                   11152:     }
1.956     raeburn  11153:     my $getpropath;
                   11154:     if ($file =~ /^userfiles\//) {
                   11155:         $getpropath = 1;
                   11156:     }
1.1136    raeburn  11157:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11158:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11159:         return ();
                   11160:     } else {
                   11161:         if (ref($listref) eq 'ARRAY') {
                   11162:             my @stats = split('&',$listref->[0]);
                   11163: 	    shift(@stats); #filename is first
                   11164: 	    return @stats;
                   11165:         }
1.712     albertel 11166:     }
                   11167:     return ();
                   11168: }
                   11169: 
1.26      www      11170: # -------------------------------------------------------- Value of a Condition
                   11171: 
1.713     albertel 11172: # gets the value of a specific preevaluated condition
                   11173: #    stored in the string  $env{user.state.<cid>}
                   11174: # or looks up a condition reference in the bighash and if if hasn't
                   11175: # already been evaluated recurses into docondval to get the value of
                   11176: # the condition, then memoizing it to 
                   11177: #   $env{user.state.<cid>.<condition>}
1.40      www      11178: sub directcondval {
                   11179:     my $number=shift;
1.620     albertel 11180:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11181: 	&Apache::lonuserstate::evalstate();
                   11182:     }
1.713     albertel 11183:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11184: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11185:     } elsif ($number =~ /^_/) {
                   11186: 	my $sub_condition;
                   11187: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11188: 		&GDBM_READER(),0640)) {
                   11189: 	    $sub_condition=$bighash{'conditions'.$number};
                   11190: 	    untie(%bighash);
                   11191: 	}
                   11192: 	my $value = &docondval($sub_condition);
1.949     raeburn  11193: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11194: 	return $value;
                   11195:     }
1.620     albertel 11196:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11197:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11198:     } else {
                   11199:        return 2;
                   11200:     }
                   11201: }
                   11202: 
1.713     albertel 11203: # get the collection of conditions for this resource
1.26      www      11204: sub condval {
                   11205:     my $condidx=shift;
1.54      www      11206:     my $allpathcond='';
1.713     albertel 11207:     foreach my $cond (split(/\|/,$condidx)) {
                   11208: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11209: 	    $allpathcond.=
                   11210: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11211: 	}
1.191     harris41 11212:     }
1.54      www      11213:     $allpathcond=~s/\|$//;
1.713     albertel 11214:     return &docondval($allpathcond);
                   11215: }
                   11216: 
                   11217: #evaluates an expression of conditions
                   11218: sub docondval {
                   11219:     my ($allpathcond) = @_;
                   11220:     my $result=0;
                   11221:     if ($env{'request.course.id'}
                   11222: 	&& defined($allpathcond)) {
                   11223: 	my $operand='|';
                   11224: 	my @stack;
                   11225: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11226: 	    if ($chunk eq '(') {
                   11227: 		push @stack,($operand,$result);
                   11228: 	    } elsif ($chunk eq ')') {
                   11229: 		my $before=pop @stack;
                   11230: 		if (pop @stack eq '&') {
                   11231: 		    $result=$result>$before?$before:$result;
                   11232: 		} else {
                   11233: 		    $result=$result>$before?$result:$before;
                   11234: 		}
                   11235: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11236: 		$operand=$chunk;
                   11237: 	    } else {
                   11238: 		my $new=directcondval($chunk);
                   11239: 		if ($operand eq '&') {
                   11240: 		    $result=$result>$new?$new:$result;
                   11241: 		} else {
                   11242: 		    $result=$result>$new?$result:$new;
                   11243: 		}
                   11244: 	    }
                   11245: 	}
1.26      www      11246:     }
                   11247:     return $result;
1.421     albertel 11248: }
                   11249: 
                   11250: # ---------------------------------------------------- Devalidate courseresdata
                   11251: 
                   11252: sub devalidatecourseresdata {
                   11253:     my ($coursenum,$coursedomain)=@_;
                   11254:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11255:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11256: }
                   11257: 
1.763     www      11258: 
1.200     www      11259: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11260: #
                   11261: #  Parameters:
                   11262: #      $coursenum    - Number of the course.
                   11263: #      $coursedomain - Domain at which the course was created.
                   11264: #  Returns:
                   11265: #     A hash of the course parameters along (I think) with timestamps
                   11266: #     and version info.
1.877     foxr     11267: 
1.624     albertel 11268: sub get_courseresdata {
                   11269:     my ($coursenum,$coursedomain)=@_;
1.200     www      11270:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11271:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11272:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11273:     my %dumpreply;
1.417     albertel 11274:     unless (defined($cached)) {
1.624     albertel 11275: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11276: 	$result=\%dumpreply;
1.251     albertel 11277: 	my ($tmp) = keys(%dumpreply);
                   11278: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11279: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11280: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11281: 	    return $tmp;
1.416     albertel 11282: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11283: 	    $result=undef;
1.599     albertel 11284: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11285: 	}
                   11286:     }
1.624     albertel 11287:     return $result;
                   11288: }
                   11289: 
1.633     albertel 11290: sub devalidateuserresdata {
                   11291:     my ($uname,$udom)=@_;
                   11292:     my $hashid="$udom:$uname";
                   11293:     &devalidate_cache_new('userres',$hashid);
                   11294: }
                   11295: 
1.624     albertel 11296: sub get_userresdata {
                   11297:     my ($uname,$udom)=@_;
                   11298:     #most student don\'t have any data set, check if there is some data
                   11299:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11300: 
                   11301:     my $hashid="$udom:$uname";
                   11302:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11303:     if (!defined($cached)) {
                   11304: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11305: 	$result=\%resourcedata;
                   11306: 	&do_cache_new('userres',$hashid,$result,600);
                   11307:     }
                   11308:     my ($tmp)=keys(%$result);
                   11309:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11310: 	return $result;
                   11311:     }
                   11312:     #error 2 occurs when the .db doesn't exist
                   11313:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11314:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11315: 	    &logthis("<font color=\"blue\">WARNING:".
                   11316: 		     " Trying to get resource data for ".
                   11317: 		     $uname." at ".$udom.": ".
                   11318: 		     $tmp."</font>");
                   11319:         }
1.624     albertel 11320:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11321: 	#&EXT_cache_set($udom,$uname);
                   11322: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11323: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11324:     }
                   11325:     return $tmp;
                   11326: }
1.879     foxr     11327: #----------------------------------------------- resdata - return resource data
                   11328: #  Purpose:
                   11329: #    Return resource data for either users or for a course.
                   11330: #  Parameters:
                   11331: #     $name      - Course/user name.
                   11332: #     $domain    - Name of the domain the user/course is registered on.
                   11333: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   11334: #     @which     - Array of names of resources desired.
                   11335: #  Returns:
                   11336: #     The value of the first reasource in @which that is found in the
                   11337: #     resource hash.
                   11338: #  Exceptional Conditions:
                   11339: #     If the $type passed in is not valid (not the string 'course' or 
                   11340: #     'user', an undefined  reference is returned.
                   11341: #     If none of the resources are found, an undef is returned
1.624     albertel 11342: sub resdata {
                   11343:     my ($name,$domain,$type,@which)=@_;
                   11344:     my $result;
                   11345:     if ($type eq 'course') {
                   11346: 	$result=&get_courseresdata($name,$domain);
                   11347:     } elsif ($type eq 'user') {
                   11348: 	$result=&get_userresdata($name,$domain);
                   11349:     }
                   11350:     if (!ref($result)) { return $result; }    
1.251     albertel 11351:     foreach my $item (@which) {
1.927     albertel 11352: 	if (defined($result->{$item->[0]})) {
                   11353: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11354: 	}
1.250     albertel 11355:     }
1.291     albertel 11356:     return undef;
1.200     www      11357: }
                   11358: 
1.1172.2.31  raeburn  11359: sub get_numsuppfiles {
                   11360:     my ($cnum,$cdom,$ignorecache)=@_;
                   11361:     my $hashid=$cnum.':'.$cdom;
                   11362:     my ($suppcount,$cached);
                   11363:     unless ($ignorecache) {
                   11364:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11365:     }
                   11366:     unless (defined($cached)) {
                   11367:         my $chome=&homeserver($cnum,$cdom);
                   11368:         unless ($chome eq 'no_host') {
                   11369:             ($suppcount,my $errors) = (0,0);
                   11370:             my $suppmap = 'supplemental.sequence';
                   11371:             ($suppcount,$errors) =
                   11372:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11373:         }
                   11374:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11375:     }
                   11376:     return $suppcount;
                   11377: }
                   11378: 
1.379     matthew  11379: #
                   11380: # EXT resource caching routines
                   11381: #
                   11382: 
                   11383: sub clear_EXT_cache_status {
1.383     albertel 11384:     &delenv('cache.EXT.');
1.379     matthew  11385: }
                   11386: 
                   11387: sub EXT_cache_status {
                   11388:     my ($target_domain,$target_user) = @_;
1.383     albertel 11389:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11390:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11391:         # We know already the user has no data
                   11392:         return 1;
                   11393:     } else {
                   11394:         return 0;
                   11395:     }
                   11396: }
                   11397: 
                   11398: sub EXT_cache_set {
                   11399:     my ($target_domain,$target_user) = @_;
1.383     albertel 11400:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11401:     #&appenv({$cachename => time});
1.379     matthew  11402: }
                   11403: 
1.28      www      11404: # --------------------------------------------------------- Value of a Variable
1.58      www      11405: sub EXT {
1.715     albertel 11406: 
1.1172.2.28  raeburn  11407:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11408:     unless ($varname) { return ''; }
1.218     albertel 11409:     #get real user name/domain, courseid and symb
                   11410:     my $courseid;
1.359     albertel 11411:     my $publicuser;
1.427     www      11412:     if ($symbparm) {
                   11413: 	$symbparm=&get_symb_from_alias($symbparm);
                   11414:     }
1.218     albertel 11415:     if (!($uname && $udom)) {
1.790     albertel 11416:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11417:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11418:     } else {
1.620     albertel 11419: 	$courseid=$env{'request.course.id'};
1.218     albertel 11420:     }
1.48      www      11421:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11422:     my $rest;
1.320     albertel 11423:     if (defined($therest[0])) {
1.48      www      11424:        $rest=join('.',@therest);
                   11425:     } else {
                   11426:        $rest='';
                   11427:     }
1.320     albertel 11428: 
1.57      www      11429:     my $qualifierrest=$qualifier;
                   11430:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11431:     my $spacequalifierrest=$space;
                   11432:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11433:     if ($realm eq 'user') {
1.48      www      11434: # --------------------------------------------------------------- user.resource
                   11435: 	if ($space eq 'resource') {
1.651     albertel 11436: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11437: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11438: 		 &&
1.744     albertel 11439: 		 ($symbparm eq &symbread()) ) {	
                   11440: 		# if we are in the middle of processing the resource the
                   11441: 		# get the value we are planning on committing
                   11442:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11443:                     return $Apache::lonhomework::results{$qualifierrest};
                   11444:                 } else {
                   11445:                     return $Apache::lonhomework::history{$qualifierrest};
                   11446:                 }
1.335     albertel 11447: 	    } else {
1.359     albertel 11448: 		my %restored;
1.620     albertel 11449: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11450: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11451: 		} else {
                   11452: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11453: 		}
1.335     albertel 11454: 		return $restored{$qualifierrest};
                   11455: 	    }
1.48      www      11456: # ----------------------------------------------------------------- user.access
                   11457:         } elsif ($space eq 'access') {
1.218     albertel 11458: 	    # FIXME - not supporting calls for a specific user
1.48      www      11459:             return &allowed($qualifier,$rest);
                   11460: # ------------------------------------------ user.preferences, user.environment
                   11461:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11462: 	    if (($uname eq $env{'user.name'}) &&
                   11463: 		($udom eq $env{'user.domain'})) {
                   11464: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11465: 	    } else {
1.359     albertel 11466: 		my %returnhash;
                   11467: 		if (!$publicuser) {
                   11468: 		    %returnhash=&userenvironment($udom,$uname,
                   11469: 						 $qualifierrest);
                   11470: 		}
1.218     albertel 11471: 		return $returnhash{$qualifierrest};
                   11472: 	    }
1.48      www      11473: # ----------------------------------------------------------------- user.course
                   11474:         } elsif ($space eq 'course') {
1.218     albertel 11475: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11476:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11477: # ------------------------------------------------------------------- user.role
                   11478:         } elsif ($space eq 'role') {
1.218     albertel 11479: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11480:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11481:             if ($qualifier eq 'value') {
                   11482: 		return $role;
                   11483:             } elsif ($qualifier eq 'extent') {
                   11484:                 return $where;
                   11485:             }
                   11486: # ----------------------------------------------------------------- user.domain
                   11487:         } elsif ($space eq 'domain') {
1.218     albertel 11488:             return $udom;
1.48      www      11489: # ------------------------------------------------------------------- user.name
                   11490:         } elsif ($space eq 'name') {
1.218     albertel 11491:             return $uname;
1.48      www      11492: # ---------------------------------------------------- Any other user namespace
1.29      www      11493:         } else {
1.359     albertel 11494: 	    my %reply;
                   11495: 	    if (!$publicuser) {
                   11496: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11497: 	    }
                   11498: 	    return $reply{$qualifierrest};
1.48      www      11499:         }
1.236     www      11500:     } elsif ($realm eq 'query') {
                   11501: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11502:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11503: 						[$spacequalifierrest]);
1.620     albertel 11504: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11505:    } elsif ($realm eq 'request') {
1.48      www      11506: # ------------------------------------------------------------- request.browser
                   11507:         if ($space eq 'browser') {
1.1145    bisitz   11508:             return $env{'browser.'.$qualifier};
1.57      www      11509: # ------------------------------------------------------------ request.filename
                   11510:         } else {
1.620     albertel 11511:             return $env{'request.'.$spacequalifierrest};
1.29      www      11512:         }
1.28      www      11513:     } elsif ($realm eq 'course') {
1.48      www      11514: # ---------------------------------------------------------- course.description
1.620     albertel 11515:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11516:     } elsif ($realm eq 'resource') {
1.165     www      11517: 
1.620     albertel 11518: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11519: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11520: 	}
1.693     albertel 11521: 
1.1172.2.30  raeburn  11522:         if ($qualifier eq '') {
                   11523: 	    if ($space eq 'title') {
                   11524: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11525: 	        return &gettitle($symbparm);
                   11526: 	    }
1.693     albertel 11527: 	
1.1172.2.30  raeburn  11528: 	    if ($space eq 'map') {
                   11529: 	        my ($map) = &decode_symb($symbparm);
                   11530: 	        return &symbread($map);
                   11531: 	    }
                   11532:             if ($space eq 'maptitle') {
                   11533:                 my ($map) = &decode_symb($symbparm);
                   11534:                 return &gettitle($map);
                   11535:             }
                   11536: 	    if ($space eq 'filename') {
                   11537: 	        if ($symbparm) {
                   11538: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11539: 	        }
                   11540: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11541: 	    }
1.1172.2.30  raeburn  11542: 
                   11543:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11544:                 if ($space eq 'visibleparts') {
                   11545:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11546:                     my $item;
                   11547:                     if (ref($navmap)) {
                   11548:                         my $res = $navmap->getBySymb($symbparm);
                   11549:                         my $parts = $res->parts();
                   11550:                         if (ref($parts) eq 'ARRAY') {
                   11551:                             $item = join(',',@{$parts});
                   11552:                         }
                   11553:                         undef($navmap);
                   11554:                     }
                   11555:                     return $item;
                   11556:                 }
                   11557:             }
                   11558:         }
1.693     albertel 11559: 
                   11560: 	my ($section, $group, @groups);
1.593     albertel 11561: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  11562:         if (($courseid eq '') && ($cid)) {
                   11563:             $courseid = $cid;
                   11564:         }
                   11565: 	if (($symbparm && $courseid) && 
                   11566: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      11567: 
1.218     albertel 11568: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11569: 
1.60      www      11570: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11571: 	    my $symbp=$symbparm;
1.735     albertel 11572: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11573: 
                   11574: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   11575: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   11576: 
1.620     albertel 11577: 	    if (($env{'user.name'} eq $uname) &&
                   11578: 		($env{'user.domain'} eq $udom)) {
                   11579: 		$section=$env{'request.course.sec'};
1.733     raeburn  11580:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11581:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11582: 	    } else {
1.539     albertel 11583: 		if (! defined($usection)) {
1.551     albertel 11584: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11585: 		} else {
                   11586: 		    $section = $usection;
                   11587: 		}
1.733     raeburn  11588:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11589: 	    }
                   11590: 
                   11591: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11592: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   11593: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11594: 
1.593     albertel 11595: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11596: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 11597: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11598: 
1.60      www      11599: # ----------------------------------------------------------- first, check user
1.624     albertel 11600: 
                   11601: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 11602: 				       ([$courselevelr,'resource'],
                   11603: 					[$courselevelm,'map'     ],
                   11604: 					[$courselevel, 'course'  ]));
1.931     albertel 11605: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11606: 
1.594     albertel 11607: # ------------------------------------------------ second, check some of course
1.684     raeburn  11608:             my $coursereply;
1.691     raeburn  11609:             if (@groups > 0) {
                   11610:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   11611:                                        $mapparm,$spacequalifierrest);
1.927     albertel 11612:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  11613:             }
1.96      www      11614: 
1.684     raeburn  11615: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11616: 				  $env{'course.'.$courseid.'.domain'},
                   11617: 				  'course',
                   11618: 				  ([$seclevelr,   'resource'],
                   11619: 				   [$seclevelm,   'map'     ],
                   11620: 				   [$seclevel,    'course'  ],
                   11621: 				   [$courselevelr,'resource']));
                   11622: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11623: 
1.60      www      11624: # ------------------------------------------------------ third, check map parms
1.218     albertel 11625: 	    my %parmhash=();
                   11626: 	    my $thisparm='';
                   11627: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11628: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11629: 		    &GDBM_READER(),0640)) {
1.218     albertel 11630: 		$thisparm=$parmhash{$symbparm};
                   11631: 		untie(%parmhash);
                   11632: 	    }
1.927     albertel 11633: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11634: 	}
1.594     albertel 11635: # ------------------------------------------ fourth, look in resource metadata
1.71      www      11636: 
1.218     albertel 11637: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 11638: 	my $filename;
                   11639: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11640: 	if ($symbparm) {
1.409     www      11641: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11642: 	} else {
1.620     albertel 11643: 	    $filename=$env{'request.filename'};
1.282     albertel 11644: 	}
                   11645: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 11646: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 11647: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 11648: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11649: 
1.927     albertel 11650: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 11651: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11652: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11653: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11654: 				     $env{'course.'.$courseid.'.domain'},
                   11655: 				     'course',
1.927     albertel 11656: 				     ([$courselevelm,'map'   ],
                   11657: 				      [$courselevel, 'course']));
                   11658: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11659: 	}
1.145     www      11660: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11661: 	unless ($space eq '0') {
1.336     albertel 11662: 	    my @parts=split(/_/,$space);
                   11663: 	    my $id=pop(@parts);
                   11664: 	    my $part=join('_',@parts);
                   11665: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11666: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11667: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11668: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11669: 	}
1.395     albertel 11670: 	if ($recurse) { return undef; }
                   11671: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11672: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11673: # ---------------------------------------------------- Any other user namespace
                   11674:     } elsif ($realm eq 'environment') {
                   11675: # ----------------------------------------------------------------- environment
1.620     albertel 11676: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11677: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11678: 	} else {
1.770     albertel 11679: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11680: 		return '';
                   11681: 	    }
1.219     albertel 11682: 	    my %returnhash=&userenvironment($udom,$uname,
                   11683: 					    $spacequalifierrest);
                   11684: 	    return $returnhash{$spacequalifierrest};
                   11685: 	}
1.28      www      11686:     } elsif ($realm eq 'system') {
1.48      www      11687: # ----------------------------------------------------------------- system.time
                   11688: 	if ($space eq 'time') {
                   11689: 	    return time;
                   11690:         }
1.696     albertel 11691:     } elsif ($realm eq 'server') {
                   11692: # ----------------------------------------------------------------- system.time
                   11693: 	if ($space eq 'name') {
                   11694: 	    return $ENV{'SERVER_NAME'};
                   11695:         }
1.28      www      11696:     }
1.48      www      11697:     return '';
1.61      www      11698: }
                   11699: 
1.927     albertel 11700: sub get_reply {
                   11701:     my ($reply_value) = @_;
1.940     raeburn  11702:     if (ref($reply_value) eq 'ARRAY') {
                   11703:         if (wantarray) {
                   11704: 	    return @$reply_value;
                   11705:         }
                   11706:         return $reply_value->[0];
                   11707:     } else {
                   11708:         return $reply_value;
1.927     albertel 11709:     }
                   11710: }
                   11711: 
1.691     raeburn  11712: sub check_group_parms {
                   11713:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11714:     my @groupitems = ();
                   11715:     my $resultitem;
1.927     albertel 11716:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11717:     foreach my $group (@{$groups}) {
                   11718:         foreach my $level (@levels) {
1.927     albertel 11719:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11720:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11721:         }
                   11722:     }
                   11723:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11724:                             $env{'course.'.$courseid.'.domain'},
                   11725:                                      'course',@groupitems);
                   11726:     return $coursereply;
                   11727: }
                   11728: 
                   11729: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11730:     my ($courseid,@groups) = @_;
                   11731:     @groups = sort(@groups);
1.691     raeburn  11732:     return @groups;
                   11733: }
                   11734: 
1.395     albertel 11735: sub packages_tab_default {
                   11736:     my ($uri,$varname)=@_;
                   11737:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11738: 
                   11739:     my (@extension,@specifics,$do_default);
                   11740:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11741: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11742: 	if ($pack_type eq 'default') {
                   11743: 	    $do_default=1;
                   11744: 	} elsif ($pack_type eq 'extension') {
                   11745: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11746: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11747: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11748: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11749: 	}
                   11750:     }
                   11751:     # first look for a package that matches the requested part id
                   11752:     foreach my $package (@specifics) {
                   11753: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11754: 	next if ($pack_part ne $part);
                   11755: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11756: 	    return $packagetab{"$pack_type&$name&default"};
                   11757: 	}
                   11758:     }
                   11759:     # look for any possible matching non extension_ package
                   11760:     foreach my $package (@specifics) {
                   11761: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11762: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11763: 	    return $packagetab{"$pack_type&$name&default"};
                   11764: 	}
1.585     albertel 11765: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11766: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11767: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11768: 	}
                   11769:     }
1.738     albertel 11770:     # look for any posible extension_ match
                   11771:     foreach my $package (@extension) {
                   11772: 	my ($package,$pack_type)=@{$package};
                   11773: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11774: 	    return $packagetab{"$pack_type&$name&default"};
                   11775: 	}
                   11776: 	if (defined($packagetab{$package."&$name&default"})) {
                   11777: 	    return $packagetab{$package."&$name&default"};
                   11778: 	}
                   11779:     }
                   11780:     # look for a global default setting
                   11781:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11782: 	return $packagetab{"default&$name&default"};
                   11783:     }
1.395     albertel 11784:     return undef;
                   11785: }
                   11786: 
1.334     albertel 11787: sub add_prefix_and_part {
                   11788:     my ($prefix,$part)=@_;
                   11789:     my $keyroot;
                   11790:     if (defined($prefix) && $prefix !~ /^__/) {
                   11791: 	# prefix that has a part already
                   11792: 	$keyroot=$prefix;
                   11793:     } elsif (defined($prefix)) {
                   11794: 	# prefix that is missing a part
                   11795: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11796:     } else {
                   11797: 	# no prefix at all
                   11798: 	if (defined($part)) { $keyroot='_'.$part; }
                   11799:     }
                   11800:     return $keyroot;
                   11801: }
                   11802: 
1.71      www      11803: # ---------------------------------------------------------------- Get metadata
                   11804: 
1.599     albertel 11805: my %metaentry;
1.1070    www      11806: my %importedpartids;
1.1172.2.99  raeburn  11807: my %importedrespids;
1.71      www      11808: sub metadata {
1.176     www      11809:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11810:     $uri=&declutter($uri);
1.288     albertel 11811:     # if it is a non metadata possible uri return quickly
1.529     albertel 11812:     if (($uri eq '') || 
                   11813: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.20  raeburn  11814: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
1.1108    raeburn  11815:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11816: 	return undef;
                   11817:     }
1.1172.2.49  raeburn  11818:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11819: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11820: 	return undef;
1.288     albertel 11821:     }
1.73      www      11822:     my $filename=$uri;
                   11823:     $uri=~s/\.meta$//;
1.172     www      11824: #
                   11825: # Is the metadata already cached?
1.177     www      11826: # Look at timestamp of caching
1.172     www      11827: # Everything is cached by the main uri, libraries are never directly cached
                   11828: #
1.428     albertel 11829:     if (!defined($liburi)) {
1.599     albertel 11830: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11831: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11832:     }
                   11833:     {
1.1069    www      11834: # Imported parts would go here
1.1172.2.99  raeburn  11835:         my @origfiletagids=();
1.1069    www      11836:         my $importedparts=0;
1.1172.2.99  raeburn  11837: 
                   11838: # Imported responseids would go here
                   11839:         my $importedresponses=0;
1.172     www      11840: #
                   11841: # Is this a recursive call for a library?
                   11842: #
1.599     albertel 11843: #	if (! exists($metacache{$uri})) {
                   11844: #	    $metacache{$uri}={};
                   11845: #	}
1.924     albertel 11846: 	my $cachetime = 60*60;
1.171     www      11847:         if ($liburi) {
                   11848: 	    $liburi=&declutter($liburi);
                   11849:             $filename=$liburi;
1.401     bowersj2 11850:         } else {
1.599     albertel 11851: 	    &devalidate_cache_new('meta',$uri);
                   11852: 	    undef(%metaentry);
1.401     bowersj2 11853: 	}
1.140     www      11854:         my %metathesekeys=();
1.73      www      11855:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11856: 	my $metastring;
1.1140    www      11857: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11858: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11859: 	    $metastring = 
1.929     albertel 11860: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11861: 					  ('grade_target' => 'meta'));
                   11862: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11863: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11864:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11865: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11866: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11867: 	    $metastring=&getfile($file);
1.489     albertel 11868: 	}
1.208     albertel 11869:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11870:         my $token;
1.140     www      11871:         undef %metathesekeys;
1.71      www      11872:         while ($token=$parser->get_token) {
1.339     albertel 11873: 	    if ($token->[0] eq 'S') {
                   11874: 		if (defined($token->[2]->{'package'})) {
1.172     www      11875: #
                   11876: # This is a package - get package info
                   11877: #
1.339     albertel 11878: 		    my $package=$token->[2]->{'package'};
                   11879: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11880: 		    if (defined($token->[2]->{'id'})) { 
                   11881: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11882: 		    }
1.599     albertel 11883: 		    if ($metaentry{':packages'}) {
                   11884: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11885: 		    } else {
1.599     albertel 11886: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11887: 		    }
1.736     albertel 11888: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11889: 			my $part=$keyroot;
                   11890: 			$part=~s/^\_//;
1.736     albertel 11891: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11892: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11893: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11894: 			    # ignore package.tab specified default values
                   11895:                             # here &package_tab_default() will fetch those
                   11896: 			    if ($subp eq 'default') { next; }
1.736     albertel 11897: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11898: 			    my $unikey;
                   11899: 			    if ($pack =~ /_0$/) {
                   11900: 				$unikey='parameter_0_'.$name;
                   11901: 				$part=0;
                   11902: 			    } else {
                   11903: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11904: 			    }
1.339     albertel 11905: 			    if ($subp eq 'display') {
                   11906: 				$value.=' [Part: '.$part.']';
                   11907: 			    }
1.599     albertel 11908: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11909: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11910: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11911: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11912: 			    }
1.599     albertel 11913: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11914: 				$metaentry{':'.$unikey}=
                   11915: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11916: 			    }
1.339     albertel 11917: 			}
                   11918: 		    }
                   11919: 		} else {
1.172     www      11920: #
                   11921: # This is not a package - some other kind of start tag
1.339     albertel 11922: #
                   11923: 		    my $entry=$token->[1];
1.1068    www      11924: 		    my $unikey='';
1.175     www      11925: 
1.339     albertel 11926: 		    if ($entry eq 'import') {
1.175     www      11927: #
                   11928: # Importing a library here
1.339     albertel 11929: #
1.1067    www      11930:                         my $location=$parser->get_text('/import');
                   11931:                         my $dir=$filename;
                   11932:                         $dir=~s|[^/]*$||;
                   11933:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  11934: 
                   11935:                         my $importid=$token->[2]->{'id'};
1.1068    www      11936:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  11937: #
                   11938: # Check metadata for imported file to
                   11939: # see if it contained response items
                   11940: #
                   11941:                         my %currmetaentry = %metaentry;
                   11942:                         my $libresponseorder = &metadata($location,'responseorder');
                   11943:                         my $origfile;
                   11944:                         if ($libresponseorder ne '') {
                   11945:                             if ($#origfiletagids<0) {
                   11946:                                 undef(%importedrespids);
                   11947:                                 undef(%importedpartids);
                   11948:                             }
                   11949:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   11950:                             if (@{$importedrespids{$importid}} > 0) {
                   11951:                                 $importedresponses = 1;
                   11952: # We need to get the original file and the imported file to get the response order correct
                   11953: # Load and inspect original file
                   11954:                                 if ($#origfiletagids<0) {
                   11955:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11956:                                     $origfile=&getfile($origfilelocation);
                   11957:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11958:                                 }
                   11959:                             }
                   11960:                         }
                   11961: # Do not overwrite contents of %metaentry hash for resource itself with 
                   11962: # hash populated for imported library file
                   11963:                         %metaentry = %currmetaentry;
                   11964:                         undef(%currmetaentry);
1.1068    www      11965:                         if ($importmode eq 'problem') {
1.1069    www      11966: # Import as problem/response
1.1068    www      11967:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11968:                         } elsif ($importmode eq 'part') {
                   11969: # Import as part(s)
1.1069    www      11970:                            $importedparts=1;
                   11971: # We need to get the original file and the imported file to get the part order correct
                   11972: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  11973: # Load and inspect original file if we didn't do that already
                   11974:                            if ($#origfiletagids<0) {
                   11975:                                undef(%importedrespids);
                   11976:                                undef(%importedpartids);
                   11977:                                if ($origfile eq '') {
                   11978:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11979:                                    $origfile=&getfile($origfilelocation);
                   11980:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11981:                                }
1.1070    www      11982:                            }
                   11983: 
1.1069    www      11984: # Load and inspect imported file
                   11985:                            my $impfile=&getfile($location);
                   11986:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11987:                            if ($#impfilepartids>=0) {
                   11988: # This problem had parts
1.1070    www      11989:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11990:                            } else {
                   11991: # Importing by turning a single problem into a problem part
                   11992: # It gets the import-tags ID as part-ID
                   11993:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11994:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11995:                            }
1.1068    www      11996:                         } else {
                   11997: # Normal import
                   11998:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11999:                            if (defined($token->[2]->{'id'})) {
                   12000:                               $unikey.='_'.$token->[2]->{'id'};
                   12001:                            }
1.1067    www      12002:                         }
                   12003: 
1.339     albertel 12004: 			if ($depthcount<20) {
1.736     albertel 12005: 			    my $metadata = 
                   12006: 				&metadata($uri,'keys', $location,$unikey,
                   12007: 					  $depthcount+1);
                   12008: 			    foreach my $meta (split(',',$metadata)) {
                   12009: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12010: 				$metathesekeys{$meta}=1;
1.339     albertel 12011: 			    }
1.1068    www      12012: 			
                   12013:                         }
1.1067    www      12014: 		    } else {
                   12015: #
                   12016: # Not importing, some other kind of non-package, non-library start tag
                   12017: # 
                   12018:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12019:                         if (defined($token->[2]->{'id'})) {
                   12020:                             $unikey.='_'.$token->[2]->{'id'};
                   12021:                         }
1.339     albertel 12022: 			if (defined($token->[2]->{'name'})) { 
                   12023: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12024: 			}
                   12025: 			$metathesekeys{$unikey}=1;
1.736     albertel 12026: 			foreach my $param (@{$token->[3]}) {
                   12027: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12028: 				$token->[2]->{$param};
1.339     albertel 12029: 			}
                   12030: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12031: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12032: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12033: 		 # only ws inside the tag, and not in default, so use default
                   12034: 		 # as value
1.599     albertel 12035: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12036: 			} elsif ( $internaltext =~ /\S/ ) {
                   12037: 		  # something interesting inside the tag
                   12038: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12039: 			} else {
1.908     albertel 12040: 		  # no interesting values, don't set a default
1.339     albertel 12041: 			}
1.172     www      12042: # end of not-a-package not-a-library import
1.339     albertel 12043: 		    }
1.172     www      12044: # end of not-a-package start tag
1.339     albertel 12045: 		}
1.172     www      12046: # the next is the end of "start tag"
1.339     albertel 12047: 	    }
                   12048: 	}
1.483     albertel 12049: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12050: 	$extension = lc($extension);
                   12051: 	if ($extension eq 'htm') { $extension='html'; }
                   12052: 
1.737     albertel 12053: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12054: 	    #no specific packages #how's our extension
                   12055: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12056: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12057: 					 \%metathesekeys);
                   12058: 	}
1.883     albertel 12059: 
                   12060: 	if (!exists($metaentry{':packages'})
                   12061: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12062: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12063: 		#no specific packages well let's get default then
                   12064: 		if ($key!~/^default&/) { next; }
1.488     albertel 12065: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12066: 					     \%metathesekeys);
                   12067: 	    }
                   12068: 	}
1.338     www      12069: # are there custom rights to evaluate
1.599     albertel 12070: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12071: 
1.338     www      12072:     #
                   12073:     # Importing a rights file here
1.339     albertel 12074:     #
                   12075: 	    unless ($depthcount) {
1.599     albertel 12076: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12077: 		my $dir=$filename;
                   12078: 		$dir=~s|[^/]*$||;
                   12079: 		$location=&filelocation($dir,$location);
1.736     albertel 12080: 		my $rights_metadata =
                   12081: 		    &metadata($uri,'keys',$location,'_rights',
                   12082: 			      $depthcount+1);
                   12083: 		foreach my $rights (split(',',$rights_metadata)) {
                   12084: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12085: 		    $metathesekeys{$rights}=1;
1.339     albertel 12086: 		}
                   12087: 	    }
                   12088: 	}
1.737     albertel 12089: 	# uniqifiy package listing
                   12090: 	my %seen;
                   12091: 	my @uniq_packages =
                   12092: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12093: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12094: 
1.1172.2.99  raeburn  12095:         if (($importedresponses) || ($importedparts)) {
                   12096:             if ($importedparts) {
1.1070    www      12097: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  12098:                 $metaentry{':partorder'}='';
                   12099:                 $metathesekeys{'partorder'}=1;
                   12100:             }
                   12101:             if ($importedresponses) {
                   12102: # We had imported responses and need to rebuild responseorder
                   12103:                 $metaentry{':responseorder'}='';
                   12104:                 $metathesekeys{'responseorder'}=1;
                   12105:             }
                   12106:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12107:                 my $origid = $origfiletagids[$index+1];
                   12108:                 if ($origfiletagids[$index] eq 'part') {
                   12109: # Original part, part of the problem
                   12110:                     if ($importedparts) {
                   12111:                         $metaentry{':partorder'}.=','.$origid;
                   12112:                     }
                   12113:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12114:                     if ($importedparts) {
                   12115: # We have imported parts at this position
                   12116:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12117:                     }
                   12118:                     if ($importedresponses) {
                   12119: # We have imported responses at this position
                   12120:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   12121:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   12122:                         }
                   12123:                     }
                   12124:                 } else {
                   12125: # Original response item, part of the problem
                   12126:                     if ($importedresponses) {
                   12127:                         $metaentry{':responseorder'}.=','.$origid;
                   12128:                     }
                   12129:                 }
                   12130:             }
                   12131:             if ($importedparts) {
                   12132:                 $metaentry{':partorder'}=~s/^\,//;
                   12133:             }
                   12134:             if ($importedresponses) {
                   12135:                 $metaentry{':responseorder'}=~s/^\,//;
                   12136:             }
1.1070    www      12137:         }
                   12138: 
1.737     albertel 12139: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12140: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  12141: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 12142: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      12143: # this is the end of "was not already recently cached
1.71      www      12144:     }
1.599     albertel 12145:     return $metaentry{':'.$what};
1.261     albertel 12146: }
                   12147: 
1.488     albertel 12148: sub metadata_create_package_def {
1.483     albertel 12149:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12150:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12151:     if ($subp eq 'default') { next; }
                   12152:     
1.599     albertel 12153:     if (defined($metaentry{':packages'})) {
                   12154: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12155:     } else {
1.599     albertel 12156: 	$metaentry{':packages'}=$package;
1.483     albertel 12157:     }
                   12158:     my $value=$packagetab{$key};
                   12159:     my $unikey;
                   12160:     $unikey='parameter_0_'.$name;
1.599     albertel 12161:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12162:     $$metathesekeys{$unikey}=1;
1.599     albertel 12163:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12164: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12165:     }
1.599     albertel 12166:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12167: 	$metaentry{':'.$unikey}=
                   12168: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12169:     }
                   12170: }
                   12171: 
1.261     albertel 12172: sub metadata_generate_part0 {
                   12173:     my ($metadata,$metacache,$uri) = @_;
                   12174:     my %allnames;
1.737     albertel 12175:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12176: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12177: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12178: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12179: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12180: 	    $allnames{$name}=$part;
                   12181: 	  }
                   12182: 	}
                   12183:     }
                   12184:     foreach my $name (keys(%allnames)) {
                   12185:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12186:       my $key=":parameter_0_$name";
1.261     albertel 12187:       $$metacache{"$key.part"}='0';
                   12188:       $$metacache{"$key.name"}=$name;
1.428     albertel 12189:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12190: 					   $allnames{$name}.'_'.$name.
                   12191: 					   '.type'};
1.428     albertel 12192:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12193: 			     '.display'};
1.644     www      12194:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12195:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12196:       $$metacache{"$key.display"}=$olddis;
                   12197:     }
1.71      www      12198: }
                   12199: 
1.764     albertel 12200: # ------------------------------------------------------ Devalidate title cache
                   12201: 
                   12202: sub devalidate_title_cache {
                   12203:     my ($url)=@_;
                   12204:     if (!$env{'request.course.id'}) { return; }
                   12205:     my $symb=&symbread($url);
                   12206:     if (!$symb) { return; }
                   12207:     my $key=$env{'request.course.id'}."\0".$symb;
                   12208:     &devalidate_cache_new('title',$key);
                   12209: }
                   12210: 
1.1014    droeschl 12211: # ------------------------------------------------- Get the title of a course
                   12212: 
                   12213: sub current_course_title {
                   12214:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12215: }
1.301     www      12216: # ------------------------------------------------- Get the title of a resource
                   12217: 
                   12218: sub gettitle {
                   12219:     my $urlsymb=shift;
                   12220:     my $symb=&symbread($urlsymb);
1.534     albertel 12221:     if ($symb) {
1.620     albertel 12222: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12223: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12224: 	if (defined($cached)) { 
                   12225: 	    return $result;
                   12226: 	}
1.534     albertel 12227: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12228: 	my $title='';
1.907     albertel 12229: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12230: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12231: 	} else {
                   12232: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12233: 		    &GDBM_READER(),0640)) {
                   12234: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12235: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12236: 		untie(%bighash);
                   12237: 	    }
1.534     albertel 12238: 	}
                   12239: 	$title=~s/\&colon\;/\:/gs;
                   12240: 	if ($title) {
1.1159    www      12241: # Remember both $symb and $title for dynamic metadata
                   12242:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12243:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12244: # Cache this title and then return it
1.599     albertel 12245: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12246: 	}
                   12247: 	$urlsymb=$url;
                   12248:     }
                   12249:     my $title=&metadata($urlsymb,'title');
                   12250:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12251:     return $title;
1.301     www      12252: }
1.613     albertel 12253: 
1.614     albertel 12254: sub get_slot {
                   12255:     my ($which,$cnum,$cdom)=@_;
                   12256:     if (!$cnum || !$cdom) {
1.790     albertel 12257: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12258: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12259: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12260:     }
1.703     albertel 12261:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12262:     my %slotinfo;
                   12263:     if (exists($remembered{$key})) {
                   12264: 	$slotinfo{$which} = $remembered{$key};
                   12265:     } else {
                   12266: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12267: 	&Apache::lonhomework::showhash(%slotinfo);
                   12268: 	my ($tmp)=keys(%slotinfo);
                   12269: 	if ($tmp=~/^error:/) { return (); }
                   12270: 	$remembered{$key} = $slotinfo{$which};
                   12271:     }
1.616     albertel 12272:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12273: 	return %{$slotinfo{$which}};
                   12274:     }
                   12275:     return $slotinfo{$which};
1.614     albertel 12276: }
1.1150    raeburn  12277: 
                   12278: sub get_reservable_slots {
                   12279:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12280:     my $now = time;
                   12281:     my $reservable_info;
                   12282:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12283:     if (exists($remembered{$key})) {
                   12284:         $reservable_info = $remembered{$key};
                   12285:     } else {
                   12286:         my %resv;
                   12287:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12288:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12289:         $reservable_info = \%resv;
                   12290:         $remembered{$key} = $reservable_info;
                   12291:     }
                   12292:     return $reservable_info;
                   12293: }
                   12294: 
                   12295: sub get_course_slots {
                   12296:     my ($cnum,$cdom) = @_;
                   12297:     my $hashid=$cnum.':'.$cdom;
                   12298:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12299:     if (defined($cached)) {
                   12300:         if (ref($result) eq 'HASH') {
                   12301:             return %{$result};
                   12302:         }
                   12303:     } else {
                   12304:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12305:         my ($tmp) = keys(%slots);
                   12306:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12307:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12308:             return %slots;
                   12309:         }
                   12310:     }
                   12311:     return;
                   12312: }
                   12313: 
                   12314: sub devalidate_slots_cache {
                   12315:     my ($cnum,$cdom)=@_;
                   12316:     my $hashid=$cnum.':'.$cdom;
                   12317:     &devalidate_cache_new('allslots',$hashid);
                   12318: }
                   12319: 
1.1172.2.8  raeburn  12320: sub get_coursechange {
                   12321:     my ($cdom,$cnum) = @_;
                   12322:     if ($cdom eq '' || $cnum eq '') {
                   12323:         return unless ($env{'request.course.id'});
                   12324:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12325:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12326:     }
                   12327:     my $hashid=$cdom.'_'.$cnum;
                   12328:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12329:     if ((defined($cached)) && ($change ne '')) {
                   12330:         return $change;
                   12331:     } else {
                   12332:         my %crshash;
                   12333:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12334:         if ($crshash{'internal.contentchange'} eq '') {
                   12335:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12336:             if ($change eq '') {
                   12337:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12338:                 $change = $crshash{'internal.created'};
                   12339:             }
                   12340:         } else {
                   12341:             $change = $crshash{'internal.contentchange'};
                   12342:         }
                   12343:         my $cachetime = 600;
                   12344:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12345:     }
                   12346:     return $change;
                   12347: }
                   12348: 
                   12349: sub devalidate_coursechange_cache {
                   12350:     my ($cnum,$cdom)=@_;
                   12351:     my $hashid=$cnum.':'.$cdom;
                   12352:     &devalidate_cache_new('crschange',$hashid);
                   12353: }
                   12354: 
1.31      www      12355: # ------------------------------------------------- Update symbolic store links
                   12356: 
                   12357: sub symblist {
                   12358:     my ($mapname,%newhash)=@_;
1.438     www      12359:     $mapname=&deversion(&declutter($mapname));
1.31      www      12360:     my %hash;
1.620     albertel 12361:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12362:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12363:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12364: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12365: 		next if ($url eq 'last_known'
                   12366: 			 && $env{'form.no_update_last_known'});
                   12367: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12368: 						    $newhash{$url}->[1],
                   12369: 						    $newhash{$url}->[0]);
1.191     harris41 12370:             }
1.31      www      12371:             if (untie(%hash)) {
                   12372: 		return 'ok';
                   12373:             }
                   12374:         }
                   12375:     }
                   12376:     return 'error';
1.212     www      12377: }
                   12378: 
                   12379: # --------------------------------------------------------------- Verify a symb
                   12380: 
                   12381: sub symbverify {
1.1172.2.11  raeburn  12382:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12383:     my $thisfn=$thisurl;
1.439     www      12384:     $thisfn=&declutter($thisfn);
1.215     www      12385: # direct jump to resource in page or to a sequence - will construct own symbs
                   12386:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12387: # check URL part
1.409     www      12388:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12389: 
1.431     www      12390:     unless ($url eq $thisfn) { return 0; }
1.213     www      12391: 
1.216     www      12392:     $symb=&symbclean($symb);
1.510     www      12393:     $thisurl=&deversion($thisurl);
1.439     www      12394:     $thisfn=&deversion($thisfn);
1.213     www      12395: 
                   12396:     my %bighash;
                   12397:     my $okay=0;
1.431     www      12398: 
1.620     albertel 12399:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12400:                             &GDBM_READER(),0640)) {
1.1032    raeburn  12401:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12402:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  12403:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12404:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12405:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12406:             }
                   12407:         }
                   12408:         my $ids;
1.1172.2.122  raeburn  12409:         if ($map =~ m{^uploaded/.+\.page$}) {
                   12410:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13  raeburn  12411:         } else {
                   12412:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12413:         }
1.1102    raeburn  12414:         unless ($ids) {
1.1172.2.13  raeburn  12415:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  12416:             $ids=$bighash{$idkey};
1.216     www      12417:         }
                   12418:         if ($ids) {
                   12419: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  12420:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   12421:                 $symb =~ s/\?.+$//;
                   12422:             }
1.800     albertel 12423: 	    foreach my $id (split(/\,/,$ids)) {
                   12424: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12425:                if (
                   12426:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  12427:    eq $symb) {
1.1172.2.11  raeburn  12428:                    if (ref($encstate)) {
                   12429:                        $$encstate = $bighash{'encrypted_'.$id};
                   12430:                    }
1.1172.2.13  raeburn  12431:                    if (($env{'request.role.adv'}) ||
                   12432:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  12433:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  12434:                        $okay=1;
                   12435:                        last;
                   12436:                    }
                   12437:                }
                   12438:            }
1.216     www      12439:         }
1.213     www      12440: 	untie(%bighash);
                   12441:     }
                   12442:     return $okay;
1.31      www      12443: }
                   12444: 
1.210     www      12445: # --------------------------------------------------------------- Clean-up symb
                   12446: 
                   12447: sub symbclean {
                   12448:     my $symb=shift;
1.568     albertel 12449:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12450: # remove version from map
                   12451:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12452: 
1.210     www      12453: # remove version from URL
                   12454:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12455: 
1.507     www      12456: # remove wrapper
                   12457: 
1.510     www      12458:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12459:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12460:     return $symb;
1.409     www      12461: }
                   12462: 
                   12463: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12464: 
                   12465: sub encode_symb {
                   12466:     my ($map,$resid,$url)=@_;
                   12467:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12468: }
1.409     www      12469: 
                   12470: sub decode_symb {
1.568     albertel 12471:     my $symb=shift;
                   12472:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12473:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12474:     return (&fixversion($map),$resid,&fixversion($url));
                   12475: }
                   12476: 
                   12477: sub fixversion {
                   12478:     my $fn=shift;
1.609     banghart 12479:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12480:     my %bighash;
                   12481:     my $uri=&clutter($fn);
1.620     albertel 12482:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12483: # is this cached?
1.599     albertel 12484:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12485:     if (defined($cached)) { return $result; }
                   12486: # unfortunately not cached, or expired
1.620     albertel 12487:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12488: 	    &GDBM_READER(),0640)) {
                   12489:  	if ($bighash{'version_'.$uri}) {
                   12490:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12491:  	    unless (($version eq 'mostrecent') || 
                   12492: 		    ($version==&getversion($uri))) {
1.440     www      12493:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12494:  	    }
                   12495:  	}
                   12496:  	untie %bighash;
1.413     www      12497:     }
1.599     albertel 12498:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12499: }
                   12500: 
                   12501: sub deversion {
                   12502:     my $url=shift;
                   12503:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12504:     return $url;
1.210     www      12505: }
                   12506: 
1.31      www      12507: # ------------------------------------------------------ Return symb list entry
                   12508: 
                   12509: sub symbread {
1.1172.2.126  raeburn  12510:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128  raeburn  12511:         $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54  raeburn  12512:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128  raeburn  12513:     if (defined($env{$cache_str})) {
1.1172.2.126  raeburn  12514:         unless (ref($possibles) eq 'HASH') {
                   12515:             if ($ignorecachednull) {
                   12516:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12517:             } else {
                   12518:                 return $env{$cache_str};
                   12519:             }
1.1172.2.66  raeburn  12520:         }
                   12521:     }
1.242     www      12522: # no filename provided? try from environment
1.1172.2.54  raeburn  12523:     unless ($thisfn) {
1.620     albertel 12524:         if ($env{'request.symb'}) {
1.1172.2.128  raeburn  12525:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13  raeburn  12526:         }
                   12527:         $thisfn=$env{'request.filename'};
1.44      www      12528:     }
1.569     albertel 12529:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12530: # is that filename actually a symb? Verify, clean, and return
                   12531:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12532: 	if (&symbverify($thisfn,$1)) {
1.1172.2.128  raeburn  12533: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12534: 	}
1.242     www      12535:     }
1.44      www      12536:     $thisfn=declutter($thisfn);
1.31      www      12537:     my %hash;
1.37      www      12538:     my %bighash;
                   12539:     my $syval='';
1.620     albertel 12540:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12541:         my $targetfn = $thisfn;
1.609     banghart 12542:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12543:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12544:         }
1.687     albertel 12545: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12546: 	    $targetfn=$1;
                   12547: 	}
1.1172.2.128  raeburn  12548:         unless ($ignoresymbdb) {
1.1172.2.126  raeburn  12549:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   12550:                           &GDBM_READER(),0640)) {
                   12551: 	        $syval=$hash{$targetfn};
                   12552:                 untie(%hash);
                   12553:             }
1.1172.2.128  raeburn  12554:             if ($syval && $checkforblock) {
                   12555:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126  raeburn  12556:                 if (@blockers) {
                   12557:                     $syval='';
                   12558:                 }
                   12559:             }
1.37      www      12560:         }
                   12561: # ---------------------------------------------------------- There was an entry
                   12562:         if ($syval) {
1.601     albertel 12563: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12564: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12565: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12566: 		    #return $env{$cache_str}='';
1.601     albertel 12567: 		#}    
                   12568: 		#$syval.=$1;
                   12569: 	    #}
1.37      www      12570:         } else {
                   12571: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12572:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12573:                             &GDBM_READER(),0640)) {
1.37      www      12574: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12575:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12576:               unless ($ids) { 
                   12577:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12578:               }
                   12579:               unless ($ids) {
                   12580: # alias?
                   12581: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12582:               }
1.37      www      12583:               if ($ids) {
                   12584: # ------------------------------------------------------------------- Has ID(s)
                   12585:                  my @possibilities=split(/\,/,$ids);
1.39      www      12586:                  if ($#possibilities==0) {
                   12587: # ----------------------------------------------- There is only one possibility
1.37      www      12588: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12589: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12590: 						    $resid,$thisfn);
1.1172.2.66  raeburn  12591:                      if (ref($possibles) eq 'HASH') {
1.1172.2.126  raeburn  12592:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   12593:                              $possibles->{$syval} = 1;
                   12594:                          }
1.1172.2.66  raeburn  12595:                      }
                   12596:                      if ($checkforblock) {
1.1172.2.126  raeburn  12597:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127  raeburn  12598:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126  raeburn  12599:                              if (@blockers) {
                   12600:                                  $syval = '';
                   12601:                                  untie(%bighash);
                   12602:                                  return $env{$cache_str}='';
                   12603:                              }
1.1172.2.66  raeburn  12604:                          }
                   12605:                      }
                   12606:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      12607: # ------------------------------------------ There is more than one possibility
                   12608:                      my $realpossible=0;
1.800     albertel 12609:                      foreach my $id (@possibilities) {
                   12610: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  12611:                          my $canaccess;
                   12612:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12613:                              $canaccess = 1;
                   12614:                          } else {
                   12615:                              $canaccess = &allowed('bre',$file);
                   12616:                          }
                   12617:                          if ($canaccess) {
                   12618:          		     my ($mapid,$resid)=split(/\./,$id);
                   12619:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12620:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12621:                                                              $resid,$thisfn);
1.1172.2.126  raeburn  12622:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127  raeburn  12623:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66  raeburn  12624:                                  if ($checkforblock) {
1.1172.2.127  raeburn  12625:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126  raeburn  12626:                                      if (@blockers > 0) {
                   12627:                                          $syval = '';
                   12628:                                      } else {
1.1172.2.66  raeburn  12629:                                          $syval = $poss_syval;
                   12630:                                          $realpossible++;
                   12631:                                      }
                   12632:                                  } else {
                   12633:                                      $syval = $poss_syval;
                   12634:                                      $realpossible++;
                   12635:                                  }
1.1172.2.126  raeburn  12636:                                  if ($syval) {
                   12637:                                      if (ref($possibles) eq 'HASH') {
                   12638:                                          $possibles->{$syval} = 1;
                   12639:                                      }
                   12640:                                  }
1.1172.2.66  raeburn  12641:                              }
1.39      www      12642: 			 }
1.191     harris41 12643:                      }
1.39      www      12644: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12645:                  } else {
                   12646:                      $syval='';
1.37      www      12647:                  }
                   12648: 	      }
1.1172.2.66  raeburn  12649:               untie(%bighash);
1.481     raeburn  12650:            }
1.31      www      12651:         }
1.62      www      12652:         if ($syval) {
1.1172.2.128  raeburn  12653: 	    return $env{$cache_str}=$syval;
1.62      www      12654:         }
1.31      www      12655:     }
1.949     raeburn  12656:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12657:     return $env{$cache_str}='';
1.31      www      12658: }
                   12659: 
                   12660: # ---------------------------------------------------------- Return random seed
                   12661: 
1.32      www      12662: sub numval {
                   12663:     my $txt=shift;
                   12664:     $txt=~tr/A-J/0-9/;
                   12665:     $txt=~tr/a-j/0-9/;
                   12666:     $txt=~tr/K-T/0-9/;
                   12667:     $txt=~tr/k-t/0-9/;
                   12668:     $txt=~tr/U-Z/0-5/;
                   12669:     $txt=~tr/u-z/0-5/;
                   12670:     $txt=~s/\D//g;
1.564     albertel 12671:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12672:     return int($txt);
1.368     albertel 12673: }
                   12674: 
1.484     albertel 12675: sub numval2 {
                   12676:     my $txt=shift;
                   12677:     $txt=~tr/A-J/0-9/;
                   12678:     $txt=~tr/a-j/0-9/;
                   12679:     $txt=~tr/K-T/0-9/;
                   12680:     $txt=~tr/k-t/0-9/;
                   12681:     $txt=~tr/U-Z/0-5/;
                   12682:     $txt=~tr/u-z/0-5/;
                   12683:     $txt=~s/\D//g;
                   12684:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12685:     my $total;
                   12686:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12687:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12688:     return int($total);
                   12689: }
                   12690: 
1.575     albertel 12691: sub numval3 {
                   12692:     use integer;
                   12693:     my $txt=shift;
                   12694:     $txt=~tr/A-J/0-9/;
                   12695:     $txt=~tr/a-j/0-9/;
                   12696:     $txt=~tr/K-T/0-9/;
                   12697:     $txt=~tr/k-t/0-9/;
                   12698:     $txt=~tr/U-Z/0-5/;
                   12699:     $txt=~tr/u-z/0-5/;
                   12700:     $txt=~s/\D//g;
                   12701:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12702:     my $total;
                   12703:     foreach my $val (@txts) { $total+=$val; }
                   12704:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12705:     return $total;
                   12706: }
                   12707: 
1.675     albertel 12708: sub digest {
                   12709:     my ($data)=@_;
                   12710:     my $digest=&Digest::MD5::md5($data);
                   12711:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12712:     my ($e,$f);
                   12713:     {
                   12714:         use integer;
                   12715:         $e=($a+$b);
                   12716:         $f=($c+$d);
                   12717:         if ($_64bit) {
                   12718:             $e=(($e<<32)>>32);
                   12719:             $f=(($f<<32)>>32);
                   12720:         }
                   12721:     }
                   12722:     if (wantarray) {
                   12723: 	return ($e,$f);
                   12724:     } else {
                   12725: 	my $g;
                   12726: 	{
                   12727: 	    use integer;
                   12728: 	    $g=($e+$f);
                   12729: 	    if ($_64bit) {
                   12730: 		$g=(($g<<32)>>32);
                   12731: 	    }
                   12732: 	}
                   12733: 	return $g;
                   12734:     }
                   12735: }
                   12736: 
1.368     albertel 12737: sub latest_rnd_algorithm_id {
1.675     albertel 12738:     return '64bit5';
1.366     albertel 12739: }
1.32      www      12740: 
1.503     albertel 12741: sub get_rand_alg {
                   12742:     my ($courseid)=@_;
1.790     albertel 12743:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12744:     if ($courseid) {
1.620     albertel 12745: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12746:     }
                   12747:     return &latest_rnd_algorithm_id();
                   12748: }
                   12749: 
1.562     albertel 12750: sub validCODE {
                   12751:     my ($CODE)=@_;
                   12752:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12753:     return 0;
                   12754: }
                   12755: 
1.491     albertel 12756: sub getCODE {
1.620     albertel 12757:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12758:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12759: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12760: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12761: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12762:     }
                   12763:     return undef;
                   12764: }
1.1133    foxr     12765: #
                   12766: #  Determines the random seed for a specific context:
                   12767: #
                   12768: # parameters:
                   12769: #   symb      - in course context the symb for the seed.
                   12770: #   course_id - The course id of the form domain_coursenum.
                   12771: #   domain    - Domain for the user.
                   12772: #   course    - Course for the user.
                   12773: #   cenv      - environment of the course.
                   12774: #
                   12775: # NOTE:
                   12776: #   All parameters are picked out of the environment if missing
                   12777: #   or not defined.
                   12778: #   If a symb cannot be determined the current time is used instead.
                   12779: #
                   12780: #  For a given well defined symb, courside, domain, username,
                   12781: #  and course environment, the seed is reproducible.
                   12782: #
1.31      www      12783: sub rndseed {
1.1133    foxr     12784:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12785:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12786:     if (!defined($symb)) {
1.366     albertel 12787: 	unless ($symb=$wsymb) { return time; }
                   12788:     }
1.1146    foxr     12789:     if (!defined $courseid) { 
                   12790: 	$courseid=$wcourseid; 
                   12791:     }
                   12792:     if (!defined $domain) { $domain=$wdomain; }
                   12793:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12794: 
                   12795:     my $which;
                   12796:     if (defined($cenv->{'rndseed'})) {
                   12797: 	$which = $cenv->{'rndseed'};
                   12798:     } else {
                   12799: 	$which =&get_rand_alg($courseid);
                   12800:     }
1.491     albertel 12801:     if (defined(&getCODE())) {
1.675     albertel 12802: 	if ($which eq '64bit5') {
                   12803: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12804: 	} elsif ($which eq '64bit4') {
1.575     albertel 12805: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12806: 	} else {
                   12807: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12808: 	}
1.675     albertel 12809:     } elsif ($which eq '64bit5') {
                   12810: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12811:     } elsif ($which eq '64bit4') {
                   12812: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12813:     } elsif ($which eq '64bit3') {
                   12814: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12815:     } elsif ($which eq '64bit2') {
                   12816: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12817:     } elsif ($which eq '64bit') {
                   12818: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12819:     }
                   12820:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12821: }
                   12822: 
                   12823: sub rndseed_32bit {
                   12824:     my ($symb,$courseid,$domain,$username)=@_;
                   12825:     {
                   12826: 	use integer;
                   12827: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12828: 	my $symbseed=numval($symb) << 22;
                   12829: 	my $namechck=unpack("%32C*",$username) << 17;
                   12830: 	my $nameseed=numval($username) << 12;
                   12831: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12832: 	my $courseseed=unpack("%32C*",$courseid);
                   12833: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12834: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12835: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12836: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12837: 	return $num;
                   12838:     }
                   12839: }
                   12840: 
                   12841: sub rndseed_64bit {
                   12842:     my ($symb,$courseid,$domain,$username)=@_;
                   12843:     {
                   12844: 	use integer;
                   12845: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12846: 	my $symbseed=numval($symb) << 10;
                   12847: 	my $namechck=unpack("%32S*",$username);
                   12848: 	
                   12849: 	my $nameseed=numval($username) << 21;
                   12850: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12851: 	my $courseseed=unpack("%32S*",$courseid);
                   12852: 	
                   12853: 	my $num1=$symbchck+$symbseed+$namechck;
                   12854: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12855: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12856: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12857: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12858: 	return "$num1,$num2";
1.155     albertel 12859:     }
1.366     albertel 12860: }
                   12861: 
1.443     albertel 12862: sub rndseed_64bit2 {
                   12863:     my ($symb,$courseid,$domain,$username)=@_;
                   12864:     {
                   12865: 	use integer;
                   12866: 	# strings need to be an even # of cahracters long, it it is odd the
                   12867:         # last characters gets thrown away
                   12868: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12869: 	my $symbseed=numval($symb) << 10;
                   12870: 	my $namechck=unpack("%32S*",$username.' ');
                   12871: 	
                   12872: 	my $nameseed=numval($username) << 21;
1.501     albertel 12873: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12874: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12875: 	
                   12876: 	my $num1=$symbchck+$symbseed+$namechck;
                   12877: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12878: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12879: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12880: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12881: 	return "$num1,$num2";
                   12882:     }
                   12883: }
                   12884: 
                   12885: sub rndseed_64bit3 {
                   12886:     my ($symb,$courseid,$domain,$username)=@_;
                   12887:     {
                   12888: 	use integer;
                   12889: 	# strings need to be an even # of cahracters long, it it is odd the
                   12890:         # last characters gets thrown away
                   12891: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12892: 	my $symbseed=numval2($symb) << 10;
                   12893: 	my $namechck=unpack("%32S*",$username.' ');
                   12894: 	
                   12895: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12896: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12897: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12898: 	
                   12899: 	my $num1=$symbchck+$symbseed+$namechck;
                   12900: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12901: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12902: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12903: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12904: 	
1.503     albertel 12905: 	return "$num1:$num2";
1.443     albertel 12906:     }
                   12907: }
                   12908: 
1.575     albertel 12909: sub rndseed_64bit4 {
                   12910:     my ($symb,$courseid,$domain,$username)=@_;
                   12911:     {
                   12912: 	use integer;
                   12913: 	# strings need to be an even # of cahracters long, it it is odd the
                   12914:         # last characters gets thrown away
                   12915: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12916: 	my $symbseed=numval3($symb) << 10;
                   12917: 	my $namechck=unpack("%32S*",$username.' ');
                   12918: 	
                   12919: 	my $nameseed=numval3($username) << 21;
                   12920: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12921: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12922: 	
                   12923: 	my $num1=$symbchck+$symbseed+$namechck;
                   12924: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12925: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12926: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12927: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12928: 	
1.575     albertel 12929: 	return "$num1:$num2";
                   12930:     }
                   12931: }
                   12932: 
1.675     albertel 12933: sub rndseed_64bit5 {
                   12934:     my ($symb,$courseid,$domain,$username)=@_;
                   12935:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12936:     return "$num1:$num2";
                   12937: }
                   12938: 
1.366     albertel 12939: sub rndseed_CODE_64bit {
                   12940:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12941:     {
1.366     albertel 12942: 	use integer;
1.443     albertel 12943: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12944: 	my $symbseed=numval2($symb);
1.491     albertel 12945: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12946: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12947: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12948: 	my $num1=$symbseed+$CODEchck;
                   12949: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12950: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12951: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12952: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12953: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12954: 	return "$num1:$num2";
1.366     albertel 12955:     }
                   12956: }
                   12957: 
1.575     albertel 12958: sub rndseed_CODE_64bit4 {
                   12959:     my ($symb,$courseid,$domain,$username)=@_;
                   12960:     {
                   12961: 	use integer;
                   12962: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12963: 	my $symbseed=numval3($symb);
                   12964: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12965: 	my $CODEseed=numval3(&getCODE());
                   12966: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12967: 	my $num1=$symbseed+$CODEchck;
                   12968: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12969: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12970: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12971: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12972: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12973: 	return "$num1:$num2";
                   12974:     }
                   12975: }
                   12976: 
1.675     albertel 12977: sub rndseed_CODE_64bit5 {
                   12978:     my ($symb,$courseid,$domain,$username)=@_;
                   12979:     my $code = &getCODE();
                   12980:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12981:     return "$num1:$num2";
                   12982: }
                   12983: 
1.366     albertel 12984: sub setup_random_from_rndseed {
                   12985:     my ($rndseed)=@_;
1.503     albertel 12986:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  12987: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12988:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12989:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12990:         } else {
                   12991:             &Math::Random::random_set_seed($num1,$num2);
                   12992:         }
1.366     albertel 12993:     } else {
                   12994: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12995:     }
1.36      albertel 12996: }
                   12997: 
1.474     albertel 12998: sub latest_receipt_algorithm_id {
1.835     albertel 12999:     return 'receipt3';
1.474     albertel 13000: }
                   13001: 
1.480     www      13002: sub recunique {
                   13003:     my $fucourseid=shift;
                   13004:     my $unique;
1.835     albertel 13005:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13006: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13007: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13008:     } else {
                   13009: 	$unique=$perlvar{'lonReceipt'};
                   13010:     }
                   13011:     return unpack("%32C*",$unique);
                   13012: }
                   13013: 
                   13014: sub recprefix {
                   13015:     my $fucourseid=shift;
                   13016:     my $prefix;
1.835     albertel 13017:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13018: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13019: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13020:     } else {
                   13021: 	$prefix=$perlvar{'lonHostID'};
                   13022:     }
                   13023:     return unpack("%32C*",$prefix);
                   13024: }
                   13025: 
1.76      www      13026: sub ireceipt {
1.474     albertel 13027:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13028: 
                   13029:     my $return =&recprefix($fucourseid).'-';
                   13030: 
                   13031:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13032: 	$env{'request.state'} eq 'construct') {
                   13033: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13034: 	return $return;
                   13035:     }
                   13036: 
1.76      www      13037:     my $cuname=unpack("%32C*",$funame);
                   13038:     my $cudom=unpack("%32C*",$fudom);
                   13039:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13040:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13041:     my $cunique=&recunique($fucourseid);
1.474     albertel 13042:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13043:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13044: 
1.790     albertel 13045: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13046: 			       
                   13047: 	$return.= ($cunique%$cuname+
                   13048: 		   $cunique%$cudom+
                   13049: 		   $cusymb%$cuname+
                   13050: 		   $cusymb%$cudom+
                   13051: 		   $cucourseid%$cuname+
                   13052: 		   $cucourseid%$cudom+
                   13053: 		   $cpart%$cuname+
                   13054: 		   $cpart%$cudom);
                   13055:     } else {
                   13056: 	$return.= ($cunique%$cuname+
                   13057: 		   $cunique%$cudom+
                   13058: 		   $cusymb%$cuname+
                   13059: 		   $cusymb%$cudom+
                   13060: 		   $cucourseid%$cuname+
                   13061: 		   $cucourseid%$cudom);
                   13062:     }
                   13063:     return $return;
1.76      www      13064: }
                   13065: 
                   13066: sub receipt {
1.474     albertel 13067:     my ($part)=@_;
1.790     albertel 13068:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13069:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13070: }
1.260     ng       13071: 
1.790     albertel 13072: sub whichuser {
                   13073:     my ($passedsymb)=@_;
                   13074:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13075:     if (defined($env{'form.grade_symb'})) {
                   13076: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13077: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13078: 	if (!$allowed &&
                   13079: 	    exists($env{'request.course.sec'}) &&
                   13080: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13081: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13082: 			      '/'.$env{'request.course.sec'});
                   13083: 	}
                   13084: 	if ($allowed) {
                   13085: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13086: 	    $courseid=$tmp_courseid;
                   13087: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13088: 	    ($name)=&get_env_multiple('form.grade_username');
                   13089: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13090: 	}
                   13091:     }
                   13092:     if (!$passedsymb) {
                   13093: 	$symb=&symbread();
                   13094:     } else {
                   13095: 	$symb=$passedsymb;
                   13096:     }
                   13097:     $courseid=$env{'request.course.id'};
                   13098:     $domain=$env{'user.domain'};
                   13099:     $name=$env{'user.name'};
                   13100:     if ($name eq 'public' && $domain eq 'public') {
                   13101: 	if (!defined($env{'form.username'})) {
                   13102: 	    $env{'form.username'}.=time.rand(10000000);
                   13103: 	}
                   13104: 	$name.=$env{'form.username'};
                   13105:     }
                   13106:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13107: 
                   13108: }
                   13109: 
1.36      albertel 13110: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13111: # returns either the contents of the file or 
                   13112: # -1 if the file doesn't exist
1.481     raeburn  13113: #
                   13114: # if the target is a file that was uploaded via DOCS, 
                   13115: # a check will be made to see if a current copy exists on the local server,
                   13116: # if it does this will be served, otherwise a copy will be retrieved from
                   13117: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13118: # the local server.   
1.472     albertel 13119: 
1.36      albertel 13120: sub getfile {
1.538     albertel 13121:     my ($file) = @_;
1.609     banghart 13122:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13123:     &repcopy($file);
                   13124:     return &readfile($file);
                   13125: }
                   13126: 
                   13127: sub repcopy_userfile {
                   13128:     my ($file)=@_;
1.1142    raeburn  13129:     my $londocroot = $perlvar{'lonDocRoot'};
                   13130:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13131:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13132:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13133: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13134:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13135:     if (-e "$file") {
1.828     www      13136: # we already have a local copy, check it out
1.538     albertel 13137: 	my @fileinfo = stat($file);
1.828     www      13138: 	my $rtncode;
                   13139: 	my $info;
1.538     albertel 13140: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13141: 	if ($lwpresp ne 'ok') {
1.828     www      13142: # there is no such file anymore, even though we had a local copy
1.482     albertel 13143: 	    if ($rtncode eq '404') {
1.538     albertel 13144: 		unlink($file);
1.482     albertel 13145: 	    }
                   13146: 	    return -1;
                   13147: 	}
                   13148: 	if ($info < $fileinfo[9]) {
1.828     www      13149: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13150: 	    return 'ok';
1.828     www      13151: 	} else {
                   13152: # the file is outdated, get rid of it
                   13153: 	    unlink($file);
1.482     albertel 13154: 	}
1.828     www      13155:     }
                   13156: # one way or the other, at this point, we don't have the file
                   13157: # construct the correct path for the file
                   13158:     my @parts = ($cdom,$cnum); 
                   13159:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13160: 	push @parts, split(/\//,$1);
                   13161:     }
                   13162:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13163:     foreach my $part (@parts) {
                   13164: 	$path .= '/'.$part;
                   13165: 	if (!-e $path) {
                   13166: 	    mkdir($path,0770);
1.482     albertel 13167: 	}
                   13168:     }
1.828     www      13169: # now the path exists for sure
                   13170: # get a user agent
                   13171:     my $ua=new LWP::UserAgent;
                   13172:     my $transferfile=$file.'.in.transfer';
                   13173: # FIXME: this should flock
                   13174:     if (-e $transferfile) { return 'ok'; }
                   13175:     my $request;
                   13176:     $uri=~s/^\///;
1.980     raeburn  13177:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13178:     my $hostname = &hostname($homeserver);
1.980     raeburn  13179:     my $protocol = $protocol{$homeserver};
                   13180:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13181:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      13182:     my $response=$ua->request($request,$transferfile);
                   13183: # did it work?
                   13184:     if ($response->is_error()) {
                   13185: 	unlink($transferfile);
                   13186: 	&logthis("Userfile repcopy failed for $uri");
                   13187: 	return -1;
                   13188:     }
                   13189: # worked, rename the transfer file
                   13190:     rename($transferfile,$file);
1.607     raeburn  13191:     return 'ok';
1.481     raeburn  13192: }
                   13193: 
1.517     albertel 13194: sub tokenwrapper {
                   13195:     my $uri=shift;
1.980     raeburn  13196:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13197:     $uri=~s|^/||;
1.620     albertel 13198:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13199:     my $token=$1;
1.552     albertel 13200:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13201:     if ($udom && $uname && $file) {
                   13202: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13203:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13204:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.120  raeburn  13205:         my $hostname = &hostname($homeserver);
1.980     raeburn  13206:         my $protocol = $protocol{$homeserver};
                   13207:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13208:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13209:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13210:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13211:     } else {
                   13212:         return '/adm/notfound.html';
                   13213:     }
                   13214: }
                   13215: 
1.828     www      13216: # call with reqtype HEAD: get last modification time
                   13217: # call with reqtype GET: get the file contents
                   13218: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13219: #
1.481     raeburn  13220: sub getuploaded {
                   13221:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13222:     $uri=~s/^\///;
1.980     raeburn  13223:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13224:     my $hostname = &hostname($homeserver);
1.980     raeburn  13225:     my $protocol = $protocol{$homeserver};
                   13226:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13227:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13228:     my $ua=new LWP::UserAgent;
                   13229:     my $request=new HTTP::Request($reqtype,$uri);
                   13230:     my $response=$ua->request($request);
                   13231:     $$rtncode = $response->code;
1.482     albertel 13232:     if (! $response->is_success()) {
                   13233: 	return 'failed';
                   13234:     }      
                   13235:     if ($reqtype eq 'HEAD') {
1.486     www      13236: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13237:     } elsif ($reqtype eq 'GET') {
                   13238: 	$$info = $response->content;
1.472     albertel 13239:     }
1.482     albertel 13240:     return 'ok';
1.36      albertel 13241: }
                   13242: 
1.481     raeburn  13243: sub readfile {
                   13244:     my $file = shift;
                   13245:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13246:     my $fh;
1.1172.2.96  raeburn  13247:     open($fh,"<",$file);
1.481     raeburn  13248:     my $a='';
1.800     albertel 13249:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13250:     return $a;
                   13251: }
                   13252: 
1.36      albertel 13253: sub filelocation {
1.590     banghart 13254:     my ($dir,$file) = @_;
                   13255:     my $location;
                   13256:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13257: 
                   13258:     if ($file =~ m-^/adm/-) {
                   13259: 	$file=~s-^/adm/wrapper/-/-;
                   13260: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13261:     }
1.882     albertel 13262: 
1.1139    www      13263:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13264:         $location = $file;
1.609     banghart 13265:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13266:         my ($udom,$uname,$filename)=
1.811     albertel 13267:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13268:         my $home=&homeserver($uname,$udom);
                   13269:         my $is_me=0;
                   13270:         my @ids=&current_machine_ids();
                   13271:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13272:         if ($is_me) {
1.1117    foxr     13273:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13274:         } else {
                   13275:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13276:   	      $udom.'/'.$uname.'/'.$filename;
                   13277:         }
1.882     albertel 13278:     } elsif ($file =~ m-^/adm/-) {
                   13279: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13280:     } else {
                   13281:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13282:         $file=~s:^/(res|priv)/:/:;
                   13283:         my $space=$1;
1.590     banghart 13284:         if ( !( $file =~ m:^/:) ) {
                   13285:             $location = $dir. '/'.$file;
                   13286:         } else {
1.1142    raeburn  13287:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13288:         }
1.59      albertel 13289:     }
1.590     banghart 13290:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13291:     while ($location=~m{/\.\./}) {
                   13292: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13293: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13294: 	} else {
                   13295: 	    $location=~ s{/\.\./}{/}g;
                   13296: 	}
                   13297:     } #remove dir/..
1.590     banghart 13298:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13299:     return $location;
1.46      www      13300: }
1.36      albertel 13301: 
1.46      www      13302: sub hreflocation {
                   13303:     my ($dir,$file)=@_;
1.980     raeburn  13304:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13305: 	$file=filelocation($dir,$file);
1.700     albertel 13306:     } elsif ($file=~m-^/adm/-) {
                   13307: 	$file=~s-^/adm/wrapper/-/-;
                   13308: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13309:     }
                   13310:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13311: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13312:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13313: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13314: 	        {/uploaded/$1/$2/}x;
1.46      www      13315:     }
1.913     albertel 13316:     if ($file=~ m{^/userfiles/}) {
                   13317: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13318:     }
1.462     albertel 13319:     return $file;
1.465     albertel 13320: }
                   13321: 
1.1139    www      13322: 
                   13323: 
                   13324: 
                   13325: 
1.465     albertel 13326: sub current_machine_domains {
1.853     albertel 13327:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13328: }
                   13329: 
                   13330: sub machine_domains {
                   13331:     my ($hostname) = @_;
1.465     albertel 13332:     my @domains;
1.838     albertel 13333:     my %hostname = &all_hostnames();
1.465     albertel 13334:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13335: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13336: 	if ($hostname eq $name) {
1.844     albertel 13337: 	    push(@domains,&host_domain($id));
1.465     albertel 13338: 	}
                   13339:     }
                   13340:     return @domains;
                   13341: }
                   13342: 
                   13343: sub current_machine_ids {
1.853     albertel 13344:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13345: }
                   13346: 
                   13347: sub machine_ids {
                   13348:     my ($hostname) = @_;
                   13349:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13350:     my @ids;
1.888     albertel 13351:     my %name_to_host = &all_names();
1.889     albertel 13352:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13353: 	return @{ $name_to_host{$hostname} };
                   13354:     }
                   13355:     return;
1.31      www      13356: }
                   13357: 
1.824     raeburn  13358: sub additional_machine_domains {
                   13359:     my @domains;
1.1172.2.96  raeburn  13360:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13361:     while( my $line = <$fh>) {
                   13362:         $line =~ s/\s//g;
                   13363:         push(@domains,$line);
                   13364:     }
                   13365:     return @domains;
                   13366: }
                   13367: 
                   13368: sub default_login_domain {
                   13369:     my $domain = $perlvar{'lonDefDomain'};
                   13370:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13371:     foreach my $posdom (&current_machine_domains(),
                   13372:                         &additional_machine_domains()) {
                   13373:         if (lc($posdom) eq lc($testdomain)) {
                   13374:             $domain=$posdom;
                   13375:             last;
                   13376:         }
                   13377:     }
                   13378:     return $domain;
                   13379: }
                   13380: 
1.1172.2.106  raeburn  13381: sub shared_institution {
1.1172.2.136  raeburn  13382:     my ($dom,$lonhost) = @_;
                   13383:     if ($lonhost eq '') {
                   13384:         $lonhost = $perlvar{'lonHostID'};
                   13385:     }
1.1172.2.106  raeburn  13386:     my $same_intdom;
1.1172.2.136  raeburn  13387:     my $hostintdom = &internet_dom($lonhost);
1.1172.2.106  raeburn  13388:     if ($hostintdom ne '') {
                   13389:         my %iphost = &get_iphost();
                   13390:         my $primary_id = &domain($dom,'primary');
                   13391:         my $primary_ip = &get_host_ip($primary_id);
                   13392:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   13393:             foreach my $id (@{$iphost{$primary_ip}}) {
                   13394:                 my $intdom = &internet_dom($id);
                   13395:                 if ($intdom eq $hostintdom) {
                   13396:                     $same_intdom = 1;
                   13397:                     last;
                   13398:                 }
                   13399:             }
                   13400:         }
                   13401:     }
                   13402:     return $same_intdom;
                   13403: }
                   13404: 
1.1172.2.120  raeburn  13405: sub uses_sts {
                   13406:     my ($ignore_cache) = @_;
                   13407:     my $lonhost = $perlvar{'lonHostID'};
                   13408:     my $hostname = &hostname($lonhost);
                   13409:     my $sts_on;
                   13410:     if ($protocol{$lonhost} eq 'https') {
                   13411:         my $cachetime = 12*3600;
                   13412:         if (!$ignore_cache) {
                   13413:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   13414:             if (defined($cached)) {
                   13415:                 return $sts_on;
                   13416:             }
                   13417:         }
1.1172.2.121  raeburn  13418:         my $ua=new LWP::UserAgent;
1.1172.2.120  raeburn  13419:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   13420:         my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121  raeburn  13421:         my $response=$ua->request($request);
1.1172.2.120  raeburn  13422:         if ($response->is_success) {
                   13423:             my $has_sts = $response->header('Strict-Transport-Security');
                   13424:             if ($has_sts eq '') {
                   13425:                 $sts_on = 0;
                   13426:             } else {
                   13427:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   13428:                     my $maxage = $1;
                   13429:                     if ($maxage) {
                   13430:                         $sts_on = 1;
                   13431:                     } else {
                   13432:                         $sts_on = 0;
                   13433:                     }
                   13434:                 } else {
                   13435:                     $sts_on = 0;
                   13436:                 }
                   13437:             }
                   13438:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   13439:         }
                   13440:     }
                   13441:     return;
                   13442: }
                   13443: 
1.1172.2.134  raeburn  13444: sub get_requestor_ip {
                   13445:     my ($r,$nolookup,$noproxy) = @_;
                   13446:     my $from_ip;
                   13447:     if (ref($r)) {
                   13448:         $from_ip = $r->get_remote_host($nolookup);
                   13449:     } else {
                   13450:         $from_ip = $ENV{'REMOTE_ADDR'};
                   13451:     }
                   13452:     return $from_ip;
                   13453: }
                   13454: 
1.31      www      13455: # ------------------------------------------------------------- Declutters URLs
                   13456: 
                   13457: sub declutter {
                   13458:     my $thisfn=shift;
1.569     albertel 13459:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  13460:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13461:         $thisfn=~s{^/home/httpd/html}{};
                   13462:     }
1.31      www      13463:     $thisfn=~s/^\///;
1.697     albertel 13464:     $thisfn=~s|^adm/wrapper/||;
                   13465:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13466:     $thisfn=~s/^res\///;
1.1172    bisitz   13467:     $thisfn=~s/^priv\///;
1.1032    raeburn  13468:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13469:         $thisfn=~s/\?.+$//;
                   13470:     }
1.268     www      13471:     return $thisfn;
                   13472: }
                   13473: 
                   13474: # ------------------------------------------------------------- Clutter up URLs
                   13475: 
                   13476: sub clutter {
                   13477:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13478:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13479: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13480:        $thisfn='/res'.$thisfn; 
                   13481:     }
1.1031    raeburn  13482:     if ($thisfn !~m|^/adm|) {
                   13483: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13484: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13485: 	} else {
                   13486: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13487: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13488: 	    if ($embstyle eq 'ssi'
                   13489: 		|| ($embstyle eq 'hdn')
                   13490: 		|| ($embstyle eq 'rat')
                   13491: 		|| ($embstyle eq 'prv')
                   13492: 		|| ($embstyle eq 'ign')) {
                   13493: 		#do nothing with these
                   13494: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13495: 		|| ($embstyle eq 'emb')
                   13496: 		|| ($embstyle eq 'wrp')) {
                   13497: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13498: 	    } elsif ($embstyle eq 'unk'
                   13499: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13500: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13501: 	    } else {
1.718     www      13502: #		&logthis("Got a blank emb style");
1.695     albertel 13503: 	    }
1.694     albertel 13504: 	}
                   13505:     }
1.31      www      13506:     return $thisfn;
1.12      www      13507: }
                   13508: 
1.787     albertel 13509: sub clutter_with_no_wrapper {
                   13510:     my $uri = &clutter(shift);
                   13511:     if ($uri =~ m-^/adm/-) {
                   13512: 	$uri =~ s-^/adm/wrapper/-/-;
                   13513: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13514:     }
                   13515:     return $uri;
                   13516: }
                   13517: 
1.557     albertel 13518: sub freeze_escape {
                   13519:     my ($value)=@_;
                   13520:     if (ref($value)) {
                   13521: 	$value=&nfreeze($value);
                   13522: 	return '__FROZEN__'.&escape($value);
                   13523:     }
                   13524:     return &escape($value);
                   13525: }
                   13526: 
1.11      www      13527: 
1.557     albertel 13528: sub thaw_unescape {
                   13529:     my ($value)=@_;
                   13530:     if ($value =~ /^__FROZEN__/) {
                   13531: 	substr($value,0,10,undef);
                   13532: 	$value=&unescape($value);
                   13533: 	return &thaw($value);
                   13534:     }
                   13535:     return &unescape($value);
                   13536: }
                   13537: 
1.436     albertel 13538: sub correct_line_ends {
                   13539:     my ($result)=@_;
                   13540:     $$result =~s/\r\n/\n/mg;
                   13541:     $$result =~s/\r/\n/mg;
1.415     albertel 13542: }
1.1       albertel 13543: # ================================================================ Main Program
                   13544: 
1.184     www      13545: sub goodbye {
1.204     albertel 13546:    &logthis("Starting Shut down");
1.443     albertel 13547: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13548:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13549: #converted
1.599     albertel 13550: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13551:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13552: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13553: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13554: #1.1 only
1.870     albertel 13555: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13556: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13557: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13558: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13559:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13560:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13561:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13562:    &flushcourselogs();
                   13563:    &logthis("Shutting down");
                   13564: }
                   13565: 
1.852     albertel 13566: sub get_dns {
1.1172.2.17  raeburn  13567:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13568:     if (!$ignore_cache) {
                   13569: 	my ($content,$cached)=
                   13570: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13571: 	if ($cached) {
1.1172.2.17  raeburn  13572: 	    &$func($content,$hashref);
1.869     albertel 13573: 	    return;
                   13574: 	}
                   13575:     }
                   13576: 
                   13577:     my %alldns;
1.1172.2.96  raeburn  13578:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13579:         foreach my $dns (<$config>) {
                   13580: 	    next if ($dns !~ /^\^(\S*)/x);
                   13581:             my $line = $1;
                   13582:             my ($host,$protocol) = split(/:/,$line);
                   13583:             if ($protocol ne 'https') {
                   13584:                 $protocol = 'http';
                   13585:             }
                   13586: 	    $alldns{$host} = $protocol;
1.979     raeburn  13587:         }
1.1172.2.96  raeburn  13588:         close($config);
1.869     albertel 13589:     }
                   13590:     while (%alldns) {
1.1172.2.52  raeburn  13591: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 13592: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  13593:         $ua->timeout(30);
1.979     raeburn  13594: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 13595: 	my $response=$ua->request($request);
1.979     raeburn  13596:         delete($alldns{$dns});
1.852     albertel 13597: 	next if ($response->is_error());
                   13598: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  13599:         unless ($nocache) {
1.1172.2.23  raeburn  13600: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  13601:         }
                   13602: 	&$func(\@content,$hashref);
1.869     albertel 13603: 	return;
1.852     albertel 13604:     }
1.871     albertel 13605:     my $which = (split('/',$url))[3];
                   13606:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  13607:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13608:         my @content = <$config>;
                   13609:         &$func(\@content,$hashref);
                   13610:     }
1.1172.2.17  raeburn  13611:     return;
                   13612: }
                   13613: 
                   13614: # ------------------------------------------------------Get DNS checksums file
                   13615: sub parse_dns_checksums_tab {
                   13616:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  13617:     my $lonhost = $perlvar{'lonHostID'};
                   13618:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  13619:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  13620:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13621:     my $webconfdir = '/etc/httpd/conf';
                   13622:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13623:         $webconfdir = '/etc/apache2';
                   13624:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13625:         if ($1 >= 10) {
                   13626:             $webconfdir = '/etc/apache2';
                   13627:         }
                   13628:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13629:         if ($1 >= 10.0) {
                   13630:             $webconfdir = '/etc/apache2';
                   13631:         }
                   13632:     }
1.1172.2.17  raeburn  13633:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13634:     my (%chksum,%revnum);
                   13635:     if (ref($lines) eq 'ARRAY') {
                   13636:         chomp(@{$lines});
1.1172.2.34  raeburn  13637:         my $version = shift(@{$lines});
                   13638:         if ($version eq $release) {
1.1172.2.17  raeburn  13639:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  13640:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  13641:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13642:                     if ($webconfdir eq '/etc/apache2') {
                   13643:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13644:                     }
                   13645:                 }
1.1172.2.34  raeburn  13646:                 $chksum{$file} = $shasum;
                   13647:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  13648:             }
                   13649:             if (ref($hashref) eq 'HASH') {
                   13650:                 %{$hashref} = (
                   13651:                                 sums     => \%chksum,
                   13652:                                 versions => \%revnum,
                   13653:                               );
                   13654:             }
                   13655:         }
                   13656:     }
1.869     albertel 13657:     return;
1.852     albertel 13658: }
1.1172.2.17  raeburn  13659: 
                   13660: sub fetch_dns_checksums {
                   13661:     my %checksums;
1.1172.2.34  raeburn  13662:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  13663:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  13664:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13665:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  13666:              \%checksums);
                   13667:     return \%checksums;
                   13668: }
                   13669: 
1.327     albertel 13670: # ------------------------------------------------------------ Read domain file
                   13671: {
1.852     albertel 13672:     my $loaded;
1.846     albertel 13673:     my %domain;
                   13674: 
1.852     albertel 13675:     sub parse_domain_tab {
                   13676: 	my ($lines) = @_;
                   13677: 	foreach my $line (@$lines) {
                   13678: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13679: 
1.846     albertel 13680: 	    chomp($line);
1.852     albertel 13681: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13682: 	    my %this_domain;
                   13683: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13684: 			       'lang_def', 'city', 'longi', 'lati',
                   13685: 			       'primary') {
                   13686: 		$this_domain{$field} = shift(@elements);
                   13687: 	    }
                   13688: 	    $domain{$name} = \%this_domain;
1.852     albertel 13689: 	}
                   13690:     }
1.864     albertel 13691: 
                   13692:     sub reset_domain_info {
                   13693: 	undef($loaded);
                   13694: 	undef(%domain);
                   13695:     }
                   13696: 
1.852     albertel 13697:     sub load_domain_tab {
1.1172.2.70  raeburn  13698: 	my ($ignore_cache,$nocache) = @_;
                   13699: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13700: 	my $fh;
1.1172.2.96  raeburn  13701: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13702: 	    my @lines = <$fh>;
                   13703: 	    &parse_domain_tab(\@lines);
1.448     albertel 13704: 	}
1.852     albertel 13705: 	close($fh);
                   13706: 	$loaded = 1;
1.327     albertel 13707:     }
1.846     albertel 13708: 
                   13709:     sub domain {
1.852     albertel 13710: 	&load_domain_tab() if (!$loaded);
                   13711: 
1.846     albertel 13712: 	my ($name,$what) = @_;
                   13713: 	return if ( !exists($domain{$name}) );
                   13714: 
                   13715: 	if (!$what) {
                   13716: 	    return $domain{$name}{'description'};
                   13717: 	}
                   13718: 	return $domain{$name}{$what};
                   13719:     }
1.974     raeburn  13720: 
                   13721:     sub domain_info {
                   13722:         &load_domain_tab() if (!$loaded);
                   13723:         return %domain;
                   13724:     }
                   13725: 
1.327     albertel 13726: }
                   13727: 
                   13728: 
1.1       albertel 13729: # ------------------------------------------------------------- Read hosts file
                   13730: {
1.838     albertel 13731:     my %hostname;
1.844     albertel 13732:     my %hostdom;
1.845     albertel 13733:     my %libserv;
1.852     albertel 13734:     my $loaded;
1.888     albertel 13735:     my %name_to_host;
1.1074    raeburn  13736:     my %internetdom;
1.1107    raeburn  13737:     my %LC_dns_serv;
1.852     albertel 13738: 
                   13739:     sub parse_hosts_tab {
                   13740: 	my ($file) = @_;
                   13741: 	foreach my $configline (@$file) {
                   13742: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13743:             chomp($configline);
                   13744: 	    if ($configline =~ /^\^/) {
                   13745:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13746:                     $LC_dns_serv{$1} = 1;
                   13747:                 }
                   13748:                 next;
                   13749:             }
1.1074    raeburn  13750: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13751: 	    $name=~s/\s//g;
                   13752: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  13753:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13754:                     my $curr = $hostname{$id};
                   13755:                     my $skip;
                   13756:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13757:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13758:                             $skip = 1;
                   13759:                         } else {
                   13760:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13761:                         }
                   13762:                     }
                   13763:                     unless ($skip) {
                   13764:                         push(@{$name_to_host{$name}},$id);
                   13765:                     }
                   13766:                 } else {
                   13767:                     push(@{$name_to_host{$name}},$id);
                   13768:                 }
1.852     albertel 13769: 		$hostname{$id}=$name;
                   13770: 		$hostdom{$id}=$domain;
                   13771: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13772:                 if (defined($protocol)) {
                   13773:                     if ($protocol eq 'https') {
                   13774:                         $protocol{$id} = $protocol;
                   13775:                     } else {
                   13776:                         $protocol{$id} = 'http'; 
                   13777:                     }
1.968     raeburn  13778:                 } else {
1.969     raeburn  13779:                     $protocol{$id} = 'http';
1.968     raeburn  13780:                 }
1.1074    raeburn  13781:                 if (defined($intdom)) {
                   13782:                     $internetdom{$id} = $intdom;
                   13783:                 }
1.852     albertel 13784: 	    }
                   13785: 	}
                   13786:     }
1.864     albertel 13787:     
                   13788:     sub reset_hosts_info {
1.897     albertel 13789: 	&purge_remembered();
1.864     albertel 13790: 	&reset_domain_info();
                   13791: 	&reset_hosts_ip_info();
1.892     albertel 13792: 	undef(%name_to_host);
1.864     albertel 13793: 	undef(%hostname);
                   13794: 	undef(%hostdom);
                   13795: 	undef(%libserv);
                   13796: 	undef($loaded);
                   13797:     }
1.1       albertel 13798: 
1.852     albertel 13799:     sub load_hosts_tab {
1.1172.2.70  raeburn  13800: 	my ($ignore_cache,$nocache) = @_;
                   13801: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  13802: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13803: 	my @config = <$config>;
                   13804: 	&parse_hosts_tab(\@config);
                   13805: 	close($config);
                   13806: 	$loaded=1;
1.1       albertel 13807:     }
1.852     albertel 13808: 
1.838     albertel 13809:     sub hostname {
1.852     albertel 13810: 	&load_hosts_tab() if (!$loaded);
                   13811: 
1.838     albertel 13812: 	my ($lonid) = @_;
                   13813: 	return $hostname{$lonid};
                   13814:     }
1.845     albertel 13815: 
1.838     albertel 13816:     sub all_hostnames {
1.852     albertel 13817: 	&load_hosts_tab() if (!$loaded);
                   13818: 
1.838     albertel 13819: 	return %hostname;
                   13820:     }
1.845     albertel 13821: 
1.888     albertel 13822:     sub all_names {
1.1172.2.70  raeburn  13823:         my ($ignore_cache,$nocache) = @_;
                   13824: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13825: 
                   13826: 	return %name_to_host;
                   13827:     }
                   13828: 
1.974     raeburn  13829:     sub all_host_domain {
                   13830:         &load_hosts_tab() if (!$loaded);
                   13831:         return %hostdom;
                   13832:     }
                   13833: 
1.845     albertel 13834:     sub is_library {
1.852     albertel 13835: 	&load_hosts_tab() if (!$loaded);
                   13836: 
1.845     albertel 13837: 	return exists($libserv{$_[0]});
                   13838:     }
                   13839: 
                   13840:     sub all_library {
1.852     albertel 13841: 	&load_hosts_tab() if (!$loaded);
                   13842: 
1.845     albertel 13843: 	return %libserv;
                   13844:     }
                   13845: 
1.1062    droeschl 13846:     sub unique_library {
                   13847: 	#2x reverse removes all hostnames that appear more than once
                   13848:         my %unique = reverse &all_library();
                   13849:         return reverse %unique;
                   13850:     }
                   13851: 
1.841     albertel 13852:     sub get_servers {
1.852     albertel 13853: 	&load_hosts_tab() if (!$loaded);
                   13854: 
1.841     albertel 13855: 	my ($domain,$type) = @_;
                   13856: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13857: 	                                          : %hostname;
                   13858: 	my %result;
1.842     albertel 13859: 	if (ref($domain) eq 'ARRAY') {
                   13860: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13861: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13862: 		    $result{$host} = $hostname;
                   13863: 		}
                   13864: 	    }
                   13865: 	} else {
                   13866: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13867: 		if ($hostdom{$host} eq $domain) {
                   13868: 		    $result{$host} = $hostname;
                   13869: 		}
1.841     albertel 13870: 	    }
                   13871: 	}
                   13872: 	return %result;
                   13873:     }
1.845     albertel 13874: 
1.1062    droeschl 13875:     sub get_unique_servers {
                   13876:         my %unique = reverse &get_servers(@_);
                   13877: 	return reverse %unique;
                   13878:     }
                   13879: 
1.844     albertel 13880:     sub host_domain {
1.852     albertel 13881: 	&load_hosts_tab() if (!$loaded);
                   13882: 
1.844     albertel 13883: 	my ($lonid) = @_;
                   13884: 	return $hostdom{$lonid};
                   13885:     }
                   13886: 
1.841     albertel 13887:     sub all_domains {
1.852     albertel 13888: 	&load_hosts_tab() if (!$loaded);
                   13889: 
1.841     albertel 13890: 	my %seen;
                   13891: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13892: 	return @uniq;
                   13893:     }
1.1074    raeburn  13894: 
                   13895:     sub internet_dom {
                   13896:         &load_hosts_tab() if (!$loaded);
                   13897: 
                   13898:         my ($lonid) = @_;
                   13899:         return $internetdom{$lonid};
                   13900:     }
1.1107    raeburn  13901: 
                   13902:     sub is_LC_dns {
                   13903:         &load_hosts_tab() if (!$loaded);
                   13904: 
                   13905:         my ($hostname) = @_;
                   13906:         return exists($LC_dns_serv{$hostname});
                   13907:     }
                   13908: 
1.1       albertel 13909: }
                   13910: 
1.847     albertel 13911: { 
                   13912:     my %iphost;
1.856     albertel 13913:     my %name_to_ip;
                   13914:     my %lonid_to_ip;
1.869     albertel 13915: 
1.847     albertel 13916:     sub get_hosts_from_ip {
                   13917: 	my ($ip) = @_;
                   13918: 	my %iphosts = &get_iphost();
                   13919: 	if (ref($iphosts{$ip})) {
                   13920: 	    return @{$iphosts{$ip}};
                   13921: 	}
                   13922: 	return;
1.839     albertel 13923:     }
1.864     albertel 13924:     
                   13925:     sub reset_hosts_ip_info {
                   13926: 	undef(%iphost);
                   13927: 	undef(%name_to_ip);
                   13928: 	undef(%lonid_to_ip);
                   13929:     }
1.856     albertel 13930: 
                   13931:     sub get_host_ip {
                   13932: 	my ($lonid) = @_;
                   13933: 	if (exists($lonid_to_ip{$lonid})) {
                   13934: 	    return $lonid_to_ip{$lonid};
                   13935: 	}
                   13936: 	my $name=&hostname($lonid);
                   13937:    	my $ip = gethostbyname($name);
                   13938: 	return if (!$ip || length($ip) ne 4);
                   13939: 	$ip=inet_ntoa($ip);
                   13940: 	$name_to_ip{$name}   = $ip;
                   13941: 	$lonid_to_ip{$lonid} = $ip;
                   13942: 	return $ip;
                   13943:     }
1.847     albertel 13944:     
                   13945:     sub get_iphost {
1.1172.2.70  raeburn  13946: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13947: 
1.869     albertel 13948: 	if (!$ignore_cache) {
                   13949: 	    if (%iphost) {
                   13950: 		return %iphost;
                   13951: 	    }
                   13952: 	    my ($ip_info,$cached)=
                   13953: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13954: 	    if ($cached) {
                   13955: 		%iphost      = %{$ip_info->[0]};
                   13956: 		%name_to_ip  = %{$ip_info->[1]};
                   13957: 		%lonid_to_ip = %{$ip_info->[2]};
                   13958: 		return %iphost;
                   13959: 	    }
                   13960: 	}
1.894     albertel 13961: 
                   13962: 	# get yesterday's info for fallback
                   13963: 	my %old_name_to_ip;
                   13964: 	my ($ip_info,$cached)=
                   13965: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13966: 	if ($cached) {
                   13967: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13968: 	}
                   13969: 
1.1172.2.70  raeburn  13970: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13971: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13972: 	    my $ip;
                   13973: 	    if (!exists($name_to_ip{$name})) {
                   13974: 		$ip = gethostbyname($name);
                   13975: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13976: 		    if (defined($old_name_to_ip{$name})) {
                   13977: 			$ip = $old_name_to_ip{$name};
                   13978: 			&logthis("Can't find $name defaulting to old $ip");
                   13979: 		    } else {
                   13980: 			&logthis("Name $name no IP found");
                   13981: 			next;
                   13982: 		    }
                   13983: 		} else {
                   13984: 		    $ip=inet_ntoa($ip);
1.847     albertel 13985: 		}
                   13986: 		$name_to_ip{$name} = $ip;
                   13987: 	    } else {
                   13988: 		$ip = $name_to_ip{$name};
1.653     albertel 13989: 	    }
1.888     albertel 13990: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13991: 		$lonid_to_ip{$id} = $ip;
                   13992: 	    }
                   13993: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13994: 	}
1.1172.2.70  raeburn  13995:         unless ($nocache) {
                   13996: 	    &do_cache_new('iphost','iphost',
                   13997: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13998: 		          48*60*60);
                   13999:         }
1.869     albertel 14000: 
1.847     albertel 14001: 	return %iphost;
1.598     albertel 14002:     }
                   14003: 
1.992     raeburn  14004:     #
                   14005:     #  Given a DNS returns the loncapa host name for that DNS 
                   14006:     # 
                   14007:     sub host_from_dns {
                   14008:         my ($dns) = @_;
                   14009:         my @hosts;
                   14010:         my $ip;
                   14011: 
1.993     raeburn  14012:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14013:             $ip = $name_to_ip{$dns};
                   14014:         }
                   14015:         if (!$ip) {
                   14016:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14017:             if (length($ip) == 4) { 
                   14018: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14019:             }
                   14020:         }
                   14021:         if ($ip) {
                   14022: 	    @hosts = get_hosts_from_ip($ip);
                   14023: 	    return $hosts[0];
                   14024:         }
                   14025:         return undef;
1.986     foxr     14026:     }
1.992     raeburn  14027: 
1.1074    raeburn  14028:     sub get_internet_names {
                   14029:         my ($lonid) = @_;
                   14030:         return if ($lonid eq '');
                   14031:         my ($idnref,$cached)=
                   14032:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14033:         if ($cached) {
                   14034:             return $idnref;
                   14035:         }
                   14036:         my $ip = &get_host_ip($lonid);
                   14037:         my @hosts = &get_hosts_from_ip($ip);
                   14038:         my %iphost = &get_iphost();
                   14039:         my (@idns,%seen);
                   14040:         foreach my $id (@hosts) {
                   14041:             my $dom = &host_domain($id);
                   14042:             my $prim_id = &domain($dom,'primary');
                   14043:             my $prim_ip = &get_host_ip($prim_id);
                   14044:             next if ($seen{$prim_ip});
                   14045:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14046:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14047:                     my $intdom = &internet_dom($id);
                   14048:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14049:                         push(@idns,$intdom);
                   14050:                     }
                   14051:                 }
                   14052:             }
                   14053:             $seen{$prim_ip} = 1;
                   14054:         }
1.1172.2.23  raeburn  14055:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14056:     }
                   14057: 
1.986     foxr     14058: }
                   14059: 
1.1079    raeburn  14060: sub all_loncaparevs {
1.1172.2.39  raeburn  14061:     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  14062: }
                   14063: 
1.1172.2.27  raeburn  14064: # ------------------------------------------------------- Read loncaparev table
                   14065: {
                   14066:     sub load_loncaparevs {
                   14067:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  14068:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  14069:                 while (my $configline=<$config>) {
                   14070:                     chomp($configline);
                   14071:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14072:                     $loncaparevs{$hostid}=$loncaparev;
                   14073:                 }
                   14074:                 close($config);
                   14075:             }
                   14076:         }
                   14077:     }
                   14078: }
                   14079: 
                   14080: # ----------------------------------------------------- Read serverhostID table
                   14081: {
                   14082:     sub load_serverhomeIDs {
                   14083:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  14084:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  14085:                 while (my $configline=<$config>) {
                   14086:                     chomp($configline);
                   14087:                     my ($name,$id)=split(/:/,$configline);
                   14088:                     $serverhomeIDs{$name}=$id;
                   14089:                 }
                   14090:                 close($config);
                   14091:             }
                   14092:         }
                   14093:     }
                   14094: }
                   14095: 
                   14096: 
1.862     albertel 14097: BEGIN {
                   14098: 
                   14099: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14100:     unless ($readit) {
                   14101: {
                   14102:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14103:     %perlvar = (%perlvar,%{$configvars});
                   14104: }
                   14105: 
                   14106: 
1.1       albertel 14107: # ------------------------------------------------------ Read spare server file
                   14108: {
1.1172.2.96  raeburn  14109:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14110: 
                   14111:     while (my $configline=<$config>) {
                   14112:        chomp($configline);
1.284     matthew  14113:        if ($configline) {
1.784     albertel 14114: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14115: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14116: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14117:        }
                   14118:     }
1.448     albertel 14119:     close($config);
1.1       albertel 14120: }
1.11      www      14121: # ------------------------------------------------------------ Read permissions
                   14122: {
1.1172.2.96  raeburn  14123:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14124: 
                   14125:     while (my $configline=<$config>) {
1.448     albertel 14126: 	chomp($configline);
                   14127: 	if ($configline) {
                   14128: 	    my ($role,$perm)=split(/ /,$configline);
                   14129: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14130: 	}
1.11      www      14131:     }
1.448     albertel 14132:     close($config);
1.11      www      14133: }
                   14134: 
                   14135: # -------------------------------------------- Read plain texts for permissions
                   14136: {
1.1172.2.96  raeburn  14137:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14138: 
                   14139:     while (my $configline=<$config>) {
1.448     albertel 14140: 	chomp($configline);
                   14141: 	if ($configline) {
1.742     raeburn  14142: 	    my ($short,@plain)=split(/:/,$configline);
                   14143:             %{$prp{$short}} = ();
                   14144: 	    if (@plain > 0) {
                   14145:                 $prp{$short}{'std'} = $plain[0];
                   14146:                 for (my $i=1; $i<@plain; $i++) {
                   14147:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14148:                 }
                   14149:             }
1.448     albertel 14150: 	}
1.135     www      14151:     }
1.448     albertel 14152:     close($config);
1.135     www      14153: }
                   14154: 
                   14155: # ---------------------------------------------------------- Read package table
                   14156: {
1.1172.2.96  raeburn  14157:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14158: 
                   14159:     while (my $configline=<$config>) {
1.483     albertel 14160: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14161: 	chomp($configline);
                   14162: 	my ($short,$plain)=split(/:/,$configline);
                   14163: 	my ($pack,$name)=split(/\&/,$short);
                   14164: 	if ($plain ne '') {
                   14165: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14166: 	    $packagetab{$short}=$plain; 
                   14167: 	}
1.11      www      14168:     }
1.448     albertel 14169:     close($config);
1.329     matthew  14170: }
                   14171: 
1.1172.2.27  raeburn  14172: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  14173: 
1.1172.2.27  raeburn  14174: &load_loncaparevs();
                   14175: 
                   14176: # ------------------------------------------------------- Read serverhostID table
                   14177: 
                   14178: &load_serverhomeIDs();
1.1074    raeburn  14179: 
1.1172.2.27  raeburn  14180: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14181: {
                   14182:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14183:     if (-e $file) {
                   14184:         my $parser = HTML::LCParser->new($file);
                   14185:         while (my $token = $parser->get_token()) {
                   14186:             if ($token->[0] eq 'S') {
                   14187:                 my $item = $token->[1];
                   14188:                 my $name = $token->[2]{'name'};
                   14189:                 my $value = $token->[2]{'value'};
                   14190:                 if ($item ne '' && $name ne '' && $value ne '') {
                   14191:                     my $release = $parser->get_text();
                   14192:                     $release =~ s/(^\s*|\s*$ )//gx;
                   14193:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   14194:                 }
                   14195:             }
                   14196:         }
                   14197:     }
1.1073    raeburn  14198: }
                   14199: 
1.1138    raeburn  14200: # ---------------------------------------------------------- Read managers table
                   14201: {
                   14202:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  14203:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14204:             while (my $configline=<$config>) {
                   14205:                 chomp($configline);
                   14206:                 next if ($configline =~ /^\#/);
                   14207:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14208:                     $managerstab{$configline} = 1;
                   14209:                 }
                   14210:             }
                   14211:             close($config);
                   14212:         }
                   14213:     }
                   14214: }
                   14215: 
1.329     matthew  14216: # ------------- set up temporary directory
                   14217: {
1.1117    foxr     14218:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14219: 
1.11      www      14220: }
                   14221: 
1.1172.2.104  raeburn  14222: # ------------- set default texengine (domain default overrides this)
                   14223: {
                   14224:     $deftex = LONCAPA::texengine();
                   14225: }
                   14226: 
1.1172.2.114  raeburn  14227: # ------------- set default minimum length for passwords for internal auth users
                   14228: {
                   14229:     $passwdmin = LONCAPA::passwd_min();
                   14230: }
                   14231: 
1.794     albertel 14232: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14233: 				'compress_threshold'=> 20_000,
                   14234:  			        });
1.185     www      14235: 
1.281     www      14236: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14237: $dumpcount=0;
1.958     www      14238: $locknum=0;
1.22      www      14239: 
1.163     harris41 14240: &logtouch();
1.672     albertel 14241: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14242: $readit=1;
1.564     albertel 14243:     {
                   14244: 	use integer;
                   14245: 	my $test=(2**32)+1;
1.568     albertel 14246: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14247: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14248:     }
1.195     www      14249: }
1.1       albertel 14250: }
1.179     www      14251: 
1.1       albertel 14252: 1;
1.191     harris41 14253: __END__
                   14254: 
1.243     albertel 14255: =pod
                   14256: 
1.191     harris41 14257: =head1 NAME
                   14258: 
1.243     albertel 14259: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14260: 
                   14261: =head1 SYNOPSIS
                   14262: 
1.243     albertel 14263: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14264: 
                   14265:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14266: 
1.243     albertel 14267: Common parameters:
                   14268: 
                   14269: =over 4
                   14270: 
                   14271: =item *
                   14272: 
                   14273: $uname : an internal username (if $cname expecting a course Id specifically)
                   14274: 
                   14275: =item *
                   14276: 
                   14277: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14278: 
                   14279: =item *
                   14280: 
                   14281: $symb : a resource instance identifier
                   14282: 
                   14283: =item *
                   14284: 
                   14285: $namespace : the name of a .db file that contains the data needed or
                   14286: being set.
                   14287: 
                   14288: =back
                   14289: 
1.394     bowersj2 14290: =head1 OVERVIEW
1.191     harris41 14291: 
1.394     bowersj2 14292: lonnet provides subroutines which interact with the
                   14293: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14294: about classes, users, and resources.
1.243     albertel 14295: 
                   14296: For many of these objects you can also use this to store data about
                   14297: them or modify them in various ways.
1.191     harris41 14298: 
1.394     bowersj2 14299: =head2 Symbs
1.191     harris41 14300: 
1.394     bowersj2 14301: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14302: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14303: map, the resource number of the resource in the map, and the URL of
                   14304: the resource itself. The latter is somewhat redundant, but might help
                   14305: if maps change.
                   14306: 
                   14307: An example is
                   14308: 
                   14309:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14310: 
                   14311: The respective map entry is
                   14312: 
                   14313:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14314:   title="Problem 2">
                   14315:  </resource>
                   14316: 
                   14317: Symbs are used by the random number generator, as well as to store and
                   14318: restore data specific to a certain instance of for example a problem.
                   14319: 
                   14320: =head2 Storing And Retrieving Data
                   14321: 
                   14322: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14323: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14324: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14325: is is the non-critical message twin of cstore. These functions are for
                   14326: handlers to store a perl hash to a user's permanent data space in an
                   14327: easy manner, and to retrieve it again on another call. It is expected
                   14328: that a handler would use this once at the beginning to retrieve data,
                   14329: and then again once at the end to send only the new data back.
                   14330: 
                   14331: The data is stored in the user's data directory on the user's
                   14332: homeserver under the ID of the course.
                   14333: 
                   14334: The hash that is returned by restore will have all of the previous
                   14335: value for all of the elements of the hash.
                   14336: 
                   14337: Example:
                   14338: 
                   14339:  #creating a hash
                   14340:  my %hash;
                   14341:  $hash{'foo'}='bar';
                   14342: 
                   14343:  #storing it
                   14344:  &Apache::lonnet::cstore(\%hash);
                   14345: 
                   14346:  #changing a value
                   14347:  $hash{'foo'}='notbar';
                   14348: 
                   14349:  #adding a new value
                   14350:  $hash{'bar'}='foo';
                   14351:  &Apache::lonnet::cstore(\%hash);
                   14352: 
                   14353:  #retrieving the hash
                   14354:  my %history=&Apache::lonnet::restore();
                   14355: 
                   14356:  #print the hash
                   14357:  foreach my $key (sort(keys(%history))) {
                   14358:    print("\%history{$key} = $history{$key}");
                   14359:  }
                   14360: 
                   14361: Will print out:
1.191     harris41 14362: 
1.394     bowersj2 14363:  %history{1:foo} = bar
                   14364:  %history{1:keys} = foo:timestamp
                   14365:  %history{1:timestamp} = 990455579
                   14366:  %history{2:bar} = foo
                   14367:  %history{2:foo} = notbar
                   14368:  %history{2:keys} = foo:bar:timestamp
                   14369:  %history{2:timestamp} = 990455580
                   14370:  %history{bar} = foo
                   14371:  %history{foo} = notbar
                   14372:  %history{timestamp} = 990455580
                   14373:  %history{version} = 2
                   14374: 
                   14375: Note that the special hash entries C<keys>, C<version> and
                   14376: C<timestamp> were added to the hash. C<version> will be equal to the
                   14377: total number of versions of the data that have been stored. The
                   14378: C<timestamp> attribute will be the UNIX time the hash was
                   14379: stored. C<keys> is available in every historical section to list which
                   14380: keys were added or changed at a specific historical revision of a
                   14381: hash.
                   14382: 
                   14383: B<Warning>: do not store the hash that restore returns directly. This
                   14384: will cause a mess since it will restore the historical keys as if the
                   14385: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14386: 
1.394     bowersj2 14387: Calling convention:
1.191     harris41 14388: 
1.1172.2.27  raeburn  14389:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  14390:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14391: 
1.394     bowersj2 14392: For more detailed information, see lonnet specific documentation.
1.191     harris41 14393: 
1.394     bowersj2 14394: =head1 RETURN MESSAGES
1.191     harris41 14395: 
1.394     bowersj2 14396: =over 4
1.191     harris41 14397: 
1.394     bowersj2 14398: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14399: 
1.394     bowersj2 14400: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14401: when the connection is brought back up
1.191     harris41 14402: 
1.394     bowersj2 14403: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14404: for later delivery
1.191     harris41 14405: 
1.967     bisitz   14406: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14407: 
1.394     bowersj2 14408: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14409: that was requested
1.191     harris41 14410: 
1.243     albertel 14411: =back
1.191     harris41 14412: 
1.243     albertel 14413: =head1 PUBLIC SUBROUTINES
1.191     harris41 14414: 
1.243     albertel 14415: =head2 Session Environment Functions
1.191     harris41 14416: 
1.243     albertel 14417: =over 4
1.191     harris41 14418: 
1.394     bowersj2 14419: =item * 
                   14420: X<appenv()>
1.949     raeburn  14421: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14422: the user envirnoment file, and will be restored for each access this
1.620     albertel 14423: user makes during this session, also modifies the %env for the current
1.949     raeburn  14424: process. Optional rolesarrayref - if defined contains a reference to an array
                   14425: of roles which are exempt from the restriction on modifying user.role entries 
                   14426: in the user's environment.db and in %env.    
1.191     harris41 14427: 
                   14428: =item *
1.394     bowersj2 14429: X<delenv()>
1.987     raeburn  14430: B<delenv($delthis,$regexp)>: removes all items from the session
                   14431: environment file that begin with $delthis. If the 
                   14432: optional second arg - $regexp - is true, $delthis is treated as a 
                   14433: regular expression, otherwise \Q$delthis\E is used. 
                   14434: The values are also deleted from the current processes %env.
1.191     harris41 14435: 
1.795     albertel 14436: =item * get_env_multiple($name) 
                   14437: 
                   14438: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14439: values may be defined and end up as an array ref.
                   14440: 
                   14441: returns an array of values
                   14442: 
1.243     albertel 14443: =back
                   14444: 
                   14445: =head2 User Information
1.191     harris41 14446: 
1.243     albertel 14447: =over 4
1.191     harris41 14448: 
                   14449: =item *
1.394     bowersj2 14450: X<queryauthenticate()>
                   14451: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14452: authentication scheme
                   14453: 
                   14454: =item *
1.394     bowersj2 14455: X<authenticate()>
1.1073    raeburn  14456: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14457: authenticate user from domain's lib servers (first use the current
                   14458: one). C<$upass> should be the users password.
1.1073    raeburn  14459: $checkdefauth is optional (value is 1 if a check should be made to
                   14460:    authenticate user using default authentication method, and allow
                   14461:    account creation if username does not have account in the domain).
                   14462: $clientcancheckhost is optional (value is 1 if checking whether the
                   14463:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14464: 
                   14465: =item *
1.394     bowersj2 14466: X<homeserver()>
                   14467: B<homeserver($uname,$udom)>: find the server which has
                   14468: the user's directory and files (there must be only one), this caches
                   14469: the answer, and also caches if there is a borken connection.
1.191     harris41 14470: 
                   14471: =item *
1.394     bowersj2 14472: X<idget()>
                   14473: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   14474: (IDs are a unique resource in a domain, there must be only 1 ID per
                   14475: username, and only 1 username per ID in a specific domain) (returns
                   14476: hash: id=>name,id=>name)
1.191     harris41 14477: 
                   14478: =item *
1.394     bowersj2 14479: X<idrget()>
                   14480: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14481: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14482: 
                   14483: =item *
1.394     bowersj2 14484: X<idput()>
                   14485: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 14486: 
                   14487: =item *
1.394     bowersj2 14488: X<rolesinit()>
1.1169    droeschl 14489: B<rolesinit($udom,$username)>: get user privileges.
                   14490: returns user role, first access and timer interval hashes
1.243     albertel 14491: 
                   14492: =item *
1.1171    droeschl 14493: X<privileged()>
                   14494: B<privileged($username,$domain)>: returns a true if user has a
                   14495: privileged and active role (i.e. su or dc), false otherwise.
                   14496: 
                   14497: =item *
1.551     albertel 14498: X<getsection()>
                   14499: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14500: course $cname, return section name/number or '' for "not in course"
                   14501: and '-1' for "no section"
                   14502: 
                   14503: =item *
1.394     bowersj2 14504: X<userenvironment()>
                   14505: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14506: passed in @what from the requested user's environment, returns a hash
                   14507: 
1.858     raeburn  14508: =item * 
                   14509: X<userlog_query()>
1.859     albertel 14510: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14511: activity.log file. %filters defines filters applied when parsing the
                   14512: log file. These can be start or end timestamps, or the type of action
                   14513: - log to look for Login or Logout events, check for Checkin or
                   14514: Checkout, role for role selection. The response is in the form
                   14515: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14516: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14517: 
1.243     albertel 14518: =back
                   14519: 
                   14520: =head2 User Roles
                   14521: 
                   14522: =over 4
                   14523: 
                   14524: =item *
                   14525: 
1.1172.2.65  raeburn  14526: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14527: returns codes for allowed actions.
                   14528: 
                   14529: The first argument is required, all others are optional.
                   14530: 
                   14531: $priv is the privilege being checked.
                   14532: $uri contains additional information about what is being checked for access (e.g.,
                   14533: URL, course ID etc.).
                   14534: $symb is the unique resource instance identifier in a course; if needed,
                   14535: but not provided, it will be retrieved via a call to &symbread().
                   14536: $role is the role for which a priv is being checked (only used if priv is evb).
                   14537: $clientip is the user's IP address (only used when checking for access to portfolio
                   14538: files).
                   14539: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   14540: prevents recursive calls to &allowed.
                   14541: 
1.243     albertel 14542:  F: full access
                   14543:  U,I,K: authentication modes (cxx only)
                   14544:  '': forbidden
                   14545:  1: user needs to choose course
                   14546:  2: browse allowed
1.766     albertel 14547:  A: passphrase authentication needed
1.1172.2.65  raeburn  14548:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14549: 
                   14550: =item *
                   14551: 
1.1172.2.13  raeburn  14552: constructaccess($url,$setpriv) : check for access to construction space URL
                   14553: 
                   14554: See if the owner domain and name in the URL match those in the
                   14555: expected environment.  If so, return three element list
                   14556: ($ownername,$ownerdomain,$ownerhome).
                   14557: 
                   14558: Otherwise return the null string.
                   14559: 
                   14560: If second argument 'setpriv' is true, it assigns the privileges,
                   14561: and returns the same three element list, unless the owner has
                   14562: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14563: in which case the null string is returned.
                   14564: 
                   14565: =item *
                   14566: 
1.1172.2.84  raeburn  14567: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14568: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14569: for system, domain, and course level. $uname and $udom are optional (current
                   14570: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14571: 
                   14572: =item *
                   14573: 
1.988     raeburn  14574: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14575: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14576: $type is Course (default) or Community.
1.988     raeburn  14577: If $forcedefault evaluates to true, text returned will be default 
                   14578: text for $type. Otherwise, if this is a course, the text returned 
                   14579: will be a custom name for the role (if defined in the course's 
                   14580: environment).  If no custom name is defined the default is returned.
                   14581:    
1.832     raeburn  14582: =item *
                   14583: 
1.1172.2.23  raeburn  14584: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14585: All arguments are optional. Returns a hash of a roles, either for
                   14586: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14587: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14588: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14589: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14590: For each key, value is set to colon-separated start and end times for
                   14591: the role.  If no username and domain are specified, will default to
1.934     raeburn  14592: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14593: of role statuses (active, future or previous), roles 
                   14594: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14595: to restrict the list of roles reported. If no array ref is 
                   14596: provided for types, will default to return only active roles.
1.834     albertel 14597: 
1.1172.2.13  raeburn  14598: =item *
                   14599: 
                   14600: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   14601: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   14602: 
                   14603: Additional optional arguments are: $type (if role checking is to be restricted
                   14604: to certain user status types -- previous (expired roles), active (currently
                   14605: available roles) or future (roles available in the future), and
                   14606: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  14607: have active Domain Coordinator role in course's domain or in additional
                   14608: domains (specified in 'Domains to check for privileged users' in course
                   14609: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14610: 
                   14611: =item *
                   14612: 
                   14613: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14614: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14615: $possdomains and $possroles are optional array refs -- to domains to check and
                   14616: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14617: users' roles.db to check for a dc or su role in any domain. This can be
                   14618: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14619: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14620: this then allows &privileged_by_domain() to be used, which caches the identity
                   14621: of privileged users, eliminating the need for repeated calls to &dump().
                   14622: 
                   14623: =item *
                   14624: 
                   14625: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14626: where the outer hash keys are domains specified in the $possdomains array ref,
                   14627: next inner hash keys are privileged roles specified in the $roles array ref,
                   14628: and the innermost hash contains key = value pairs for username:domain = end:start
                   14629: for active or future "privileged" users with that role in that domain. To avoid
                   14630: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14631: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  14632: 
1.243     albertel 14633: =back
                   14634: 
                   14635: =head2 User Modification
                   14636: 
                   14637: =over 4
                   14638: 
                   14639: =item *
                   14640: 
1.957     raeburn  14641: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14642: user for the level given by URL.  Optional start and end dates (leave empty
                   14643: string or zero for "no date")
1.191     harris41 14644: 
                   14645: =item *
                   14646: 
1.243     albertel 14647: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14648: change a users, password, possible return values are: ok,
                   14649: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14650: refused
1.191     harris41 14651: 
                   14652: =item *
                   14653: 
1.243     albertel 14654: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14655: 
                   14656: =item *
                   14657: 
1.1058    raeburn  14658: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14659:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14660: 
                   14661: will update user information (firstname,middlename,lastname,generation,
                   14662: permanentemail), and if forceid is true, student/employee ID also.
                   14663: A user's institutional affiliation(s) can also be updated.
                   14664: User information fields will not be overwritten with empty entries 
                   14665: unless the field is included in the $candelete array reference.
                   14666: This array is included when a single user is modified via "Manage Users",
                   14667: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14668: 
                   14669: =item *
                   14670: 
1.286     matthew  14671: modifystudent
                   14672: 
1.957     raeburn  14673: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  14674: The course id is resolved based on the current user's environment.  
                   14675: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14676: associated with a course.
                   14677: 
1.297     matthew  14678: This call is essentially a wrapper for lonnet::modifyuser and
                   14679: lonnet::modify_student_enrollment
1.286     matthew  14680: 
                   14681: Inputs: 
                   14682: 
                   14683: =over 4
                   14684: 
1.957     raeburn  14685: =item B<$udom> Student's loncapa domain
1.286     matthew  14686: 
1.957     raeburn  14687: =item B<$uname> Student's loncapa login name
1.286     matthew  14688: 
1.964     bisitz   14689: =item B<$uid> Student/Employee ID
1.286     matthew  14690: 
1.957     raeburn  14691: =item B<$umode> Student's authentication mode
1.286     matthew  14692: 
1.957     raeburn  14693: =item B<$upass> Student's password
1.286     matthew  14694: 
1.957     raeburn  14695: =item B<$first> Student's first name
1.286     matthew  14696: 
1.957     raeburn  14697: =item B<$middle> Student's middle name
1.286     matthew  14698: 
1.957     raeburn  14699: =item B<$last> Student's last name
1.286     matthew  14700: 
1.957     raeburn  14701: =item B<$gene> Student's generation
1.286     matthew  14702: 
1.957     raeburn  14703: =item B<$usec> Student's section in course
1.286     matthew  14704: 
                   14705: =item B<$end> Unix time of the roles expiration
                   14706: 
                   14707: =item B<$start> Unix time of the roles start date
                   14708: 
                   14709: =item B<$forceid> If defined, allow $uid to be changed
                   14710: 
                   14711: =item B<$desiredhome> server to use as home server for student
                   14712: 
1.957     raeburn  14713: =item B<$email> Student's permanent e-mail address
                   14714: 
                   14715: =item B<$type> Type of enrollment (auto or manual)
                   14716: 
1.963     raeburn  14717: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14718: 
                   14719: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14720: 
1.963     raeburn  14721: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14722: 
1.963     raeburn  14723: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14724: 
1.1172.2.19  raeburn  14725: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14726: 
                   14727: =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  14728: 
1.286     matthew  14729: =back
1.297     matthew  14730: 
                   14731: =item *
                   14732: 
                   14733: modify_student_enrollment
                   14734: 
1.1172.2.31  raeburn  14735: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14736: 'role.request.course' must be defined for this function to proceed.
                   14737: 
                   14738: Inputs:
                   14739: 
                   14740: =over 4
                   14741: 
1.1172.2.31  raeburn  14742: =item $udom, student's domain
1.297     matthew  14743: 
1.1172.2.31  raeburn  14744: =item $uname, student's name
1.297     matthew  14745: 
1.1172.2.31  raeburn  14746: =item $uid, student's user id
1.297     matthew  14747: 
1.1172.2.31  raeburn  14748: =item $first, student's first name
1.297     matthew  14749: 
                   14750: =item $middle
                   14751: 
                   14752: =item $last
                   14753: 
                   14754: =item $gene
                   14755: 
                   14756: =item $usec
                   14757: 
                   14758: =item $end
                   14759: 
                   14760: =item $start
                   14761: 
1.957     raeburn  14762: =item $type
                   14763: 
                   14764: =item $locktype
                   14765: 
                   14766: =item $cid
                   14767: 
                   14768: =item $selfenroll
                   14769: 
                   14770: =item $context
                   14771: 
1.1172.2.19  raeburn  14772: =item $credits, number of credits student will earn from this class
                   14773: 
1.1172.2.76  raeburn  14774: =item $instsec, institutional course section code for student
                   14775: 
1.297     matthew  14776: =back
                   14777: 
1.191     harris41 14778: 
                   14779: =item *
                   14780: 
1.243     albertel 14781: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14782: custom role; give a custom role to a user for the level given by URL.  Specify
                   14783: name and domain of role author, and role name
1.191     harris41 14784: 
                   14785: =item *
                   14786: 
1.243     albertel 14787: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14788: 
                   14789: =item *
                   14790: 
1.243     albertel 14791: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14792: 
                   14793: =back
                   14794: 
                   14795: =head2 Course Infomation
                   14796: 
                   14797: =over 4
1.191     harris41 14798: 
                   14799: =item *
                   14800: 
1.1118    foxr     14801: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14802: specified course id, including all environment settings for the
                   14803: course, the description of the course will be in the hash under the
                   14804: key 'description'
1.191     harris41 14805: 
1.1118    foxr     14806: $options is an optional parameter that if supplied is a hash reference that controls
                   14807: what how this function works.  It has the following key/values:
                   14808: 
                   14809: =over 4
                   14810: 
                   14811: =item freshen_cache
                   14812: 
                   14813: If defined, and the environment cache for the course is valid, it is 
                   14814: returned in the returned hash.
                   14815: 
                   14816: =item one_time
                   14817: 
                   14818: If defined, the last cache time is set to _now_
                   14819: 
                   14820: =item user
                   14821: 
                   14822: If defined, the supplied username is used instead of the current user.
                   14823: 
                   14824: 
                   14825: =back
                   14826: 
1.191     harris41 14827: =item *
                   14828: 
1.624     albertel 14829: resdata($name,$domain,$type,@which) : request for current parameter
                   14830: setting for a specific $type, where $type is either 'course' or 'user',
                   14831: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  14832: answers for 10 minutes.
1.243     albertel 14833: 
1.877     foxr     14834: =item *
                   14835: 
                   14836: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14837: data base, returning a hash that is keyed by the resource name and has
                   14838: values that are the resource value.  I believe that the timestamps and
                   14839: versions are also returned.
                   14840: 
1.1172.2.31  raeburn  14841: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14842: supplemental content area. This routine caches the number of files for
                   14843: 10 minutes.
                   14844: 
1.243     albertel 14845: =back
                   14846: 
                   14847: =head2 Course Modification
                   14848: 
                   14849: =over 4
1.191     harris41 14850: 
                   14851: =item *
                   14852: 
1.243     albertel 14853: writecoursepref($courseid,%prefs) : write preferences (environment
                   14854: database) for a course
1.191     harris41 14855: 
                   14856: =item *
                   14857: 
1.1011    raeburn  14858: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14859: 
                   14860: =item *
                   14861: 
1.1038    raeburn  14862: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14863: 
1.1167    droeschl 14864: =item *
                   14865: 
                   14866: is_course($courseid), is_course($cdom, $cnum)
                   14867: 
                   14868: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14869: two component version $cdom, $cnum. It checks if the specified course exists.
                   14870: 
                   14871: Returns:
                   14872:     undef if the course doesn't exist, otherwise
                   14873:     in scalar context the combined courseid.
                   14874:     in list context the two components of the course identifier, domain and 
                   14875:     courseid.    
                   14876: 
1.243     albertel 14877: =back
                   14878: 
1.1172.2.109  raeburn  14879: =head2 Bubblesheet Configuration
                   14880: 
                   14881: =over 4
                   14882: 
                   14883: =item *
                   14884: 
                   14885: get_scantron_config($which)
                   14886: 
                   14887: $which - the name of the configuration to parse from the file.
                   14888: 
                   14889: Parses and returns the bubblesheet configuration line selected as a
                   14890: hash of configuration file fields.
                   14891: 
                   14892: 
                   14893: Returns:
                   14894:     If the named configuration is not in the file, an empty
                   14895:     hash is returned.
                   14896: 
                   14897:     a hash with the fields
                   14898:       name         - internal name for the this configuration setup
                   14899:       description  - text to display to operator that describes this config
                   14900:       CODElocation - if 0 or the string 'none'
                   14901:                           - no CODE exists for this config
                   14902:                      if -1 || the string 'letter'
                   14903:                           - a CODE exists for this config and is
                   14904:                             a string of letters
                   14905:                      Unsupported value (but planned for future support)
                   14906:                           if a positive integer
                   14907:                                - The CODE exists as the first n items from
                   14908:                                  the question section of the form
                   14909:                           if the string 'number'
                   14910:                                - The CODE exists for this config and is
                   14911:                                  a string of numbers
                   14912:       CODEstart   - (only matter if a CODE exists) column in the line where
                   14913:                      the CODE starts
                   14914:       CODElength  - length of the CODE
                   14915:       IDstart     - column where the student/employee ID starts
                   14916:       IDlength    - length of the student/employee ID info
                   14917:       Qstart      - column where the information from the bubbled
                   14918:                     'questions' start
                   14919:       Qlength     - number of columns comprising a single bubble line from
                   14920:                     the sheet. (usually either 1 or 10)
                   14921:       Qon         - either a single character representing the character used
                   14922:                     to signal a bubble was chosen in the positional setup, or
                   14923:                     the string 'letter' if the letter of the chosen bubble is
                   14924:                     in the final, or 'number' if a number representing the
                   14925:                     chosen bubble is in the file (1->A 0->J)
                   14926:       Qoff        - the character used to represent that a bubble was
                   14927:                     left blank
                   14928:       PaperID     - if the scanning process generates a unique number for each
                   14929:                     sheet scanned the column that this ID number starts in
                   14930:       PaperIDlength - number of columns that comprise the unique ID number
                   14931:                       for the sheet of paper
                   14932:       FirstName   - column that the first name starts in
                   14933:       FirstNameLength - number of columns that the first name spans
                   14934:       LastName    - column that the last name starts in
                   14935:       LastNameLength - number of columns that the last name spans
                   14936:       BubblesPerRow - number of bubbles available in each row used to
                   14937:                       bubble an answer. (If not specified, 10 assumed).
                   14938: 
                   14939: 
                   14940: =item *
                   14941: 
                   14942: get_scantronformat_file($cdom)
                   14943: 
                   14944: $cdom - the course's domain (optional); if not supplied, uses
                   14945: domain for current $env{'request.course.id'}.
                   14946: 
                   14947: Returns an array containing lines from the scantron format file for
                   14948: the domain of the course.
                   14949: 
                   14950: If a url for a custom.tab file is listed in domain's configuration.db,
                   14951: lines are from this file.
                   14952: 
                   14953: Otherwise, if a default.tab has been published in RES space by the
                   14954: domainconfig user, lines are from this file.
                   14955: 
                   14956: Otherwise, fall back to getting lines from the legacy file on the
                   14957: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   14958: 
                   14959: =back
                   14960: 
1.243     albertel 14961: =head2 Resource Subroutines
                   14962: 
                   14963: =over 4
1.191     harris41 14964: 
                   14965: =item *
                   14966: 
1.243     albertel 14967: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14968: 
                   14969: =item *
                   14970: 
1.243     albertel 14971: repcopy($filename) : subscribes to the requested file, and attempts to
                   14972: replicate from the owning library server, Might return
1.607     raeburn  14973: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14974: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14975: resource. Expects the local filesystem pathname
                   14976: (/home/httpd/html/res/....)
                   14977: 
                   14978: =back
                   14979: 
                   14980: =head2 Resource Information
                   14981: 
                   14982: =over 4
1.191     harris41 14983: 
                   14984: =item *
                   14985: 
1.1172.2.28  raeburn  14986: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14987: and returns the value of a variety of different possible values,
                   14988: $varname should be a request string, and the other parameters can be
                   14989: used to specify who and what one is asking about. Ordinarily, $cid 
                   14990: does not need to be specified, as it is retrived from 
                   14991: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14992: within lonuserstate::loadmap() when initializing a course, before
                   14993: $env{'request.course.id'} has been set, so it needs to be provided
                   14994: in that one case.
1.243     albertel 14995: 
                   14996: Possible values for $varname are environment.lastname (or other item
                   14997: from the envirnment hash), user.name (or someother aspect about the
                   14998: user), resource.0.maxtries (or some other part and parameter of a
                   14999: resource)
1.204     albertel 15000: 
                   15001: =item *
                   15002: 
1.243     albertel 15003: directcondval($number) : get current value of a condition; reads from a state
                   15004: string
1.204     albertel 15005: 
                   15006: =item *
                   15007: 
1.243     albertel 15008: condval($condidx) : value of condition index based on state
1.204     albertel 15009: 
                   15010: =item *
                   15011: 
1.243     albertel 15012: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   15013: resource's metadata, $what should be either a specific key, or either
                   15014: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   15015: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   15016: 
                   15017: this function automatically caches all requests
1.191     harris41 15018: 
                   15019: =item *
                   15020: 
1.243     albertel 15021: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15022: network of library servers; returns file handle of where SQL and regex results
                   15023: will be stored for query
1.191     harris41 15024: 
                   15025: =item *
                   15026: 
1.1172.2.66  raeburn  15027: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   15028: return symbolic list entry (all arguments optional).
                   15029: 
                   15030: Args: filename is the filename (including path) for the file for which a symb
                   15031: is required; donotrecurse, if true will prevent calls to allowed() being made
                   15032: to check access status if more than one resource was found in the bighash
                   15033: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   15034: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   15035: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15036: cause possible symbs to be checked to determine if they are subject to content
                   15037: blocking, if so they will not be included as possible symbs; possibles is a
                   15038: ref to a hash, which, as a side effect, will be populated with all possible
                   15039: symbs (content blocking not tested).
                   15040: 
1.243     albertel 15041: returns the data handle
1.191     harris41 15042: 
                   15043: =item *
                   15044: 
1.1172.2.17  raeburn  15045: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  15046: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15047: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  15048: on failure, user must be in a course, as it assumes the existence of
                   15049: the course initial hash, and uses $env('request.course.id'}.  The third
                   15050: arg is an optional reference to a scalar.  If this arg is passed in the
                   15051: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15052: encrypted; otherwise it will be null.
1.243     albertel 15053: 
1.191     harris41 15054: =item *
                   15055: 
1.243     albertel 15056: symbclean($symb) : removes versions numbers from a symb, returns the
                   15057: cleaned symb
1.191     harris41 15058: 
                   15059: =item *
                   15060: 
1.243     albertel 15061: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15062: course map, user must be in a course for it to work.
1.191     harris41 15063: 
                   15064: =item *
                   15065: 
1.243     albertel 15066: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15067: 
                   15068: =item *
                   15069: 
1.243     albertel 15070: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15071: a random seed, all arguments are optional, if they aren't sent it uses the
                   15072: environment to derive them. Note: if symb isn't sent and it can't get one
                   15073: from &symbread it will use the current time as its return value
1.191     harris41 15074: 
                   15075: =item *
                   15076: 
1.243     albertel 15077: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15078: unfakeable, receipt
1.191     harris41 15079: 
                   15080: =item *
                   15081: 
1.620     albertel 15082: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15083: 
                   15084: =item *
                   15085: 
1.243     albertel 15086: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15087: 
                   15088: =item *
                   15089: 
1.243     albertel 15090: 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 15091: 
                   15092: =item *
                   15093: 
1.243     albertel 15094: 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 15095: 
                   15096: =item *
                   15097: 
1.243     albertel 15098: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15099: 
                   15100: =item *
                   15101: 
1.243     albertel 15102: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15103: forcing spreadsheet to reevaluate the resource scores next time.
                   15104: 
1.1172.2.13  raeburn  15105: =item *
                   15106: 
                   15107: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15108: when viewing in course context.
                   15109: 
                   15110:  input: six args -- filename (decluttered), course number, course domain,
                   15111:                     url, symb (if registered) and group (if this is a
                   15112:                     group item -- e.g., bulletin board, group page etc.).
                   15113: 
                   15114:  output: array of five scalars --
                   15115:          $cfile -- url for file editing if editable on current server
                   15116:          $home -- homeserver of resource (i.e., for author if published,
                   15117:                                           or course if uploaded.).
                   15118:          $switchserver --  1 if server switch will be needed.
                   15119:          $forceedit -- 1 if icon/link should be to go to edit mode
                   15120:          $forceview -- 1 if icon/link should be to go to view mode
                   15121: 
                   15122: =item *
                   15123: 
                   15124: is_course_upload($file,$cnum,$cdom)
                   15125: 
                   15126: Used in course context to determine if current file was uploaded to
                   15127: the course (i.e., would be found in /userfiles/docs on the course's
                   15128: homeserver.
                   15129: 
                   15130:   input: 3 args -- filename (decluttered), course number and course domain.
                   15131:   output: boolean -- 1 if file was uploaded.
                   15132: 
1.243     albertel 15133: =back
                   15134: 
                   15135: =head2 Storing/Retreiving Data
                   15136: 
                   15137: =over 4
1.191     harris41 15138: 
                   15139: =item *
                   15140: 
1.1172.2.64  raeburn  15141: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   15142: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15143: the remaining args aren't required and if they aren't passed or are '' they will
                   15144: be derived from the env (with the exception of $laststore, which is an
                   15145: optional arg used when a user's submission is stored in grading).
                   15146: $laststore is $version=$timestamp, where $version is the most recent version
                   15147: number retrieved for the corresponding $symb in the $namespace db file, and
                   15148: $timestamp is the timestamp for that transaction (UNIX time).
                   15149: $laststore is currently only passed when cstore() is called by
                   15150: structuretags::finalize_storage().
1.191     harris41 15151: 
                   15152: =item *
                   15153: 
1.1172.2.64  raeburn  15154: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   15155: but uses critical subroutine
1.191     harris41 15156: 
                   15157: =item *
                   15158: 
1.243     albertel 15159: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15160: all args are optional
1.191     harris41 15161: 
                   15162: =item *
                   15163: 
1.717     albertel 15164: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15165: dumps the complete (or key matching regexp) namespace into a hash
                   15166: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15167: normally &store()ed into
                   15168: 
                   15169: $range should be either an integer '100' (give me the first 100
                   15170:                                            matching records)
                   15171:               or be  two integers sperated by a - with no spaces
                   15172:                  '30-50' (give me the 30th through the 50th matching
                   15173:                           records)
                   15174: 
                   15175: 
                   15176: =item *
                   15177: 
1.1172.2.59  raeburn  15178: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15179: replaces a &store() version of data with a replacement set of data
                   15180: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  15181: reference. If $tolog is true, the transaction is logged in the courselog
                   15182: with an action=PUTSTORE.
1.717     albertel 15183: 
                   15184: =item *
                   15185: 
1.243     albertel 15186: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15187: works very similar to store/cstore, but all data is stored in a
                   15188: temporary location and can be reset using tmpreset, $storehash should
                   15189: be a hash reference, returns nothing on success
1.191     harris41 15190: 
                   15191: =item *
                   15192: 
1.243     albertel 15193: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15194: similar to restore, but all data is stored in a temporary location and
                   15195: can be reset using tmpreset. Returns a hash of values on success,
                   15196: error string otherwise.
1.191     harris41 15197: 
                   15198: =item *
                   15199: 
1.243     albertel 15200: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15201: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15202: 
                   15203: =item *
                   15204: 
1.243     albertel 15205: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15206: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15207: 
                   15208: =item *
                   15209: 
1.243     albertel 15210: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15211: namesp ($udom and $uname are optional)
1.191     harris41 15212: 
                   15213: =item *
                   15214: 
1.702     albertel 15215: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15216: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15217: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15218: 
1.702     albertel 15219: $range should be either an integer '100' (give me the first 100
                   15220:                                            matching records)
                   15221:               or be  two integers sperated by a - with no spaces
                   15222:                  '30-50' (give me the 30th through the 50th matching
                   15223:                           records)
1.449     matthew  15224: =item *
                   15225: 
                   15226: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15227: $store can be a scalar, an array reference, or if the amount to be 
                   15228: incremented is > 1, a hash reference.
                   15229: 
                   15230: ($udom and $uname are optional)
1.191     harris41 15231: 
                   15232: =item *
                   15233: 
1.243     albertel 15234: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15235: ($udom and $uname are optional)
1.191     harris41 15236: 
                   15237: =item *
                   15238: 
1.243     albertel 15239: cput($namespace,$storehash,$udom,$uname) : critical put
                   15240: ($udom and $uname are optional)
1.191     harris41 15241: 
                   15242: =item *
                   15243: 
1.748     albertel 15244: newput($namespace,$storehash,$udom,$uname) :
                   15245: 
                   15246: Attempts to store the items in the $storehash, but only if they don't
                   15247: currently exist, if this succeeds you can be certain that you have 
                   15248: successfully created a new key value pair in the $namespace db.
                   15249: 
                   15250: 
                   15251: Args:
                   15252:  $namespace: name of database to store values to
                   15253:  $storehash: hashref to store to the db
                   15254:  $udom: (optional) domain of user containing the db
                   15255:  $uname: (optional) name of user caontaining the db
                   15256: 
                   15257: Returns:
                   15258:  'ok' -> succeeded in storing all keys of $storehash
                   15259:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15260:                         least <key> already existed in the db (other
                   15261:                         requested keys may also already exist)
1.967     bisitz   15262:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15263:  'con_lost' -> unable to contact request server
                   15264:  'refused' -> action was not allowed by remote machine
                   15265: 
                   15266: 
                   15267: =item *
                   15268: 
1.243     albertel 15269: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15270: reference filled in from namesp (encrypts the return communication)
                   15271: ($udom and $uname are optional)
1.191     harris41 15272: 
                   15273: =item *
                   15274: 
1.243     albertel 15275: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15276: critical subroutine
                   15277: 
1.806     raeburn  15278: =item *
                   15279: 
1.860     raeburn  15280: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15281: array reference filled in from namespace found in domain level on either
                   15282: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15283: 
                   15284: =item *
                   15285: 
1.860     raeburn  15286: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15287: domain level either on specified domain server ($uhome) or primary domain 
                   15288: server ($udom and $uhome are optional)
1.806     raeburn  15289: 
1.943     raeburn  15290: =item * 
                   15291: 
1.1172.2.35  raeburn  15292: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   15293: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15294: the target domain.
                   15295: 
                   15296: May also include additional key => value pairs for the following groups:
                   15297: 
                   15298: =over
                   15299: 
                   15300: =item
                   15301: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15302: 
                   15303: =over
                   15304: 
                   15305: =item defaultquota, authorquota
                   15306: 
                   15307: =back
                   15308: 
                   15309: =item
                   15310: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15311: portfolio for users).
                   15312: 
                   15313: =over
                   15314: 
                   15315: =item
                   15316: aboutme, blog, webdav, portfolio
                   15317: 
                   15318: =back
                   15319: 
                   15320: =item
                   15321: requestcourses: ability to request courses, and how requests are processed.
                   15322: 
                   15323: =over
                   15324: 
                   15325: =item
1.1172.2.37  raeburn  15326: official, unofficial, community, textbook
1.1172.2.35  raeburn  15327: 
                   15328: =back
                   15329: 
                   15330: =item
                   15331: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15332: 
                   15333: =over
                   15334: 
                   15335: =item
1.1172.2.44  raeburn  15336: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  15337: 
                   15338: =back
                   15339: 
                   15340: =item
                   15341: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15342: for course's uploaded content.
                   15343: 
                   15344: =over
                   15345: 
                   15346: =item
1.1172.2.68  raeburn  15347: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   15348: communityquota, textbookquota
1.1172.2.35  raeburn  15349: 
                   15350: =back
                   15351: 
                   15352: =item
                   15353: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15354: on your servers.
                   15355: 
                   15356: =over
                   15357: 
                   15358: =item
                   15359: remotesessions, hostedsessions
                   15360: 
                   15361: =back
                   15362: 
                   15363: =back
                   15364: 
                   15365: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15366: utility to create a configuration.db file on a domain's primary library server
                   15367: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15368: -- corresponding values are authentication type (internal, krb4, krb5,
                   15369: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   15370: will be available. Values are retrieved from cache (if current), unless the
                   15371: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15372: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15373: 
                   15374: Typical usage:
1.943     raeburn  15375: 
1.1172.2.35  raeburn  15376: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15377: 
1.243     albertel 15378: =back
                   15379: 
                   15380: =head2 Network Status Functions
                   15381: 
                   15382: =over 4
1.191     harris41 15383: 
                   15384: =item *
                   15385: 
1.1137    raeburn  15386: dirlist() : return directory list based on URI (first arg).
                   15387: 
                   15388: Inputs: 1 required, 5 optional.
                   15389: 
                   15390: =over
                   15391: 
                   15392: =item 
                   15393: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15394: 
                   15395: =item
                   15396: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15397: 
                   15398: =item
                   15399: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15400: 
                   15401: =item
                   15402: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15403: 
                   15404: =item
                   15405: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15406: 
                   15407: =item 
                   15408: $alternateRoot - path to prepend in place of path from $uri.
                   15409: 
                   15410: =back
                   15411: 
                   15412: Returns: Array of up to two items.
                   15413: 
                   15414: =over
                   15415: 
                   15416: a reference to an array of files/subdirectories
                   15417: 
                   15418: =over
                   15419: 
                   15420: Each element in the array of files/subdirectories is a & separated list of
                   15421: item name and the result of running stat on the item.  If dirlist was requested
                   15422: for a file instead of a directory, the item name will be ''. For a directory 
                   15423: listing, if the item is a metadata file, the element will end &N&M 
                   15424: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15425: default copyright set (1).  
                   15426: 
                   15427: =back
                   15428: 
                   15429: a scalar containing error condition (if encountered).
                   15430: 
                   15431: =over
                   15432: 
                   15433: =item 
                   15434: no_host (no homeserver identified for $username:$domain).
                   15435: 
                   15436: =item 
                   15437: no_such_host (server contacted for listing not identified as valid host).
                   15438: 
                   15439: =item 
                   15440: con_lost (connection to remote server failed).
                   15441: 
                   15442: =item 
                   15443: refused (invalid $username:$domain received on lond side).
                   15444: 
                   15445: =item 
                   15446: no_such_dir (directory at specified path on lond side does not exist). 
                   15447: 
                   15448: =item 
                   15449: empty (directory at specified path on lond side is empty).
                   15450: 
                   15451: =over
                   15452: 
                   15453: This is currently not encountered because the &ls3, &ls2, 
                   15454: &ls (_handler) routines on the lond side do not filter out
                   15455: . and .. from a directory listing. 
                   15456: 
                   15457: =back
                   15458: 
                   15459: =back
                   15460: 
                   15461: =back
1.191     harris41 15462: 
                   15463: =item *
                   15464: 
1.243     albertel 15465: spareserver() : find server with least workload from spare.tab
                   15466: 
1.986     foxr     15467: 
                   15468: =item *
                   15469: 
                   15470: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15471: if there is no corresponding loncapa host.
                   15472: 
1.243     albertel 15473: =back
                   15474: 
1.986     foxr     15475: 
1.243     albertel 15476: =head2 Apache Request
                   15477: 
                   15478: =over 4
1.191     harris41 15479: 
                   15480: =item *
                   15481: 
1.243     albertel 15482: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15483: localhost, posts hash
                   15484: 
                   15485: =back
                   15486: 
                   15487: =head2 Data to String to Data
                   15488: 
                   15489: =over 4
1.191     harris41 15490: 
                   15491: =item *
                   15492: 
1.243     albertel 15493: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15494: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15495: 
                   15496: =item *
                   15497: 
1.243     albertel 15498: hashref2str($hashref) : convert a hashref into a string complete with
                   15499: escaping and '=' and '&' separators, supports elements that are
                   15500: arrayrefs and hashrefs
1.191     harris41 15501: 
                   15502: =item *
                   15503: 
1.243     albertel 15504: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15505: with escaping and '&' separators, supports elements that are arrayrefs
                   15506: and hashrefs
1.191     harris41 15507: 
                   15508: =item *
                   15509: 
1.243     albertel 15510: str2hash($string) : convert string to hash using unescaping and
                   15511: splitting on '=' and '&', supports elements that are arrayrefs and
                   15512: hashrefs
1.191     harris41 15513: 
                   15514: =item *
                   15515: 
1.243     albertel 15516: str2array($string) : convert string to hash using unescaping and
                   15517: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15518: 
                   15519: =back
                   15520: 
                   15521: =head2 Logging Routines
                   15522: 
                   15523: 
                   15524: These routines allow one to make log messages in the lonnet.log and
                   15525: lonnet.perm logfiles.
1.191     harris41 15526: 
1.1119    foxr     15527: =over 4
                   15528: 
1.191     harris41 15529: =item *
                   15530: 
1.243     albertel 15531: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15532: 
                   15533: =item *
                   15534: 
1.243     albertel 15535: logthis() : append message to the normal lonnet.log file, it gets
                   15536: preiodically rolled over and deleted.
1.191     harris41 15537: 
                   15538: =item *
                   15539: 
1.243     albertel 15540: logperm() : append a permanent message to lonnet.perm.log, this log
                   15541: file never gets deleted by any automated portion of the system, only
                   15542: messages of critical importance should go in here.
                   15543: 
1.1119    foxr     15544: 
1.243     albertel 15545: =back
                   15546: 
                   15547: =head2 General File Helper Routines
                   15548: 
                   15549: =over 4
1.191     harris41 15550: 
                   15551: =item *
                   15552: 
1.481     raeburn  15553: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15554: (a) files in /uploaded
                   15555:   (i) If a local copy of the file exists - 
                   15556:       compares modification date of local copy with last-modified date for 
                   15557:       definitive version stored on home server for course. If local copy is 
                   15558:       stale, requests a new version from the home server and stores it. 
                   15559:       If the original has been removed from the home server, then local copy 
                   15560:       is unlinked.
                   15561:   (ii) If local copy does not exist -
                   15562:       requests the file from the home server and stores it. 
                   15563:   
                   15564:   If $caller is 'uploadrep':  
                   15565:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15566:     for request for files originally uploaded via DOCS. 
                   15567:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15568:   
                   15569:   Otherwise:
                   15570:      This indicates a call from the content generation phase of the request.
                   15571:      -  returns the entire contents of the file or -1.
                   15572:      
                   15573: (b) files in /res
                   15574:    - returns the entire contents of a file or -1; 
                   15575:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15576: 
1.712     albertel 15577: 
                   15578: =item *
                   15579: 
                   15580: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15581:                   reference
                   15582: 
                   15583: returns either a stat() list of data about the file or an empty list
                   15584: if the file doesn't exist or couldn't find out about it (connection
                   15585: problems or user unknown)
                   15586: 
1.191     harris41 15587: =item *
                   15588: 
1.243     albertel 15589: filelocation($dir,$file) : returns file system location of a file
                   15590: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15591: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15592: and a file of ../bob will become /a/bob)
1.191     harris41 15593: 
                   15594: =item *
                   15595: 
                   15596: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15597: filelocation except for hrefs
                   15598: 
                   15599: =item *
                   15600: 
1.1172.2.49  raeburn  15601: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15602: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15603: 
1.243     albertel 15604: =back
                   15605: 
1.608     albertel 15606: =head2 Usererfile file routines (/uploaded*)
                   15607: 
                   15608: =over 4
                   15609: 
                   15610: =item *
                   15611: 
                   15612: userfileupload(): main rotine for putting a file in a user or course's
                   15613:                   filespace, arguments are,
                   15614: 
1.620     albertel 15615:  formname - required - this is the name of the element in $env where the
1.608     albertel 15616:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15617:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15618:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15619:  context - if coursedoc, store the file in the course of the active role
                   15620:              of the current user; 
                   15621:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15622:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15623:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15624:          if undefined, it will be placed in "unknown"
                   15625: 
                   15626:  (This routine calls clean_filename() to remove any dangerous
                   15627:  characters from the filename, and then calls finuserfileupload() to
                   15628:  complete the transaction)
                   15629: 
                   15630:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15631:  and /adm/notfound.html if unsuccessful
                   15632: 
                   15633: =item *
                   15634: 
                   15635: clean_filename(): routine for cleaing a filename up for storage in
                   15636:                  userfile space, argument is:
                   15637: 
                   15638:  filename - proposed filename
                   15639: 
                   15640: returns: the new clean filename
                   15641: 
                   15642: =item *
                   15643: 
1.1090    raeburn  15644: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15645: userspace, probably shouldn't be called directly
                   15646: 
                   15647:   docuname: username or courseid of destination for the file
                   15648:   docudom: domain of user/course of destination for the file
                   15649:   formname: same as for userfileupload()
1.1090    raeburn  15650:   fname: filename (including subdirectories) for the file
                   15651:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  15652:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  15653:   allfiles: reference to hash used to store objects found by parser
                   15654:   codebase: reference to hash used for codebases of java objects found by parser
                   15655:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15656:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15657:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15658:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15659:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15660:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15661:   mimetype: reference to scalar to accommodate mime type determined
                   15662:             from File::MMagic if $parser = parse.
1.608     albertel 15663: 
                   15664:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15665:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15666:  was 'overwrite').
                   15667:  
1.608     albertel 15668: 
                   15669: =item *
                   15670: 
                   15671: renameuserfile(): renames an existing userfile to a new name
                   15672: 
                   15673:   Args:
                   15674:    docuname: username or courseid of destination for the file
                   15675:    docudom: domain of user/course of destination for the file
                   15676:    old: current file name (including any subdirs under userfiles)
                   15677:    new: desired file name (including any subdirs under userfiles)
                   15678: 
                   15679: =item *
                   15680: 
                   15681: mkdiruserfile(): creates a directory is a userfiles dir
                   15682: 
                   15683:   Args:
                   15684:    docuname: username or courseid of destination for the file
                   15685:    docudom: domain of user/course of destination for the file
                   15686:    dir: dir to create (including any subdirs under userfiles)
                   15687: 
                   15688: =item *
                   15689: 
                   15690: removeuserfile(): removes a file that exists in userfiles
                   15691: 
                   15692:   Args:
                   15693:    docuname: username or courseid of destination for the file
                   15694:    docudom: domain of user/course of destination for the file
                   15695:    fname: filname to delete (including any subdirs under userfiles)
                   15696: 
                   15697: =item *
                   15698: 
                   15699: removeuploadedurl(): convience function for removeuserfile()
                   15700: 
                   15701:   Args:
                   15702:    url:  a full /uploaded/... url to delete
                   15703: 
1.747     albertel 15704: =item * 
                   15705: 
                   15706: get_portfile_permissions():
                   15707:   Args:
                   15708:     domain: domain of user or course contain the portfolio files
                   15709:     user: name of user or num of course contain the portfolio files
                   15710:   Returns:
                   15711:     hashref of a dump of the proper file_permissions.db
                   15712:    
                   15713: 
                   15714: =item * 
                   15715: 
                   15716: get_access_controls():
                   15717: 
                   15718: Args:
                   15719:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15720:   group: (optional) the group you want the files associated with
                   15721:   file: (optional) the file you want access info on
                   15722: 
                   15723: Returns:
1.749     raeburn  15724:     a hash (keys are file names) of hashes containing
                   15725:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15726:         values are XML containing access control settings (see below) 
1.747     albertel 15727: 
                   15728: Internal notes:
                   15729: 
1.749     raeburn  15730:  access controls are stored in file_permissions.db as key=value pairs.
                   15731:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15732:         where scope -> public,guest,course,group,domains or users.
                   15733:               end -> UNIX time for end of access (0 -> no end date)
                   15734:               start -> UNIX time for start of access
                   15735: 
                   15736:     value -> XML description of access control
                   15737:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15738:             <start></start>
                   15739:             <end></end>
                   15740: 
                   15741:             <password></password>  for scope type = guest
                   15742: 
                   15743:             <domain></domain>     for scope type = course or group
                   15744:             <number></number>
                   15745:             <roles id="">
                   15746:              <role></role>
                   15747:              <access></access>
                   15748:              <section></section>
                   15749:              <group></group>
                   15750:             </roles>
                   15751: 
                   15752:             <dom></dom>         for scope type = domains
                   15753: 
                   15754:             <users>             for scope type = users
                   15755:              <user>
                   15756:               <uname></uname>
                   15757:               <udom></udom>
                   15758:              </user>
                   15759:             </users>
                   15760:            </scope> 
                   15761:               
                   15762:  Access data is also aggregated for each file in an additional key=value pair:
                   15763:  key -> path to file/file_name\0accesscontrol 
                   15764:  value -> reference to hash
                   15765:           hash contains key = value pairs
                   15766:           where key = uniqueID:scope_end_start
                   15767:                 value = UNIX time record was last updated
                   15768: 
                   15769:           Used to improve speed of look-ups of access controls for each file.  
                   15770:  
                   15771:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15772: 
1.1172.2.13  raeburn  15773: =item *
                   15774: 
1.749     raeburn  15775: modify_access_controls():
                   15776: 
                   15777: Modifies access controls for a portfolio file
                   15778: Args
                   15779: 1. file name
                   15780: 2. reference to hash of required changes,
                   15781: 3. domain
                   15782: 4. username
                   15783:   where domain,username are the domain of the portfolio owner 
                   15784:   (either a user or a course) 
                   15785: 
                   15786: Returns:
                   15787: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15788: 2. result of deletions ('ok' or 'error', with error message).
                   15789: 3. reference to hash of any new or updated access controls.
                   15790: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15791:    key = integer (inbound ID)
1.1172.2.13  raeburn  15792:    value = uniqueID
                   15793: 
                   15794: =item *
                   15795: 
                   15796: get_timebased_id():
                   15797: 
                   15798: Attempts to get a unique timestamp-based suffix for use with items added to a
                   15799: course via the Course Editor (e.g., folders, composite pages,
                   15800: group bulletin boards).
                   15801: 
                   15802: Args: (first three required; six others optional)
                   15803: 
                   15804: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15805:    docssequence, or name of group
                   15806: 
                   15807: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15808:    e.g., num, boardids
                   15809: 
                   15810: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   15811:    file will be named nohist_namespace.db
                   15812: 
                   15813: 4. cdom: domain of course; default is current course domain from %env
                   15814: 
                   15815: 5. cnum: course number; default is current course number from %env
                   15816: 
                   15817: 6. idtype: set to concat if an additional digit is to be appended to the
                   15818:    unix timestamp to form the suffix, if the plain timestamp is already
                   15819:    in use.  Default is to not do this, but simply increment the unix
                   15820:    timestamp by 1 until a unique key is obtained.
                   15821: 
                   15822: 7. who: holder of locking key; defaults to user:domain for user.
                   15823: 
                   15824: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   15825:    retrying); default is 3.
                   15826: 
                   15827: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   15828: 
                   15829: Returns:
                   15830: 
                   15831: 1. suffix obtained (numeric)
                   15832: 
                   15833: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15834: 
                   15835: 3. error: contains (localized) error message if an error occurred.
                   15836: 
1.747     albertel 15837: 
1.608     albertel 15838: =back
                   15839: 
1.243     albertel 15840: =head2 HTTP Helper Routines
                   15841: 
                   15842: =over 4
                   15843: 
1.191     harris41 15844: =item *
                   15845: 
                   15846: escape() : unpack non-word characters into CGI-compatible hex codes
                   15847: 
                   15848: =item *
                   15849: 
                   15850: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15851: 
1.243     albertel 15852: =back
                   15853: 
                   15854: =head1 PRIVATE SUBROUTINES
                   15855: 
                   15856: =head2 Underlying communication routines (Shouldn't call)
                   15857: 
                   15858: =over 4
                   15859: 
                   15860: =item *
                   15861: 
                   15862: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15863: 
                   15864: =item *
                   15865: 
                   15866: reply() : uses subreply to send a message to remote machine, logs all failures
                   15867: 
                   15868: =item *
                   15869: 
                   15870: critical() : passes a critical message to another server; if cannot
                   15871: get through then place message in connection buffer directory and
                   15872: returns con_delayed, if incapable of saving message, returns
                   15873: con_failed
                   15874: 
                   15875: =item *
                   15876: 
                   15877: reconlonc() : tries to reconnect lonc client processes.
                   15878: 
                   15879: =back
                   15880: 
                   15881: =head2 Resource Access Logging
                   15882: 
                   15883: =over 4
                   15884: 
                   15885: =item *
                   15886: 
                   15887: flushcourselogs() : flush (save) buffer logs and access logs
                   15888: 
                   15889: =item *
                   15890: 
                   15891: courselog($what) : save message for course in hash
                   15892: 
                   15893: =item *
                   15894: 
                   15895: courseacclog($what) : save message for course using &courselog().  Perform
                   15896: special processing for specific resource types (problems, exams, quizzes, etc).
                   15897: 
1.191     harris41 15898: =item *
                   15899: 
                   15900: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15901: as a PerlChildExitHandler
1.243     albertel 15902: 
                   15903: =back
                   15904: 
                   15905: =head2 Other
                   15906: 
                   15907: =over 4
                   15908: 
                   15909: =item *
                   15910: 
                   15911: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15912: 
                   15913: =back
                   15914: 
                   15915: =cut
1.877     foxr     15916: 

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