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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.118.  .7(raebu    4:20): # $Id: lonnet.pm,v 1.1172.2.118.2.6 2020/07/20 12:45:31 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.9  raeburn   128:         my $logentry = {
                    129:                          $id => {
                    130:                                   'exe_uname' => $env{'user.name'},
                    131:                                   'exe_udom'  => $env{'user.domain'},
                    132:                                   'exe_time'  => $now,
                    133:                                   'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    134:                                   'delflag'   => $delflag,
                    135:                                   'logentry'  => $storehash,
                    136:                                   'uname'     => $uname,
                    137:                                   'udom'      => $udom,
                    138:                                 }
                    139:                        };
                    140:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       141:     }
                    142: }
1.1       albertel  143: 
1.163     harris41  144: sub logtouch {
                    145:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  146:     unless (-e "$execdir/logs/lonnet.log") {	
1.1172.2.96  raeburn   147: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  148: 	close $fh;
                    149:     }
                    150:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    151:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    152: }
                    153: 
1.1       albertel  154: sub logthis {
                    155:     my $message=shift;
                    156:     my $execdir=$perlvar{'lonDaemons'};
                    157:     my $now=time;
                    158:     my $local=localtime($now);
1.1172.2.96  raeburn   159:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      160: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    161: 	print $fh $logstring;
1.448     albertel  162: 	close($fh);
                    163:     }
1.1       albertel  164:     return 1;
                    165: }
                    166: 
                    167: sub logperm {
                    168:     my $message=shift;
                    169:     my $execdir=$perlvar{'lonDaemons'};
                    170:     my $now=time;
                    171:     my $local=localtime($now);
1.1172.2.96  raeburn   172:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  173: 	print $fh "$now:$message:$local\n";
                    174: 	close($fh);
                    175:     }
1.1       albertel  176:     return 1;
                    177: }
                    178: 
1.850     albertel  179: sub create_connection {
1.853     albertel  180:     my ($hostname,$lonid) = @_;
1.851     albertel  181:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  182: 				     Type    => SOCK_STREAM,
                    183: 				     Timeout => 10);
                    184:     return 0 if (!$client);
1.890     albertel  185:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  186:     my $result = <$client>;
                    187:     chomp($result);
                    188:     return 1 if ($result eq 'done');
                    189:     return 0;
                    190: }
                    191: 
1.983     raeburn   192: sub get_server_timezone {
                    193:     my ($cnum,$cdom) = @_;
                    194:     my $home=&homeserver($cnum,$cdom);
                    195:     if ($home ne 'no_host') {
                    196:         my $cachetime = 24*3600;
                    197:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    198:         if (defined($cached)) {
                    199:             return $timezone;
                    200:         } else {
                    201:             my $timezone = &reply('servertimezone',$home);
                    202:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    203:         }
                    204:     }
                    205: }
1.850     albertel  206: 
1.1106    raeburn   207: sub get_server_distarch {
                    208:     my ($lonhost,$ignore_cache) = @_;
                    209:     if (defined($lonhost)) {
                    210:         if (!defined(&hostname($lonhost))) {
                    211:             return;
                    212:         }
                    213:         my $cachetime = 12*3600;
                    214:         if (!$ignore_cache) {
                    215:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    216:             if (defined($cached)) {
                    217:                 return $distarch;
                    218:             }
                    219:         }
                    220:         my $rep = &reply('serverdistarch',$lonhost);
                    221:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    222:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    223:                 $rep eq '') {
                    224:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    225:         }
                    226:     }
                    227:     return;
                    228: }
                    229: 
1.993     raeburn   230: sub get_server_loncaparev {
1.1073    raeburn   231:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   232:     if (defined($lonhost)) {
                    233:         if (!defined(&hostname($lonhost))) {
                    234:             undef($lonhost);
                    235:         }
                    236:     }
                    237:     if (!defined($lonhost)) {
                    238:         if (defined(&domain($dom,'primary'))) {
                    239:             $lonhost=&domain($dom,'primary');
                    240:             if ($lonhost eq 'no_host') {
                    241:                 undef($lonhost);
                    242:             }
                    243:         }
                    244:     }
                    245:     if (defined($lonhost)) {
1.1073    raeburn   246:         my $cachetime = 12*3600;
                    247:         if (!$ignore_cache) {
                    248:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    249:             if (defined($cached)) {
                    250:                 return $loncaparev;
                    251:             }
                    252:         }
                    253:         my ($answer,$loncaparev);
                    254:         my @ids=&current_machine_ids();
                    255:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    256:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   257:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   258:                 $loncaparev = $1;
                    259:             }
                    260:         } else {
                    261:             $answer = &reply('serverloncaparev',$lonhost);
                    262:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    263:                 if ($caller eq 'loncron') {
                    264:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   265:                     $ua->timeout(4);
1.1172.2.118.  .3(raebu  266:20):                     my $hostname = &hostname($lonhost);
1.1073    raeburn   267:                     my $protocol = $protocol{$lonhost};
                    268:                     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu  269:20):                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073    raeburn   270:                     my $request=new HTTP::Request('GET',$url);
                    271:                     my $response=$ua->request($request);
                    272:                     unless ($response->is_error()) {
                    273:                         my $content = $response->content;
1.1081    raeburn   274:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   275:                             $loncaparev = $1;
                    276:                         }
                    277:                     }
                    278:                 } else {
                    279:                     $loncaparev = $loncaparevs{$lonhost};
                    280:                 }
1.1081    raeburn   281:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   282:                 $loncaparev = $1;
                    283:             }
1.993     raeburn   284:         }
1.1073    raeburn   285:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   286:     }
                    287: }
                    288: 
1.1074    raeburn   289: sub get_server_homeID {
                    290:     my ($hostname,$ignore_cache,$caller) = @_;
                    291:     unless ($ignore_cache) {
                    292:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    293:         if (defined($cached)) {
                    294:             return $serverhomeID;
                    295:         }
                    296:     }
                    297:     my $cachetime = 12*3600;
                    298:     my $serverhomeID;
                    299:     if ($caller eq 'loncron') { 
                    300:         my @machine_ids = &machine_ids($hostname);
                    301:         foreach my $id (@machine_ids) {
                    302:             my $response = &reply('serverhomeID',$id);
                    303:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    304:                 $serverhomeID = $response;
                    305:                 last;
                    306:             }
                    307:         }
                    308:         if ($serverhomeID eq '') {
                    309:             $serverhomeID = $machine_ids[-1];
                    310:         }
                    311:     } else {
                    312:         $serverhomeID = $serverhomeIDs{$hostname};
                    313:     }
                    314:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    315: }
                    316: 
1.1121    raeburn   317: sub get_remote_globals {
                    318:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   319:     my ($result,%returnhash,%whatneeded);
                    320:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   321:         foreach my $what (sort(keys(%{$whathash}))) {
                    322:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   323:             my ($response,$cached);
1.1121    raeburn   324:             unless ($ignore_cache) {
1.1125    raeburn   325:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   326:             }
                    327:             if (defined($cached)) {
1.1125    raeburn   328:                 $returnhash{$what} = $response;
1.1121    raeburn   329:             } else {
1.1125    raeburn   330:                 $whatneeded{$what} = 1;
1.1121    raeburn   331:             }
                    332:         }
1.1125    raeburn   333:         if (keys(%whatneeded) == 0) {
                    334:             $result = 'ok';
                    335:         } else {
1.1121    raeburn   336:             my $requested = &freeze_escape(\%whatneeded);
                    337:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   338:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    339:                 ($rep eq 'unknown_cmd')) {
                    340:                 $result = $rep;
                    341:             } else {
                    342:                 $result = 'ok';
1.1121    raeburn   343:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   344:                 foreach my $item (@pairs) {
                    345:                     my ($key,$value)=split(/=/,$item,2);
                    346:                     my $what = &unescape($key);
                    347:                     my $hashid = $lonhost.'-'.$what;
                    348:                     $returnhash{$what}=&thaw_unescape($value);
                    349:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   350:                 }
                    351:             }
                    352:         }
                    353:     }
1.1125    raeburn   354:     return ($result,\%returnhash);
1.1121    raeburn   355: }
                    356: 
1.1124    raeburn   357: sub remote_devalidate_cache {
1.1172.2.35  raeburn   358:     my ($lonhost,$cachekeys) = @_;
                    359:     my $items;
                    360:     return unless (ref($cachekeys) eq 'ARRAY');
                    361:     my $cachestr = join('&',@{$cachekeys});
                    362:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   363: }
                    364: 
1.1       albertel  365: # -------------------------------------------------- Non-critical communication
                    366: sub subreply {
                    367:     my ($cmd,$server)=@_;
1.838     albertel  368:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      369:     #
                    370:     #  With loncnew process trimming, there's a timing hole between lonc server
                    371:     #  process exit and the master server picking up the listen on the AF_UNIX
                    372:     #  socket.  In that time interval, a lock file will exist:
                    373: 
                    374:     my $lockfile=$peerfile.".lock";
                    375:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1172.2.79  raeburn   376: 	sleep(0.1);
1.549     foxr      377:     }
                    378:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      379:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      380:     #
1.550     foxr      381:     #   We'll give the connection a few tries before abandoning it.  If
                    382:     #   connection is not possible, we'll con_lost back to the client.
                    383:     #   
                    384:     my $client;
                    385:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    386: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    387: 				      Type    => SOCK_STREAM,
                    388: 				      Timeout => 10);
1.869     albertel  389: 	if ($client) {
1.550     foxr      390: 	    last;		# Connected!
1.850     albertel  391: 	} else {
1.853     albertel  392: 	    &create_connection(&hostname($server),$server);
1.550     foxr      393: 	}
1.1172.2.79  raeburn   394:         sleep(0.1);		# Try again later if failed connection.
1.550     foxr      395:     }
                    396:     my $answer;
                    397:     if ($client) {
1.704     albertel  398: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      399: 	$answer=<$client>;
                    400: 	if (!$answer) { $answer="con_lost"; }
                    401: 	chomp($answer);
                    402:     } else {
                    403: 	$answer = 'con_lost';	# Failed connection.
                    404:     }
1.1       albertel  405:     return $answer;
                    406: }
                    407: 
                    408: sub reply {
                    409:     my ($cmd,$server)=@_;
1.838     albertel  410:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  411:     my $answer=subreply($cmd,$server);
1.65      www       412:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1172.2.111  raeburn   413:         my $logged = $cmd;
                    414:         if ($cmd =~ /^encrypt:([^:]+):/) {
                    415:             my $subcmd = $1;
                    416:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
                    417:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    418:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
                    419:                 (undef,undef,my @rest) = split(/:/,$cmd);
                    420:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
                    421:                     splice(@rest,2,1,'Hidden');
                    422:                 } elsif ($subcmd eq 'passwd') {
                    423:                     splice(@rest,2,2,('Hidden','Hidden'));
                    424:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    425:                          ($subcmd eq 'autoexportgrades')) {
                    426:                     splice(@rest,3,1,'Hidden');
                    427:                 }
                    428:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
                    429:             }
                    430:         }
                    431:         &logthis("<font color=\"blue\">WARNING:".
                    432:                  " $logged to $server returned $answer</font>");
1.12      www       433:     }
1.1       albertel  434:     return $answer;
                    435: }
                    436: 
                    437: # ----------------------------------------------------------- Send USR1 to lonc
                    438: 
                    439: sub reconlonc {
1.891     albertel  440:     my ($lonid) = @_;
                    441:     if ($lonid) {
1.1172.2.72  raeburn   442:         my $hostname = &hostname($lonid);
1.891     albertel  443: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    444: 	if ($hostname && -e $peerfile) {
                    445: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    446: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    447: 					     Type    => SOCK_STREAM,
                    448: 					     Timeout => 10);
                    449: 	    if ($client) {
                    450: 		print $client ("reset_retries\n");
                    451: 		my $answer=<$client>;
                    452: 		#reset just this one.
                    453: 	    }
                    454: 	}
                    455: 	return;
                    456:     }
                    457: 
1.836     www       458:     &logthis("Trying to reconnect lonc");
1.1       albertel  459:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96  raeburn   460:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  461: 	my $loncpid=<$fh>;
                    462:         chomp($loncpid);
                    463:         if (kill 0 => $loncpid) {
                    464: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    465:             kill USR1 => $loncpid;
                    466:             sleep 1;
1.836     www       467:          } else {
1.12      www       468: 	    &logthis(
1.672     albertel  469:                "<font color=\"blue\">WARNING:".
1.12      www       470:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  471:         }
                    472:     } else {
1.836     www       473: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  474:     }
                    475: }
                    476: 
                    477: # ------------------------------------------------------ Critical communication
1.12      www       478: 
1.1       albertel  479: sub critical {
                    480:     my ($cmd,$server)=@_;
1.838     albertel  481:     unless (&hostname($server)) {
1.672     albertel  482:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       483:                " Critical message to unknown server ($server)</font>");
                    484:         return 'no_such_host';
                    485:     }
1.1       albertel  486:     my $answer=reply($cmd,$server);
                    487:     if ($answer eq 'con_lost') {
1.1172.2.72  raeburn   488: 	&reconlonc($server);
1.589     albertel  489: 	my $answer=reply($cmd,$server);
1.1       albertel  490:         if ($answer eq 'con_lost') {
                    491:             my $now=time;
                    492:             my $middlename=$cmd;
1.5       www       493:             $middlename=substr($middlename,0,16);
1.1       albertel  494:             $middlename=~s/\W//g;
                    495:             my $dfilename=
1.305     www       496:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    497:             $dumpcount++;
1.1       albertel  498:             {
1.448     albertel  499: 		my $dfh;
1.1172.2.96  raeburn   500: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  501: 		    print $dfh "$cmd\n"; 
                    502: 		    close($dfh);
                    503: 		}
1.1       albertel  504:             }
1.1172.2.79  raeburn   505:             sleep 1;
1.1       albertel  506:             my $wcmd='';
                    507:             {
1.448     albertel  508: 		my $dfh;
1.1172.2.96  raeburn   509: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  510: 		    $wcmd=<$dfh>; 
                    511: 		    close($dfh);
                    512: 		}
1.1       albertel  513:             }
                    514:             chomp($wcmd);
1.7       www       515:             if ($wcmd eq $cmd) {
1.672     albertel  516: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       517:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  518:                 &logperm("D:$server:$cmd");
                    519: 	        return 'con_delayed';
                    520:             } else {
1.672     albertel  521:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       522:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  523:                 &logperm("F:$server:$cmd");
                    524:                 return 'con_failed';
                    525:             }
                    526:         }
                    527:     }
                    528:     return $answer;
1.405     albertel  529: }
                    530: 
1.755     albertel  531: # ------------------------------------------- check if return value is an error
                    532: 
                    533: sub error {
                    534:     my ($result) = @_;
1.756     albertel  535:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  536: 	if ($2 == 2) { return undef; }
                    537: 	return $1;
                    538:     }
                    539:     return undef;
                    540: }
                    541: 
1.783     albertel  542: sub convert_and_load_session_env {
                    543:     my ($lonidsdir,$handle)=@_;
                    544:     my @profile;
                    545:     {
1.917     albertel  546: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    547: 	if (!$opened) {
1.915     albertel  548: 	    return 0;
                    549: 	}
1.783     albertel  550: 	flock($idf,LOCK_SH);
                    551: 	@profile=<$idf>;
                    552: 	close($idf);
                    553:     }
                    554:     my %temp_env;
                    555:     foreach my $line (@profile) {
1.786     albertel  556: 	if ($line !~ m/=/) {
                    557: 	    return 0;
                    558: 	}
1.783     albertel  559: 	chomp($line);
                    560: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    561: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    562:     }
                    563:     unlink("$lonidsdir/$handle.id");
                    564:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    565: 	    0640)) {
                    566: 	%disk_env = %temp_env;
                    567: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    568: 	untie(%disk_env);
                    569:     }
1.786     albertel  570:     return 1;
1.783     albertel  571: }
                    572: 
1.374     www       573: # ------------------------------------------- Transfer profile into environment
1.780     albertel  574: my $env_loaded;
                    575: sub transfer_profile_to_env {
1.788     albertel  576:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    577:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       578: 
1.720     albertel  579:     if (!defined($lonidsdir)) {
                    580: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    581:     }
                    582:     if (!defined($handle)) {
                    583:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    584:     }
                    585: 
1.786     albertel  586:     my $convert;
                    587:     {
1.917     albertel  588:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    589: 	if (!$opened) {
1.915     albertel  590: 	    return;
                    591: 	}
1.786     albertel  592: 	flock($idf,LOCK_SH);
                    593: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    594: 		&GDBM_READER(),0640)) {
                    595: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    596: 	    untie(%disk_env);
                    597: 	} else {
                    598: 	    $convert = 1;
                    599: 	}
                    600:     }
                    601:     if ($convert) {
                    602: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    603: 	    &logthis("Failed to load session, or convert session.");
                    604: 	}
1.374     www       605:     }
1.783     albertel  606: 
1.786     albertel  607:     my %remove;
1.783     albertel  608:     while ( my $envname = each(%env) ) {
1.433     matthew   609:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    610:             if ($time < time-300) {
1.783     albertel  611:                 $remove{$key}++;
1.433     matthew   612:             }
                    613:         }
                    614:     }
1.783     albertel  615: 
1.619     albertel  616:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  617:     $env_loaded=1;
1.783     albertel  618:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   619:         &delenv($expired_key);
1.374     www       620:     }
1.1       albertel  621: }
                    622: 
1.916     albertel  623: # ---------------------------------------------------- Check for valid session 
                    624: sub check_for_valid_session {
1.1172.2.96  raeburn   625:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  626:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1172.2.108  raeburn   627:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
1.1155    raeburn   628:     if ($name eq 'lonDAV') {
                    629:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    630:     } else {
                    631:         $lonidsdir=$r->dir_config('lonIDsDir');
1.1172.2.108  raeburn   632:         if ($name eq '') {
                    633:             $name = 'lonID';
                    634:         }
                    635:     }
                    636:     if ($name eq 'lonID') {
                    637:         $secure = 'lonSID';
                    638:         $linkname = 'lonLinkID';
                    639:         $pubname = 'lonPubID';
                    640:         if (exists($cookies{$secure})) {
                    641:             $lonid=$cookies{$secure};
                    642:         } elsif (exists($cookies{$name})) {
                    643:             $lonid=$cookies{$name};
                    644:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
                    645:             $lonid=$cookies{$linkname};
                    646:         } elsif (exists($cookies{$pubname})) {
                    647:             $lonid=$cookies{$pubname};
                    648:         }
                    649:     } else {
                    650:         $lonid=$cookies{$name};
                    651:     }
                    652:     return undef if (!$lonid);
                    653: 
                    654:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    655:     if (-l "$lonidsdir/$handle.id") {
                    656:         my $link = readlink("$lonidsdir/$handle.id");
                    657:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    658:             $handle = $1;
                    659:         }
1.1155    raeburn   660:     }
1.1172.2.96  raeburn   661:     if (!-e "$lonidsdir/$handle.id") {
                    662:         if ((ref($domref)) && ($name eq 'lonID') &&
                    663:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    664:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    665:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    666:                 $$domref = $possudom;
                    667:             }
                    668:         }
                    669:         return undef;
                    670:     }
1.916     albertel  671: 
1.917     albertel  672:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    673:     return undef if (!$opened);
1.916     albertel  674: 
                    675:     flock($idf,LOCK_SH);
                    676:     my %disk_env;
                    677:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    678: 	    &GDBM_READER(),0640)) {
                    679: 	return undef;	
                    680:     }
                    681: 
                    682:     if (!defined($disk_env{'user.name'})
                    683: 	|| !defined($disk_env{'user.domain'})) {
1.1172.2.107  raeburn   684:         untie(%disk_env);
1.916     albertel  685: 	return undef;
                    686:     }
1.1172.2.18  raeburn   687: 
1.1172.2.36  raeburn   688:     if (ref($userhashref) eq 'HASH') {
                    689:         $userhashref->{'name'} = $disk_env{'user.name'};
                    690:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18  raeburn   691:     }
1.1172.2.107  raeburn   692:     untie(%disk_env);
1.1172.2.18  raeburn   693: 
1.916     albertel  694:     return $handle;
                    695: }
                    696: 
1.830     albertel  697: sub timed_flock {
                    698:     my ($file,$lock_type) = @_;
                    699:     my $failed=0;
                    700:     eval {
                    701: 	local $SIG{__DIE__}='DEFAULT';
                    702: 	local $SIG{ALRM}=sub {
                    703: 	    $failed=1;
                    704: 	    die("failed lock");
                    705: 	};
                    706: 	alarm(13);
                    707: 	flock($file,$lock_type);
                    708: 	alarm(0);
                    709:     };
                    710:     if ($failed) {
                    711: 	return undef;
                    712:     } else {
                    713: 	return 1;
                    714:     }
                    715: }
                    716: 
1.1172.2.107  raeburn   717: sub get_sessionfile_vars {
                    718:     my ($handle,$lonidsdir,$storearr) = @_;
                    719:     my %returnhash;
                    720:     unless (ref($storearr) eq 'ARRAY') {
                    721:         return %returnhash;
                    722:     }
                    723:     if (-l "$lonidsdir/$handle.id") {
                    724:         my $link = readlink("$lonidsdir/$handle.id");
                    725:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    726:             $handle = $1;
                    727:         }
                    728:     }
                    729:     if ((-e "$lonidsdir/$handle.id") &&
                    730:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    731:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    732:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    733:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    734:                 flock($idf,LOCK_SH);
                    735:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    736:                         &GDBM_READER(),0640)) {
                    737:                     foreach my $item (@{$storearr}) {
                    738:                         $returnhash{$item} = $disk_env{$item};
                    739:                     }
                    740:                     untie(%disk_env);
                    741:                 }
                    742:             }
                    743:         }
                    744:     }
                    745:     return %returnhash;
                    746: }
                    747: 
1.5       www       748: # ---------------------------------------------------------- Append Environment
                    749: 
                    750: sub appenv {
1.949     raeburn   751:     my ($newenv,$roles) = @_;
                    752:     if (ref($newenv) eq 'HASH') {
                    753:         foreach my $key (keys(%{$newenv})) {
                    754:             my $refused = 0;
                    755: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    756:                 $refused = 1;
                    757:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   758:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   759:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    760:                         $refused = 0;
                    761:                     }
                    762:                 }
                    763:             }
                    764:             if ($refused) {
                    765:                 &logthis("<font color=\"blue\">WARNING: ".
                    766:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    767:                          .'</font>');
                    768: 	        delete($newenv->{$key});
                    769:             } else {
                    770:                 $env{$key}=$newenv->{$key};
                    771:             }
                    772:         }
1.1172.2.96  raeburn   773:         my $lonids = $perlvar{'lonIDsDir'};
                    774:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    775:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    776:             if ($opened
                    777: 	        && &timed_flock($env_file,LOCK_EX)
                    778: 	        &&
                    779: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    780: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    781: 	        while (my ($key,$value) = each(%{$newenv})) {
                    782: 	            $disk_env{$key} = $value;
                    783: 	        }
                    784: 	        untie(%disk_env);
                    785:             }
1.35      www       786:         }
1.191     harris41  787:     }
1.56      www       788:     return 'ok';
                    789: }
                    790: # ----------------------------------------------------- Delete from Environment
                    791: 
                    792: sub delenv {
1.1104    raeburn   793:     my ($delthis,$regexp,$roles) = @_;
                    794:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    795:         my $refused = 1;
                    796:         if (ref($roles) eq 'ARRAY') {
                    797:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    798:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    799:                 $refused = 0;
                    800:             }
                    801:         }
                    802:         if ($refused) {
                    803:             &logthis("<font color=\"blue\">WARNING: ".
                    804:                      "Attempt to delete from environment ".$delthis);
                    805:             return 'error';
                    806:         }
1.56      www       807:     }
1.917     albertel  808:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    809:     if ($opened
1.915     albertel  810: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  811: 	&&
                    812: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    813: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  814: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   815: 	    if ($regexp) {
                    816:                 if ($key=~/^$delthis/) {
                    817:                     delete($env{$key});
                    818:                     delete($disk_env{$key});
                    819:                 } 
                    820:             } else {
                    821:                 if ($key=~/^\Q$delthis\E/) {
                    822: 		    delete($env{$key});
                    823: 		    delete($disk_env{$key});
                    824: 	        }
                    825:             }
1.448     albertel  826: 	}
1.783     albertel  827: 	untie(%disk_env);
1.5       www       828:     }
                    829:     return 'ok';
1.369     albertel  830: }
                    831: 
1.790     albertel  832: sub get_env_multiple {
                    833:     my ($name) = @_;
                    834:     my @values;
                    835:     if (defined($env{$name})) {
                    836:         # exists is it an array
                    837:         if (ref($env{$name})) {
                    838:             @values=@{ $env{$name} };
                    839:         } else {
                    840:             $values[0]=$env{$name};
                    841:         }
                    842:     }
                    843:     return(@values);
                    844: }
                    845: 
1.958     www       846: # ------------------------------------------------------------------- Locking
                    847: 
                    848: sub set_lock {
                    849:     my ($text)=@_;
                    850:     $locknum++;
                    851:     my $id=$$.'-'.$locknum;
                    852:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    853:              'session.lock.'.$id => $text});
                    854:     return $id;
                    855: }
                    856: 
                    857: sub get_locks {
                    858:     my $num=0;
                    859:     my %texts=();
                    860:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    861:        if ($lock=~/\w/) {
                    862:           $num++;
                    863:           $texts{$lock}=$env{'session.lock.'.$lock};
                    864:        }
                    865:    }
                    866:    return ($num,%texts);
                    867: }
                    868: 
                    869: sub remove_lock {
                    870:     my ($id)=@_;
                    871:     my $newlocks='';
                    872:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    873:        if (($lock=~/\w/) && ($lock ne $id)) {
                    874:           $newlocks.=','.$lock;
                    875:        }
                    876:     }
                    877:     &appenv({'session.locks' => $newlocks});
                    878:     &delenv('session.lock.'.$id);
                    879: }
                    880: 
                    881: sub remove_all_locks {
                    882:     my $activelocks=$env{'session.locks'};
                    883:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    884:        if ($lock=~/\w/) {
                    885:           &remove_lock($lock);
                    886:        }
                    887:     }
                    888: }
                    889: 
                    890: 
1.369     albertel  891: # ------------------------------------------ Find out current server userload
                    892: sub userload {
                    893:     my $numusers=0;
                    894:     {
                    895: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    896: 	my $filename;
                    897: 	my $curtime=time;
                    898: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  899: 	    next if ($filename eq '.' || $filename eq '..');
                    900: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1172.2.112  raeburn   901:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel  902: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  903: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  904: 	}
                    905: 	closedir(LONIDS);
                    906:     }
                    907:     my $userloadpercent=0;
                    908:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    909:     if ($maxuserload) {
1.371     albertel  910: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  911:     }
1.372     albertel  912:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  913:     return $userloadpercent;
1.283     www       914: }
                    915: 
1.1       albertel  916: # ------------------------------ Find server with least workload from spare.tab
1.11      www       917: 
1.1       albertel  918: sub spareserver {
1.1083    raeburn   919:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  920:     my $spare_server;
1.370     albertel  921:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  922:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    923:                                                      :  $userloadpercent;
1.1083    raeburn   924:     my ($uint_dom,$remotesessions);
                    925:     if (($udom ne '') && (&domain($udom) ne '')) {
                    926:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    927:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    928:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    929:         $remotesessions = $udomdefaults{'remotesessions'};
                    930:     }
1.1123    raeburn   931:     my $spareshash = &this_host_spares($udom);
                    932:     if (ref($spareshash) eq 'HASH') {
                    933:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    934:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62  raeburn   935:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    936:                                              $try_server));
1.1123    raeburn   937: 	        ($spare_server, $lowest_load) =
                    938: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    939:             }
1.1083    raeburn   940:         }
1.784     albertel  941: 
1.1123    raeburn   942:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    943: 
                    944:         if (!$found_server) {
                    945:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    946: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62  raeburn   947:                     next unless (&spare_can_host($udom,$uint_dom,
                    948:                                                  $remotesessions,$try_server));
1.1123    raeburn   949: 	            ($spare_server, $lowest_load) =
                    950: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    951:                 }
                    952: 	    }
                    953:         }
1.784     albertel  954:     }
                    955: 
                    956:     if (!$want_server_name) {
1.1001    raeburn   957:         if (defined($spare_server)) {
                    958:             my $hostname = &hostname($spare_server);
1.1083    raeburn   959:             if (defined($hostname)) {
1.1172.2.118.  .3(raebu  960:20):                 my $protocol = 'http';
                    961:20):                 if ($protocol{$spare_server} eq 'https') {
                    962:20):                     $protocol = $protocol{$spare_server};
                    963:20):                 }
1.1001    raeburn   964: 	        $spare_server = $protocol.'://'.$hostname;
                    965:             }
                    966:         }
1.784     albertel  967:     }
                    968:     return $spare_server;
                    969: }
                    970: 
                    971: sub compare_server_load {
1.1172.2.41  raeburn   972:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    973: 
                    974:     if ($required) {
                    975:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    976:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    977:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    978:         if (($major eq '' && $minor eq '') ||
                    979:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    980:             return ($spare_server,$lowest_load);
                    981:         }
                    982:     }
1.784     albertel  983: 
                    984:     my $loadans     = &reply('load',    $try_server);
                    985:     my $userloadans = &reply('userload',$try_server);
                    986: 
                    987:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   988: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  989:     }
                    990: 
                    991:     my $load;
                    992:     if ($loadans =~ /\d/) {
                    993: 	if ($userloadans =~ /\d/) {
                    994: 	    #both are numbers, pick the bigger one
                    995: 	    $load = ($loadans > $userloadans) ? $loadans 
                    996: 		                              : $userloadans;
1.411     albertel  997: 	} else {
1.784     albertel  998: 	    $load = $loadans;
1.411     albertel  999: 	}
1.784     albertel 1000:     } else {
                   1001: 	$load = $userloadans;
                   1002:     }
                   1003: 
                   1004:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1005: 	$spare_server = $try_server;
                   1006: 	$lowest_load  = $load;
1.370     albertel 1007:     }
1.784     albertel 1008:     return ($spare_server,$lowest_load);
1.202     matthew  1009: }
1.914     albertel 1010: 
                   1011: # --------------------------- ask offload servers if user already has a session
                   1012: sub find_existing_session {
                   1013:     my ($udom,$uname) = @_;
1.1123    raeburn  1014:     my $spareshash = &this_host_spares($udom);
                   1015:     if (ref($spareshash) eq 'HASH') {
                   1016:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1017:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1018:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1019:             }
                   1020:         }
                   1021:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1022:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1023:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1024:             }
                   1025:         }
1.914     albertel 1026:     }
                   1027:     return;
                   1028: }
                   1029: 
1.1172.2.107  raeburn  1030: # check if user's browser sent load balancer cookie and server still has session
                   1031: # and is not overloaded.
                   1032: sub check_for_balancer_cookie {
                   1033:     my ($r,$update_mtime) = @_;
                   1034:     my ($otherserver,$cookie);
                   1035:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1036:     if (exists($cookies{'balanceID'})) {
                   1037:         my $balid = $cookies{'balanceID'};
                   1038:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1039:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1040:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1041:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1042:                 my ($possudom,$possuname) = ($1,$2);
                   1043:                 my $has_session = 0;
                   1044:                 if ((&domain($possudom) ne '') &&
                   1045:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1046:                     my $try_server;
                   1047:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1048:                     if ($opened) {
                   1049:                         flock($idf,LOCK_SH);
                   1050:                         while (my $line = <$idf>) {
                   1051:                             chomp($line);
                   1052:                             if (&hostname($line) ne '') {
                   1053:                                 $try_server = $line;
                   1054:                                 last;
                   1055:                             }
                   1056:                         }
                   1057:                         close($idf);
                   1058:                         if (($try_server) &&
                   1059:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1060:                             my $lowest_load = 30000;
                   1061:                             ($otherserver,$lowest_load) =
                   1062:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1063:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1064:                                 $has_session = 1;
                   1065:                             } else {
                   1066:                                 undef($otherserver);
                   1067:                             }
                   1068:                         }
                   1069:                     }
                   1070:                 }
                   1071:                 if ($has_session) {
                   1072:                     if ($update_mtime) {
                   1073:                         my $atime = my $mtime = time;
                   1074:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1075:                     }
                   1076:                 } else {
                   1077:                     unlink("$balancedir/$cookie.id");
                   1078:                 }
                   1079:             }
                   1080:         }
                   1081:     }
                   1082:     return ($otherserver,$cookie);
                   1083: }
                   1084: 
                   1085: sub delbalcookie {
                   1086:     my ($cookie,$balancer) =@_;
                   1087:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1088:         my ($udom,$uname) = ($1,$2);
                   1089:         my $uprimary_id = &domain($udom,'primary');
                   1090:         my $uintdom = &internet_dom($uprimary_id);
                   1091:         my $intdom = &internet_dom($balancer);
                   1092:         my $serverhomedom = &host_domain($balancer);
                   1093:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1094:             return &reply("delbalcookie:$cookie",$balancer);
                   1095:         }
                   1096:     }
                   1097: }
                   1098: 
1.914     albertel 1099: # -------------------------------- ask if server already has a session for user
                   1100: sub has_user_session {
                   1101:     my ($lonid,$udom,$uname) = @_;
                   1102:     my $result = &reply(join(':','userhassession',
                   1103: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1104:     return 1 if ($result eq 'ok');
                   1105: 
                   1106:     return 0;
                   1107: }
                   1108: 
1.1076    raeburn  1109: # --------- determine least loaded server in a user's domain which allows login
                   1110: 
                   1111: sub choose_server {
1.1172.2.47  raeburn  1112:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1113:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1114:     my %servers = &get_servers($udom);
1.1076    raeburn  1115:     my $lowest_load = 30000;
1.1172.2.47  raeburn  1116:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1117:     if ($skiploadbal) {
                   1118:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1119:         unless (defined($cached)) {
                   1120:             my $cachetime = 60*60*24;
                   1121:             my %domconfig =
                   1122:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1123:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1124:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1125:                                            $cachetime);
                   1126:             }
                   1127:         }
                   1128:     }
1.1076    raeburn  1129:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn  1130:         my $loginvia;
1.1172.2.47  raeburn  1131:         if ($skiploadbal) {
                   1132:             if (ref($balancers) eq 'HASH') {
                   1133:                 next if (exists($balancers->{$lonhost}));
                   1134:             }
                   1135:         }
1.1115    raeburn  1136:         if ($checkloginvia) {
                   1137:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1138:             if ($loginvia) {
                   1139:                 my ($server,$path) = split(/:/,$loginvia);
                   1140:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1141:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1142:                 if ($login_host eq $server) {
                   1143:                     $portal_path = $path;
1.1151    raeburn  1144:                     $isredirect = 1;
1.1116    raeburn  1145:                 }
                   1146:             } else {
                   1147:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1148:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1149:                 if ($login_host eq $lonhost) {
                   1150:                     $portal_path = '';
1.1151    raeburn  1151:                     $isredirect = ''; 
1.1116    raeburn  1152:                 }
                   1153:             }
                   1154:         } else {
1.1076    raeburn  1155:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1156:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1157:         }
                   1158:     }
                   1159:     if ($login_host ne '') {
1.1116    raeburn  1160:         $hostname = &hostname($login_host);
1.1076    raeburn  1161:     }
1.1172.2.88  raeburn  1162:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1163: }
                   1164: 
1.1172.2.118.  .5(raebu 1165:20): sub get_course_sessions {
                   1166:20):     my ($cnum,$cdom,$lastactivity) = @_;
                   1167:20):     my %servers = &internet_dom_servers($cdom);
                   1168:20):     my %returnhash;
                   1169:20):     foreach my $server (sort(keys(%servers))) {
                   1170:20):         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
                   1171:20):         my @pairs=split(/\&/,$rep);
                   1172:20):         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
                   1173:20):             foreach my $item (@pairs) {
                   1174:20):                 my ($key,$value)=split(/=/,$item,2);
                   1175:20):                 $key = &unescape($key);
                   1176:20):                 next if ($key =~ /^error: 2 /);
                   1177:20):                 if (exists($returnhash{$key})) {
                   1178:20):                     next if ($value < $returnhash{$key});
                   1179:20):                 }
                   1180:20):                 $returnhash{$key}=$value;
                   1181:20):             }
                   1182:20):         }
                   1183:20):     }
                   1184:20):     return %returnhash;
                   1185:20): }
                   1186:20): 
1.202     matthew  1187: # --------------------------------------------- Try to change a user's password
                   1188: 
                   1189: sub changepass {
1.799     raeburn  1190:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1191:     $currentpass = &escape($currentpass);
                   1192:     $newpass     = &escape($newpass);
1.1030    raeburn  1193:     my $lonhost = $perlvar{'lonHostID'};
                   1194:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1195: 		       $server);
                   1196:     if (! $answer) {
                   1197: 	&logthis("No reply on password change request to $server ".
                   1198: 		 "by $uname in domain $udom.");
                   1199:     } elsif ($answer =~ "^ok") {
                   1200:         &logthis("$uname in $udom successfully changed their password ".
                   1201: 		 "on $server.");
                   1202:     } elsif ($answer =~ "^pwchange_failure") {
                   1203: 	&logthis("$uname in $udom was unable to change their password ".
                   1204: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1205: 		 "or pwchange");
                   1206:     } elsif ($answer =~ "^non_authorized") {
                   1207:         &logthis("$uname in $udom did not get their password correct when ".
                   1208: 		 "attempting to change it on $server.");
                   1209:     } elsif ($answer =~ "^auth_mode_error") {
                   1210:         &logthis("$uname in $udom attempted to change their password despite ".
                   1211: 		 "not being locally or internally authenticated on $server.");
                   1212:     } elsif ($answer =~ "^unknown_user") {
                   1213:         &logthis("$uname in $udom attempted to change their password ".
                   1214: 		 "on $server but were unable to because $server is not ".
                   1215: 		 "their home server.");
                   1216:     } elsif ($answer =~ "^refused") {
                   1217: 	&logthis("$server refused to change $uname in $udom password because ".
                   1218: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1219:     } elsif ($answer =~ "invalid_client") {
                   1220:         &logthis("$server refused to change $uname in $udom password because ".
                   1221:                  "it was a reset by e-mail originating from an invalid server.");
1.1172.2.113  raeburn  1222:     } elsif ($answer =~ "^prioruse") {
                   1223:        &logthis("$server refused to change $uname in $udom password because ".
                   1224:                 "the password had been used before");
1.202     matthew  1225:     }
                   1226:     return $answer;
1.1       albertel 1227: }
                   1228: 
1.169     harris41 1229: # ----------------------- Try to determine user's current authentication scheme
                   1230: 
                   1231: sub queryauthenticate {
                   1232:     my ($uname,$udom)=@_;
1.456     albertel 1233:     my $uhome=&homeserver($uname,$udom);
                   1234:     if (!$uhome) {
                   1235: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1236: 	return 'no_host';
                   1237:     }
                   1238:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1239:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1240: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1241:     }
1.456     albertel 1242:     return $answer;
1.169     harris41 1243: }
                   1244: 
1.1       albertel 1245: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1246: 
1.1       albertel 1247: sub authenticate {
1.1073    raeburn  1248:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1249:     $upass=&escape($upass);
                   1250:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1251:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1252:     my $newhome;
1.836     www      1253:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1254: # Maybe the machine was offline and only re-appeared again recently?
                   1255:         &reconlonc();
                   1256: # One more
1.952     raeburn  1257: 	$uhome=&homeserver($uname,$udom,1);
                   1258:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1259:             if (defined(&domain($udom,'primary'))) {
                   1260:                 $newhome=&domain($udom,'primary');
                   1261:             }
                   1262:             if ($newhome ne '') {
                   1263:                 $uhome = $newhome;
                   1264:             }
                   1265:         }
1.836     www      1266: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1267: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1268: 	    return 'no_host';
                   1269:         }
1.1       albertel 1270:     }
1.1073    raeburn  1271:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1272:     if ($answer eq 'authorized') {
1.952     raeburn  1273:         if ($newhome) {
                   1274:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1275:             return 'no_account_on_host'; 
                   1276:         } else {
                   1277:             &logthis("User $uname at $udom authorized by $uhome");
                   1278:             return $uhome;
                   1279:         }
1.471     albertel 1280:     }
                   1281:     if ($answer eq 'non_authorized') {
                   1282: 	&logthis("User $uname at $udom rejected by $uhome");
                   1283: 	return 'no_host'; 
1.9       www      1284:     }
1.471     albertel 1285:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1286:     return 'no_host';
                   1287: }
                   1288: 
1.1073    raeburn  1289: sub can_host_session {
1.1074    raeburn  1290:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1291:     my $canhost = 1;
1.1074    raeburn  1292:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1293:     if (ref($remotesessions) eq 'HASH') {
                   1294:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1295:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1296:                 $canhost = 0;
                   1297:             } else {
                   1298:                 $canhost = 1;
                   1299:             }
                   1300:         }
                   1301:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1302:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1303:                 $canhost = 1;
                   1304:             } else {
                   1305:                 $canhost = 0;
                   1306:             }
                   1307:         }
                   1308:         if ($canhost) {
                   1309:             if ($remotesessions->{'version'} ne '') {
                   1310:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1311:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1312:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1313:                         my $major = $1;
                   1314:                         my $minor = $2;
                   1315:                         if (($major < $reqmajor ) ||
                   1316:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1317:                             $canhost = 0;
                   1318:                         }
                   1319:                     } else {
                   1320:                         $canhost = 0;
                   1321:                     }
                   1322:                 }
                   1323:             }
                   1324:         }
                   1325:     }
                   1326:     if ($canhost) {
                   1327:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1328:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1329:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1330:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1331:                 if (($uint_dom ne '') && 
                   1332:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1333:                     $canhost = 0;
                   1334:                 } else {
                   1335:                     $canhost = 1;
                   1336:                 }
                   1337:             }
                   1338:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1339:                 if (($uint_dom ne '') && 
                   1340:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1341:                     $canhost = 1;
                   1342:                 } else {
                   1343:                     $canhost = 0;
                   1344:                 }
                   1345:             }
                   1346:         }
                   1347:     }
                   1348:     return $canhost;
                   1349: }
                   1350: 
1.1083    raeburn  1351: sub spare_can_host {
                   1352:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1353:     my $canhost=1;
1.1172.2.62  raeburn  1354:     my $try_server_hostname = &hostname($try_server);
                   1355:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1356:     my $serverhomedom = &host_domain($serverhomeID);
                   1357:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1358:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1359:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1360:             $canhost = 0;
                   1361:         }
                   1362:     }
                   1363:     if (($canhost) && ($uint_dom)) {
                   1364:         my @intdoms;
                   1365:         my $internet_names = &get_internet_names($try_server);
                   1366:         if (ref($internet_names) eq 'ARRAY') {
                   1367:             @intdoms = @{$internet_names};
                   1368:         }
                   1369:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1370:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1371:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1372:                                          $remotesessions,
                   1373:                                          $defdomdefaults{'hostedsessions'});
                   1374:         }
1.1083    raeburn  1375:     }
                   1376:     return $canhost;
                   1377: }
                   1378: 
1.1123    raeburn  1379: sub this_host_spares {
                   1380:     my ($dom) = @_;
1.1126    raeburn  1381:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1382:     my @hosts = &current_machine_ids();
                   1383:     foreach my $lonhost (@hosts) {
                   1384:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1385:             $dom_in_use = $dom;
                   1386:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1387:             last;
                   1388:         }
                   1389:     }
1.1126    raeburn  1390:     if ($dom_in_use ne '') {
                   1391:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1392:     }
                   1393:     if (ref($result) ne 'HASH') {
                   1394:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1395:         $dom_in_use = &host_domain($lonhost_in_use);
                   1396:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1397:         if (ref($result) ne 'HASH') {
                   1398:             $result = \%spareid;
                   1399:         }
                   1400:     }
                   1401:     return $result;
                   1402: }
                   1403: 
                   1404: sub spares_for_offload  {
                   1405:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1406:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1407:     if (defined($cached)) {
                   1408:         return $result;
                   1409:     } else {
1.1126    raeburn  1410:         my $cachetime = 60*60*24;
                   1411:         my %domconfig =
                   1412:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1413:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1414:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1415:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1416:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1417:                 }
                   1418:             }
                   1419:         }
                   1420:     }
1.1126    raeburn  1421:     return;
1.1123    raeburn  1422: }
                   1423: 
1.1129    raeburn  1424: sub get_lonbalancer_config {
                   1425:     my ($servers) = @_;
                   1426:     my ($currbalancer,$currtargets);
                   1427:     if (ref($servers) eq 'HASH') {
                   1428:         foreach my $server (keys(%{$servers})) {
                   1429:             my %what = (
                   1430:                          spareid => 1,
                   1431:                          perlvar => 1,
                   1432:                        );
                   1433:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1434:             if ($result eq 'ok') {
                   1435:                 if (ref($returnhash) eq 'HASH') {
                   1436:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1437:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1438:                             $currbalancer = $server;
                   1439:                             $currtargets = {};
                   1440:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1441:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1442:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1443:                                 }
                   1444:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1445:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1446:                                 }
                   1447:                             }
                   1448:                             last;
                   1449:                         }
                   1450:                     }
                   1451:                 }
                   1452:             }
                   1453:         }
                   1454:     }
                   1455:     return ($currbalancer,$currtargets);
                   1456: }
                   1457: 
                   1458: sub check_loadbalancing {
1.1172.2.88  raeburn  1459:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1460:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107  raeburn  1461:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129    raeburn  1462:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1463:     my @hosts = &current_machine_ids();
1.1129    raeburn  1464:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1465:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1466:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1467:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1468:     my $domneedscache; 
1.1129    raeburn  1469:     my $cachetime = 60*60*24;
                   1470: 
                   1471:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1472:         $dom_in_use = $udom;
                   1473:         $homeintdom = 1;
                   1474:     } else {
                   1475:         $dom_in_use = $serverhomedom;
                   1476:     }
                   1477:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1478:     unless (defined($cached)) {
                   1479:         my %domconfig =
                   1480:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1481:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1482:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1483:         } else {
                   1484:             $domneedscache = $dom_in_use;
1.1129    raeburn  1485:         }
                   1486:     }
                   1487:     if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1488:         ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1489:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1490:         if ($is_balancer) {
                   1491:             if (ref($currrules) eq 'HASH') {
                   1492:                 if ($homeintdom) {
                   1493:                     if ($uname ne '') {
                   1494:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1495:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1496:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1497:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1498:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1499:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1500:                             }
                   1501:                         }
                   1502:                         if ($rule_in_effect eq '') {
                   1503:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1504:                             if ($userenv{'inststatus'} ne '') {
                   1505:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1506:                                 my ($othertitle,$usertypes,$types) =
                   1507:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1508:                                 if (ref($types) eq 'ARRAY') {
                   1509:                                     foreach my $type (@{$types}) {
                   1510:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1511:                                             if (exists($currrules->{$type})) {
                   1512:                                                 $rule_in_effect = $currrules->{$type};
                   1513:                                             }
                   1514:                                         }
                   1515:                                     }
                   1516:                                 }
                   1517:                             } else {
                   1518:                                 if (exists($currrules->{'default'})) {
                   1519:                                     $rule_in_effect = $currrules->{'default'};
                   1520:                                 }
                   1521:                             }
                   1522:                         }
                   1523:                     } else {
                   1524:                         if (exists($currrules->{'default'})) {
                   1525:                             $rule_in_effect = $currrules->{'default'};
                   1526:                         }
                   1527:                     }
                   1528:                 } else {
                   1529:                     if ($currrules->{'_LC_external'} ne '') {
                   1530:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1531:                     }
                   1532:                 }
                   1533:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1534:                                                        $uname,$udom);
                   1535:             }
                   1536:         }
                   1537:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1538:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1539:         unless (defined($cached)) {
                   1540:             my %domconfig =
                   1541:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1542:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1543:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1544:             } else {
                   1545:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1546:             }
                   1547:         }
                   1548:         if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1549:             ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1550:                 &check_balancer_result($result,@hosts);
                   1551:             if ($is_balancer) {
1.1129    raeburn  1552:                 if (ref($currrules) eq 'HASH') {
                   1553:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1554:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1555:                     }
                   1556:                 }
                   1557:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1558:                                                        $uname,$udom);
                   1559:             }
                   1560:         } else {
                   1561:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1562:                 $is_balancer = 1;
                   1563:                 $offloadto = &this_host_spares($dom_in_use);
                   1564:             }
1.1172.2.75  raeburn  1565:             unless (defined($cached)) {
                   1566:                 $domneedscache = $serverhomedom;
                   1567:             }
1.1129    raeburn  1568:         }
                   1569:     } else {
                   1570:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1571:             $is_balancer = 1;
                   1572:             $offloadto = &this_host_spares($dom_in_use);
                   1573:         }
1.1172.2.75  raeburn  1574:         unless (defined($cached)) {
                   1575:             $domneedscache = $serverhomedom;
                   1576:         }
                   1577:     }
                   1578:     if ($domneedscache) {
                   1579:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1580:     }
1.1172.2.5  raeburn  1581:     if ($is_balancer) {
                   1582:         my $lowest_load = 30000;
                   1583:         if (ref($offloadto) eq 'HASH') {
                   1584:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1585:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1586:                     ($otherserver,$lowest_load) =
                   1587:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1588:                 }
1.1129    raeburn  1589:             }
1.1172.2.5  raeburn  1590:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1591: 
1.1172.2.5  raeburn  1592:             if (!$found_server) {
                   1593:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1594:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1595:                         ($otherserver,$lowest_load) =
                   1596:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1597:                     }
                   1598:                 }
                   1599:             }
                   1600:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1601:             if (@{$offloadto} == 1) {
                   1602:                 $otherserver = $offloadto->[0];
                   1603:             } elsif (@{$offloadto} > 1) {
                   1604:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1605:                     ($otherserver,$lowest_load) =
                   1606:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1607:                 }
                   1608:             }
                   1609:         }
1.1172.2.88  raeburn  1610:         unless ($caller eq 'login') {
                   1611:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1612:                 $is_balancer = 0;
                   1613:                 if ($uname ne '' && $udom ne '') {
                   1614:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1615:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1616:                                  'user.loadbalcheck.time' => time});
                   1617:                     }
1.1172.2.5  raeburn  1618:                 }
1.1129    raeburn  1619:             }
                   1620:         }
1.1172.2.107  raeburn  1621:         unless ($homeintdom) {
                   1622:             undef($setcookie);
                   1623:         }
1.1129    raeburn  1624:     }
1.1172.2.107  raeburn  1625:     return ($is_balancer,$otherserver,$setcookie);
1.1129    raeburn  1626: }
                   1627: 
1.1172.2.12  raeburn  1628: sub check_balancer_result {
                   1629:     my ($result,@hosts) = @_;
1.1172.2.107  raeburn  1630:     my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1631:     if (ref($result) eq 'HASH') {
                   1632:         if ($result->{'lonhost'} ne '') {
                   1633:             my $currbalancer = $result->{'lonhost'};
                   1634:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1635:                 $is_balancer = 1;
                   1636:                 $currtargets = $result->{'targets'};
                   1637:                 $currrules = $result->{'rules'};
                   1638:             }
                   1639:         } else {
                   1640:             foreach my $key (keys(%{$result})) {
                   1641:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1642:                     (ref($result->{$key}) eq 'HASH')) {
                   1643:                     $is_balancer = 1;
                   1644:                     $currrules = $result->{$key}{'rules'};
                   1645:                     $currtargets = $result->{$key}{'targets'};
1.1172.2.107  raeburn  1646:                     $setcookie = $result->{$key}{'cookie'};
1.1172.2.12  raeburn  1647:                     last;
                   1648:                 }
                   1649:             }
                   1650:         }
                   1651:     }
1.1172.2.107  raeburn  1652:     return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1653: }
                   1654: 
1.1129    raeburn  1655: sub get_loadbalancer_targets {
                   1656:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1657:     my $offloadto;
1.1172.2.4  raeburn  1658:     if ($rule_in_effect eq 'none') {
                   1659:         return [$perlvar{'lonHostID'}];
                   1660:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1661:         $offloadto = $currtargets;
                   1662:     } else {
                   1663:         if ($rule_in_effect eq 'homeserver') {
                   1664:             my $homeserver = &homeserver($uname,$udom);
                   1665:             if ($homeserver ne 'no_host') {
                   1666:                 $offloadto = [$homeserver];
                   1667:             }
                   1668:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1669:             my %domconfig =
                   1670:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1671:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1672:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1673:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1674:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1675:                     }
                   1676:                 }
                   1677:             } else {
1.1172.2.7  raeburn  1678:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1679:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1680:                 if (&hostname($remotebalancer) ne '') {
                   1681:                     $offloadto = [$remotebalancer];
                   1682:                 }
                   1683:             }
                   1684:         } elsif (&hostname($rule_in_effect) ne '') {
                   1685:             $offloadto = [$rule_in_effect];
                   1686:         }
                   1687:     }
                   1688:     return $offloadto;
                   1689: }
                   1690: 
1.1127    raeburn  1691: sub internet_dom_servers {
                   1692:     my ($dom) = @_;
                   1693:     my (%uniqservers,%servers);
                   1694:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1695:     my @machinedoms = &machine_domains($primaryserver);
                   1696:     foreach my $mdom (@machinedoms) {
                   1697:         my %currservers = %servers;
                   1698:         my %server = &get_servers($mdom);
                   1699:         %servers = (%currservers,%server);
                   1700:     }
                   1701:     my %by_hostname;
                   1702:     foreach my $id (keys(%servers)) {
                   1703:         push(@{$by_hostname{$servers{$id}}},$id);
                   1704:     }
                   1705:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1706:         if (@{$by_hostname{$hostname}} > 1) {
                   1707:             my $match = 0;
                   1708:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1709:                 if (&host_domain($id) eq $dom) {
                   1710:                     $uniqservers{$id} = $hostname;
                   1711:                     $match = 1;
                   1712:                 }
                   1713:             }
                   1714:             unless ($match) {
                   1715:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1716:             }
                   1717:         } else {
                   1718:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1719:         }
                   1720:     }
                   1721:     return %uniqservers;
                   1722: }
                   1723: 
1.1       albertel 1724: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1725: 
1.599     albertel 1726: my %homecache;
1.1       albertel 1727: sub homeserver {
1.230     stredwic 1728:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1729:     my $index="$uname:$udom";
1.426     albertel 1730: 
1.599     albertel 1731:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1732: 
                   1733:     my %servers = &get_servers($udom,'library');
                   1734:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1735:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1736: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1737: 
                   1738: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1739: 	if ($answer eq 'found') {
                   1740: 	    delete($badServerCache{$tryserver}); 
                   1741: 	    return $homecache{$index}=$tryserver;
                   1742: 	} elsif ($answer eq 'no_host') {
                   1743: 	    $badServerCache{$tryserver}=1;
                   1744: 	}
1.1       albertel 1745:     }    
                   1746:     return 'no_host';
1.70      www      1747: }
                   1748: 
                   1749: # ------------------------------------- Find the usernames behind a list of IDs
                   1750: 
                   1751: sub idget {
                   1752:     my ($udom,@ids)=@_;
                   1753:     my %returnhash=();
                   1754:     
1.841     albertel 1755:     my %servers = &get_servers($udom,'library');
                   1756:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1757: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1758: 	$idlist=~tr/A-Z/a-z/; 
                   1759: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1760: 	my @answer=();
                   1761: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1762: 	    @answer=split(/\&/,$reply);
                   1763: 	}                    ;
                   1764: 	my $i;
                   1765: 	for ($i=0;$i<=$#ids;$i++) {
                   1766: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1767: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1768: 	    } 
                   1769: 	}
                   1770:     } 
1.70      www      1771:     return %returnhash;
                   1772: }
                   1773: 
                   1774: # ------------------------------------- Find the IDs behind a list of usernames
                   1775: 
                   1776: sub idrget {
                   1777:     my ($udom,@unames)=@_;
                   1778:     my %returnhash=();
1.800     albertel 1779:     foreach my $uname (@unames) {
                   1780:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1781:     }
1.70      www      1782:     return %returnhash;
                   1783: }
                   1784: 
                   1785: # ------------------------------- Store away a list of names and associated IDs
                   1786: 
                   1787: sub idput {
                   1788:     my ($udom,%ids)=@_;
                   1789:     my %servers=();
1.800     albertel 1790:     foreach my $uname (keys(%ids)) {
                   1791: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1792:         my $uhom=&homeserver($uname,$udom);
1.70      www      1793:         if ($uhom ne 'no_host') {
1.800     albertel 1794:             my $id=&escape($ids{$uname});
1.70      www      1795:             $id=~tr/A-Z/a-z/;
1.800     albertel 1796:             my $esc_unam=&escape($uname);
1.70      www      1797: 	    if ($servers{$uhom}) {
1.800     albertel 1798: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1799:             } else {
1.800     albertel 1800:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1801:             }
                   1802:         }
1.191     harris41 1803:     }
1.800     albertel 1804:     foreach my $server (keys(%servers)) {
                   1805:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1806:     }
1.344     www      1807: }
                   1808: 
1.1172.2.30  raeburn  1809: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1810: 
                   1811: sub iddel {
                   1812:     my ($udom,$idshashref,$uhome)=@_;
                   1813:     my %result=();
                   1814:     unless (ref($idshashref) eq 'HASH') {
                   1815:         return %result;
                   1816:     }
                   1817:     my %servers=();
                   1818:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1819:         my $uhom;
                   1820:         if ($uhome) {
                   1821:             $uhom = $uhome;
                   1822:         } else {
                   1823:             $uhom=&homeserver($uname,$udom);
                   1824:         }
                   1825:         if ($uhom ne 'no_host') {
                   1826:             if ($servers{$uhom}) {
                   1827:                 $servers{$uhom}.='&'.&escape($id);
                   1828:             } else {
                   1829:                 $servers{$uhom}=&escape($id);
                   1830:             }
                   1831:         }
                   1832:     }
                   1833:     foreach my $server (keys(%servers)) {
                   1834:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1835:     }
                   1836:     return %result;
                   1837: }
                   1838: 
1.1023    raeburn  1839: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1840: sub dump_dom {
1.1165    droeschl 1841:     my ($namespace, $udom, $regexp) = @_;
                   1842: 
                   1843:     $udom ||= $env{'user.domain'};
                   1844: 
                   1845:     return () unless $udom;
                   1846: 
                   1847:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1848: }
                   1849: 
1.1023    raeburn  1850: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1851: 
                   1852: sub get_dom {
1.860     raeburn  1853:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1854:     return if ($udom eq 'public');
1.806     raeburn  1855:     my $items='';
                   1856:     foreach my $item (@$storearr) {
                   1857:         $items.=&escape($item).'&';
                   1858:     }
                   1859:     $items=~s/\&$//;
1.860     raeburn  1860:     if (!$udom) {
                   1861:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1862:         return if ($udom eq 'public');
1.860     raeburn  1863:         if (defined(&domain($udom,'primary'))) {
                   1864:             $uhome=&domain($udom,'primary');
                   1865:         } else {
1.874     albertel 1866:             undef($uhome);
1.860     raeburn  1867:         }
                   1868:     } else {
                   1869:         if (!$uhome) {
                   1870:             if (defined(&domain($udom,'primary'))) {
                   1871:                 $uhome=&domain($udom,'primary');
                   1872:             }
                   1873:         }
                   1874:     }
                   1875:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1172.2.118.  .1(raebu 1876:20):         my $rep;
                   1877:20):         if ($namespace =~ /^enc/) {
                   1878:20):             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   1879:20):         } else {
                   1880:20):             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   1881:20):         }
1.866     raeburn  1882:         my %returnhash;
1.875     albertel 1883:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1884:             return %returnhash;
                   1885:         }
1.806     raeburn  1886:         my @pairs=split(/\&/,$rep);
                   1887:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1888:             return @pairs;
                   1889:         }
                   1890:         my $i=0;
                   1891:         foreach my $item (@$storearr) {
                   1892:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1893:             $i++;
                   1894:         }
                   1895:         return %returnhash;
                   1896:     } else {
1.880     banghart 1897:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1898:     }
                   1899: }
                   1900: 
                   1901: # -------------------------------------------- put items in domain db files 
                   1902: 
                   1903: sub put_dom {
1.860     raeburn  1904:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1905:     if (!$udom) {
                   1906:         $udom=$env{'user.domain'};
                   1907:         if (defined(&domain($udom,'primary'))) {
                   1908:             $uhome=&domain($udom,'primary');
                   1909:         } else {
1.874     albertel 1910:             undef($uhome);
1.860     raeburn  1911:         }
                   1912:     } else {
                   1913:         if (!$uhome) {
                   1914:             if (defined(&domain($udom,'primary'))) {
                   1915:                 $uhome=&domain($udom,'primary');
                   1916:             }
                   1917:         }
                   1918:     } 
                   1919:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1920:         my $items='';
                   1921:         foreach my $item (keys(%$storehash)) {
                   1922:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1923:         }
                   1924:         $items=~s/\&$//;
1.1172.2.118.  .1(raebu 1925:20):         if ($namespace =~ /^enc/) {
                   1926:20):             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   1927:20):         } else {
                   1928:20):             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1929:20):         }
1.806     raeburn  1930:     } else {
1.860     raeburn  1931:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1932:     }
                   1933: }
                   1934: 
1.1023    raeburn  1935: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1936: sub newput_dom {
1.1023    raeburn  1937:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1938:     my $result;
                   1939:     if (!$udom) {
                   1940:         $udom=$env{'user.domain'};
                   1941:     }
1.1023    raeburn  1942:     if ($udom) {
                   1943:         my $uname = &get_domainconfiguser($udom);
                   1944:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1945:     }
                   1946:     return $result;
                   1947: }
                   1948: 
1.1023    raeburn  1949: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1950: sub del_dom {
1.1023    raeburn  1951:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1952:     if (ref($storearr) eq 'ARRAY') {
                   1953:         if (!$udom) {
                   1954:             $udom=$env{'user.domain'};
                   1955:         }
1.1023    raeburn  1956:         if ($udom) {
                   1957:             my $uname = &get_domainconfiguser($udom); 
                   1958:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1959:         }
                   1960:     }
                   1961: }
                   1962: 
1.1023    raeburn  1963: # ----------------------------------construct domainconfig user for a domain 
                   1964: sub get_domainconfiguser {
                   1965:     my ($udom) = @_;
                   1966:     return $udom.'-domainconfig';
                   1967: }
                   1968: 
1.837     raeburn  1969: sub retrieve_inst_usertypes {
                   1970:     my ($udom) = @_;
                   1971:     my (%returnhash,@order);
1.989     raeburn  1972:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1973:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1974:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1975:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1976:     } else {
                   1977:         if (defined(&domain($udom,'primary'))) {
                   1978:             my $uhome=&domain($udom,'primary');
                   1979:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1980:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1981:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1982:                 return (\%returnhash,\@order);
                   1983:             }
                   1984:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1985:             my @pairs=split(/\&/,$hashitems);
                   1986:             foreach my $item (@pairs) {
                   1987:                 my ($key,$value)=split(/=/,$item,2);
                   1988:                 $key = &unescape($key);
                   1989:                 next if ($key =~ /^error: 2 /);
                   1990:                 $returnhash{$key}=&thaw_unescape($value);
                   1991:             }
                   1992:             my @esc_order = split(/\&/,$orderitems);
                   1993:             foreach my $item (@esc_order) {
                   1994:                 push(@order,&unescape($item));
                   1995:             }
                   1996:         } else {
1.1172.2.44  raeburn  1997:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1998:         }
1.1172.2.44  raeburn  1999:         return (\%returnhash,\@order);
1.837     raeburn  2000:     }
                   2001: }
                   2002: 
1.868     raeburn  2003: sub is_domainimage {
                   2004:     my ($url) = @_;
1.1172.2.74  raeburn  2005:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2006:         if (&domain($1) ne '') {
                   2007:             return '1';
                   2008:         }
                   2009:     }
                   2010:     return;
                   2011: }
                   2012: 
1.899     raeburn  2013: sub inst_directory_query {
                   2014:     my ($srch) = @_;
                   2015:     my $udom = $srch->{'srchdomain'};
                   2016:     my %results;
                   2017:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2018:     my $outcome;
1.899     raeburn  2019:     if ($homeserver ne '') {
1.1172.2.116  raeburn  2020:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2021:             if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2022:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116  raeburn  2023:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
                   2024:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2025:                     (($major == 2) && ($minor < 11)) ||
                   2026:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
                   2027:                     return;
                   2028:                 }
                   2029:             }
                   2030:         }
1.904     albertel 2031: 	my $queryid=&reply("querysend:instdirsearch:".
                   2032: 			   &escape($srch->{'srchby'}).':'.
                   2033: 			   &escape($srch->{'srchterm'}).':'.
                   2034: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2035: 	my $host=&hostname($homeserver);
                   2036: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  2037: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2038: 	    return;
                   2039: 	}
                   2040: 	my $response = &get_query_reply($queryid);
                   2041: 	my $maxtries = 5;
                   2042: 	my $tries = 1;
                   2043: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2044: 	    $response = &get_query_reply($queryid);
                   2045: 	    $tries ++;
                   2046: 	}
                   2047: 
                   2048:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2049:             if ($response eq 'unavailable') {
                   2050:                 $outcome = $response;
                   2051:             } else {
                   2052:                 $outcome = 'ok';
                   2053:                 my @matches = split(/\n/,$response);
                   2054:                 foreach my $match (@matches) {
                   2055:                     my ($key,$value) = split(/=/,$match);
                   2056:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2057:                 }
1.899     raeburn  2058:             }
                   2059:         }
                   2060:     }
1.909     raeburn  2061:     return ($outcome,%results);
1.899     raeburn  2062: }
                   2063: 
                   2064: sub usersearch {
                   2065:     my ($srch) = @_;
                   2066:     my $dom = $srch->{'srchdomain'};
                   2067:     my %results;
                   2068:     my %libserv = &all_library();
                   2069:     my $query = 'usersearch';
                   2070:     foreach my $tryserver (keys(%libserv)) {
                   2071:         if (&host_domain($tryserver) eq $dom) {
1.1172.2.116  raeburn  2072:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2073:                 if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2074:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.118.  .2(raebu 2075:20):                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116  raeburn  2076:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2077:                              (($major == 2) && ($minor < 11)) ||
                   2078:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
                   2079:                 }
                   2080:             }
1.899     raeburn  2081:             my $host=&hostname($tryserver);
                   2082:             my $queryid=
1.911     raeburn  2083:                 &reply("querysend:".&escape($query).':'.
                   2084:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2085:                        &escape($srch->{'srchtype'}).':'.
                   2086:                        &escape($srch->{'srchterm'}),$tryserver);
                   2087:             if ($queryid !~/^\Q$host\E\_/) {
                   2088:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2089:                 next;
1.899     raeburn  2090:             }
                   2091:             my $reply = &get_query_reply($queryid);
                   2092:             my $maxtries = 1;
                   2093:             my $tries = 1;
                   2094:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2095:                 $reply = &get_query_reply($queryid);
                   2096:                 $tries ++;
                   2097:             }
                   2098:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2099:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2100:             } else {
1.911     raeburn  2101:                 my @matches;
                   2102:                 if ($reply =~ /\n/) {
                   2103:                     @matches = split(/\n/,$reply);
                   2104:                 } else {
                   2105:                     @matches = split(/\&/,$reply);
                   2106:                 }
1.899     raeburn  2107:                 foreach my $match (@matches) {
                   2108:                     my ($uname,$udom,%userhash);
1.911     raeburn  2109:                     foreach my $entry (split(/:/,$match)) {
                   2110:                         my ($key,$value) =
                   2111:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2112:                         $userhash{$key} = $value;
                   2113:                         if ($key eq 'username') {
                   2114:                             $uname = $value;
                   2115:                         } elsif ($key eq 'domain') {
                   2116:                             $udom = $value;
1.911     raeburn  2117:                         }
1.899     raeburn  2118:                     }
                   2119:                     $results{$uname.':'.$udom} = \%userhash;
                   2120:                 }
                   2121:             }
                   2122:         }
                   2123:     }
                   2124:     return %results;
                   2125: }
                   2126: 
1.912     raeburn  2127: sub get_instuser {
                   2128:     my ($udom,$uname,$id) = @_;
                   2129:     my $homeserver = &domain($udom,'primary');
                   2130:     my ($outcome,%results);
                   2131:     if ($homeserver ne '') {
                   2132:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2133:                            &escape($id).':'.&escape($udom),$homeserver);
                   2134:         my $host=&hostname($homeserver);
                   2135:         if ($queryid !~/^\Q$host\E\_/) {
                   2136:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2137:             return;
                   2138:         }
                   2139:         my $response = &get_query_reply($queryid);
                   2140:         my $maxtries = 5;
                   2141:         my $tries = 1;
                   2142:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2143:             $response = &get_query_reply($queryid);
                   2144:             $tries ++;
                   2145:         }
                   2146:         if (!&error($response) && $response ne 'refused') {
                   2147:             if ($response eq 'unavailable') {
                   2148:                 $outcome = $response;
                   2149:             } else {
                   2150:                 $outcome = 'ok';
                   2151:                 my @matches = split(/\n/,$response);
                   2152:                 foreach my $match (@matches) {
                   2153:                     my ($key,$value) = split(/=/,$match);
                   2154:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2155:                 }
                   2156:             }
                   2157:         }
                   2158:     }
                   2159:     my %userinfo;
                   2160:     if (ref($results{$uname}) eq 'HASH') {
                   2161:         %userinfo = %{$results{$uname}};
                   2162:     } 
                   2163:     return ($outcome,%userinfo);
                   2164: }
                   2165: 
1.1172.2.69  raeburn  2166: sub get_multiple_instusers {
                   2167:     my ($udom,$users,$caller) = @_;
                   2168:     my ($outcome,$results);
                   2169:     if (ref($users) eq 'HASH') {
                   2170:         my $count = keys(%{$users});
                   2171:         my $requested = &freeze_escape($users);
                   2172:         my $homeserver = &domain($udom,'primary');
                   2173:         if ($homeserver ne '') {
                   2174:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2175:             my $host=&hostname($homeserver);
                   2176:             if ($queryid !~/^\Q$host\E\_/) {
                   2177:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2178:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2179:                 return ($outcome,$results);
                   2180:             }
                   2181:             my $response = &get_query_reply($queryid);
                   2182:             my $maxtries = 5;
                   2183:             if ($count > 100) {
                   2184:                 $maxtries = 1+int($count/20);
                   2185:             }
                   2186:             my $tries = 1;
                   2187:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2188:                 $response = &get_query_reply($queryid);
                   2189:                 $tries ++;
                   2190:             }
                   2191:             if ($response eq '') {
                   2192:                 $results = {};
                   2193:                 foreach my $key (keys(%{$users})) {
                   2194:                     my ($uname,$id);
                   2195:                     if ($caller eq 'id') {
                   2196:                         $id = $key;
                   2197:                     } else {
                   2198:                         $uname = $key;
                   2199:                     }
                   2200:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2201:                     $outcome = $resp;
                   2202:                     if ($resp eq 'ok') {
                   2203:                         %{$results} = (%{$results}, %info);
                   2204:                     } else {
                   2205:                         last;
                   2206:                     }
                   2207:                 }
                   2208:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2209:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2210:                     $outcome = $response;
                   2211:                 } else {
                   2212:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2213:                     if ($outcome eq 'ok') {
                   2214:                         $results = &thaw_unescape($userdata);
                   2215:                     }
                   2216:                 }
                   2217:             }
                   2218:         }
                   2219:     }
                   2220:     return ($outcome,$results);
                   2221: }
                   2222: 
1.912     raeburn  2223: sub inst_rulecheck {
1.923     raeburn  2224:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2225:     my %returnhash;
                   2226:     if ($udom ne '') {
                   2227:         if (ref($rules) eq 'ARRAY') {
                   2228:             @{$rules} = map {&escape($_);} (@{$rules});
                   2229:             my $rulestr = join(':',@{$rules});
                   2230:             my $homeserver=&domain($udom,'primary');
                   2231:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2232:                 my $response;
                   2233:                 if ($item eq 'username') {                
                   2234:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2235:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2236:                                               $homeserver));
1.923     raeburn  2237:                 } elsif ($item eq 'id') {
                   2238:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2239:                                               ':'.&escape($id).':'.$rulestr,
                   2240:                                               $homeserver));
1.945     raeburn  2241:                 } elsif ($item eq 'selfcreate') {
                   2242:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2243:                                                &escape($udom).':'.&escape($uname).
                   2244:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2245:                 }
1.912     raeburn  2246:                 if ($response ne 'refused') {
                   2247:                     my @pairs=split(/\&/,$response);
                   2248:                     foreach my $item (@pairs) {
                   2249:                         my ($key,$value)=split(/=/,$item,2);
                   2250:                         $key = &unescape($key);
                   2251:                         next if ($key =~ /^error: 2 /);
                   2252:                         $returnhash{$key}=&thaw_unescape($value);
                   2253:                     }
                   2254:                 }
                   2255:             }
                   2256:         }
                   2257:     }
                   2258:     return %returnhash;
                   2259: }
                   2260: 
                   2261: sub inst_userrules {
1.923     raeburn  2262:     my ($udom,$check) = @_;
1.912     raeburn  2263:     my (%ruleshash,@ruleorder);
                   2264:     if ($udom ne '') {
                   2265:         my $homeserver=&domain($udom,'primary');
                   2266:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2267:             my $response;
                   2268:             if ($check eq 'id') {
                   2269:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2270:                                  $homeserver);
1.943     raeburn  2271:             } elsif ($check eq 'email') {
                   2272:                 $response=&reply('instemailrules:'.&escape($udom),
                   2273:                                  $homeserver);
1.923     raeburn  2274:             } else {
                   2275:                 $response=&reply('instuserrules:'.&escape($udom),
                   2276:                                  $homeserver);
                   2277:             }
1.912     raeburn  2278:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2279:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2280:                 ($response ne 'no_such_host')) {
                   2281:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2282:                 my @pairs=split(/\&/,$hashitems);
                   2283:                 foreach my $item (@pairs) {
                   2284:                     my ($key,$value)=split(/=/,$item,2);
                   2285:                     $key = &unescape($key);
                   2286:                     next if ($key =~ /^error: 2 /);
                   2287:                     $ruleshash{$key}=&thaw_unescape($value);
                   2288:                 }
                   2289:                 my @esc_order = split(/\&/,$orderitems);
                   2290:                 foreach my $item (@esc_order) {
                   2291:                     push(@ruleorder,&unescape($item));
                   2292:                 }
                   2293:             }
                   2294:         }
                   2295:     }
                   2296:     return (\%ruleshash,\@ruleorder);
                   2297: }
                   2298: 
1.976     raeburn  2299: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2300: 
                   2301: sub get_domain_defaults {
1.1172.2.35  raeburn  2302:     my ($domain,$ignore_cache) = @_;
                   2303:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2304:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2305:     unless ($ignore_cache) {
                   2306:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2307:         if (defined($cached)) {
                   2308:             if (ref($result) eq 'HASH') {
                   2309:                 return %{$result};
                   2310:             }
1.943     raeburn  2311:         }
                   2312:     }
                   2313:     my %domdefaults;
                   2314:     my %domconfig =
1.989     raeburn  2315:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2316:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2317:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2318:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2319:                                   'coursecategories','autoenroll',
                   2320:                                   'helpsettings'],$domain);
1.1172.2.41  raeburn  2321:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2322:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2323:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2324:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2325:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2326:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2327:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2328:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2329:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2330:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2331:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2332:     } else {
                   2333:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2334:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2335:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2336:     }
1.976     raeburn  2337:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2338:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2339:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2340:         } else {
                   2341:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2342:         }
1.1172.2.6  raeburn  2343:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2344:         foreach my $item (@usertools) {
                   2345:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2346:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2347:             }
                   2348:         }
1.1172.2.29  raeburn  2349:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2350:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2351:         }
1.976     raeburn  2352:     }
1.985     raeburn  2353:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2354:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2355:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2356:         }
                   2357:     }
1.1172.2.9  raeburn  2358:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2359:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2360:     }
1.989     raeburn  2361:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2362:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2363:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2364:         }
                   2365:     }
1.1047    raeburn  2366:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2367:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2368:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2369:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2370:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2371:         }
1.1172.2.41  raeburn  2372:         foreach my $type (@coursetypes) {
                   2373:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2374:                 unless ($type eq 'community') {
                   2375:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2376:                 }
                   2377:             }
                   2378:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2379:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2380:             }
1.1172.2.60  raeburn  2381:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2382:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2383:                     $domdefaults{$type.'postsubtimeout'} =
                   2384:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2385:                 }
                   2386:             }
1.1172.2.30  raeburn  2387:         }
1.1172.2.67  raeburn  2388:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2389:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2390:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2391:                 if (@clonecodes) {
                   2392:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2393:                 }
                   2394:             }
                   2395:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2396:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2397:         }
1.1172.2.103  raeburn  2398:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2399:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2400:         }
1.1047    raeburn  2401:     }
1.1073    raeburn  2402:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2403:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2404:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2405:         }
                   2406:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2407:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2408:         }
1.1172.2.62  raeburn  2409:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2410:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2411:         }
1.1073    raeburn  2412:     }
1.1172.2.41  raeburn  2413:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2414:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2415:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2416:                             'approval','limit');
                   2417:             foreach my $type (@coursetypes) {
                   2418:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2419:                     my @mgrdc = ();
                   2420:                     foreach my $item (@settings) {
                   2421:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2422:                             push(@mgrdc,$item);
                   2423:                         }
                   2424:                     }
                   2425:                     if (@mgrdc) {
                   2426:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2427:                     }
                   2428:                 }
                   2429:             }
                   2430:         }
                   2431:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2432:             foreach my $type (@coursetypes) {
                   2433:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2434:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2435:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2436:                     }
                   2437:                 }
                   2438:             }
                   2439:         }
                   2440:     }
1.1172.2.46  raeburn  2441:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2442:         $domdefaults{'catauth'} = 'std';
                   2443:         $domdefaults{'catunauth'} = 'std';
                   2444:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2445:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2446:         }
                   2447:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2448:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2449:         }
                   2450:     }
1.1172.2.76  raeburn  2451:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2452:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2453:     }
1.1172.2.89  raeburn  2454:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2455:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2456:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2457:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2458:         }
                   2459:     }
1.1172.2.23  raeburn  2460:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2461:     return %domdefaults;
                   2462: }
                   2463: 
1.1172.2.106  raeburn  2464: sub get_dom_cats {
                   2465:     my ($dom) = @_;
                   2466:     return unless (&domain($dom));
                   2467:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2468:     unless (defined($cached)) {
                   2469:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2470:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2471:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2472:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2473:             } else {
                   2474:                 $cats = {};
                   2475:             }
                   2476:         } else {
                   2477:             $cats = {};
                   2478:         }
                   2479:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2480:     }
                   2481:     return $cats;
                   2482: }
                   2483: 
                   2484: sub get_dom_instcats {
                   2485:     my ($dom) = @_;
                   2486:     return unless (&domain($dom));
                   2487:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2488:     unless (defined($cached)) {
                   2489:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2490:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2491:         if ($totcodes > 0) {
                   2492:             my $caller = 'global';
                   2493:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2494:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2495:                 $instcats = {
                   2496:                                 codes => \%codes,
                   2497:                                 codetitles => \@codetitles,
                   2498:                                 cat_titles => \%cat_titles,
                   2499:                                 cat_order => \%cat_order,
                   2500:                             };
                   2501:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2502:             }
                   2503:         }
                   2504:     }
                   2505:     return $instcats;
                   2506: }
                   2507: 
                   2508: sub retrieve_instcodes {
                   2509:     my ($coursecodes,$dom) = @_;
                   2510:     my $totcodes;
                   2511:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2512:     foreach my $course (keys(%courses)) {
                   2513:         if (ref($courses{$course}) eq 'HASH') {
                   2514:             if ($courses{$course}{'inst_code'} ne '') {
                   2515:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2516:                 $totcodes ++;
                   2517:             }
                   2518:         }
                   2519:     }
                   2520:     return $totcodes;
                   2521: }
                   2522: 
1.1172.2.113  raeburn  2523: # --------------------------------------------- Get domain config for passwords
                   2524: 
                   2525: sub get_passwdconf {
                   2526:     my ($dom) = @_;
                   2527:     my (%passwdconf,$gotconf,$lookup);
                   2528:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2529:     if (defined($cached)) {
                   2530:         if (ref($result) eq 'HASH') {
                   2531:             %passwdconf = %{$result};
                   2532:             $gotconf = 1;
                   2533:         }
                   2534:     }
                   2535:     unless ($gotconf) {
                   2536:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2537:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2538:             %passwdconf = %{$domconfig{'passwords'}};
                   2539:         }
                   2540:         my $cachetime = 24*60*60;
                   2541:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2542:     }
                   2543:     return %passwdconf;
                   2544: }
                   2545: 
1.1172.2.118.  .1(raebu 2546:20): sub course_portal_url {
                   2547:20):     my ($cnum,$cdom) = @_;
                   2548:20):     my $chome = &homeserver($cnum,$cdom);
                   2549:20):     my $hostname = &hostname($chome);
                   2550:20):     my $protocol = $protocol{$chome};
                   2551:20):     $protocol = 'http' if ($protocol ne 'https');
                   2552:20):     my %domdefaults = &get_domain_defaults($cdom);
                   2553:20):     my $firsturl;
                   2554:20):     if ($domdefaults{'portal_def'}) {
                   2555:20):         $firsturl = $domdefaults{'portal_def'};
                   2556:20):     } else {
                   2557:20):         $firsturl = $protocol.'://'.$hostname;
                   2558:20):     }
                   2559:20):     return $firsturl;
                   2560:20): }
                   2561:20): 
1.344     www      2562: # --------------------------------------------------- Assign a key to a student
                   2563: 
                   2564: sub assign_access_key {
1.364     www      2565: #
                   2566: # a valid key looks like uname:udom#comments
                   2567: # comments are being appended
                   2568: #
1.498     www      2569:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2570:     $kdom=
1.620     albertel 2571:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2572:     $knum=
1.620     albertel 2573:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2574:     $cdom=
1.620     albertel 2575:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2576:     $cnum=
1.620     albertel 2577:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2578:     $udom=$env{'user.name'} unless (defined($udom));
                   2579:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2580:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2581:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2582:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2583:                                                   # assigned to this person
                   2584:                                                   # - this should not happen,
1.345     www      2585:                                                   # unless something went wrong
                   2586:                                                   # the first time around
                   2587: # ready to assign
1.364     www      2588:         $logentry=$1.'; '.$logentry;
1.496     www      2589:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2590:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2591: # key now belongs to user
1.346     www      2592: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2593:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2594:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2595:                 return 'ok';
                   2596:             } else {
                   2597:                 return 
                   2598:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2599: 	    }
                   2600:         } else {
                   2601:             return 'error: Could not assign key, try again later.';
                   2602:         }
1.364     www      2603:     } elsif (!$existing{$ckey}) {
1.345     www      2604: # the key does not exist
                   2605: 	return 'error: The key does not exist';
                   2606:     } else {
                   2607: # the key is somebody else's
                   2608: 	return 'error: The key is already in use';
                   2609:     }
1.344     www      2610: }
                   2611: 
1.364     www      2612: # ------------------------------------------ put an additional comment on a key
                   2613: 
                   2614: sub comment_access_key {
                   2615: #
                   2616: # a valid key looks like uname:udom#comments
                   2617: # comments are being appended
                   2618: #
                   2619:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2620:     $cdom=
1.620     albertel 2621:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2622:     $cnum=
1.620     albertel 2623:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2624:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2625:     if ($existing{$ckey}) {
                   2626:         $existing{$ckey}.='; '.$logentry;
                   2627: # ready to assign
1.367     www      2628:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2629:                                                  $cdom,$cnum) eq 'ok') {
                   2630: 	    return 'ok';
                   2631:         } else {
                   2632: 	    return 'error: Count not store comment.';
                   2633:         }
                   2634:     } else {
                   2635: # the key does not exist
                   2636: 	return 'error: The key does not exist';
                   2637:     }
                   2638: }
                   2639: 
1.344     www      2640: # ------------------------------------------------------ Generate a set of keys
                   2641: 
                   2642: sub generate_access_keys {
1.364     www      2643:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2644:     $cdom=
1.620     albertel 2645:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2646:     $cnum=
1.620     albertel 2647:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2648:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2649:     unless (($cdom) && ($cnum)) { return 0; }
                   2650:     if ($number>10000) { return 0; }
                   2651:     sleep(2); # make sure don't get same seed twice
                   2652:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2653:     my $total=0;
                   2654:     for (my $i=1;$i<=$number;$i++) {
                   2655:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2656:                   sprintf("%lx",int(100000*rand)).'-'.
                   2657:                   sprintf("%lx",int(100000*rand));
                   2658:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2659:        $newkey=~s/0/h/g; # and also 0 and O
                   2660:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2661:        if ($existing{$newkey}) {
                   2662:            $i--;
                   2663:        } else {
1.364     www      2664: 	  if (&put('accesskeys',
                   2665:               { $newkey => '# generated '.localtime().
1.620     albertel 2666:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2667:                            '; '.$logentry },
                   2668: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2669:               $total++;
                   2670: 	  }
                   2671:        }
                   2672:     }
1.620     albertel 2673:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2674:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2675:     return $total;
                   2676: }
                   2677: 
                   2678: # ------------------------------------------------------- Validate an accesskey
                   2679: 
                   2680: sub validate_access_key {
                   2681:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2682:     $cdom=
1.620     albertel 2683:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2684:     $cnum=
1.620     albertel 2685:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2686:     $udom=$env{'user.domain'} unless (defined($udom));
                   2687:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2688:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2689:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2690: }
                   2691: 
                   2692: # ------------------------------------- Find the section of student in a course
1.652     albertel 2693: sub devalidate_getsection_cache {
                   2694:     my ($udom,$unam,$courseid)=@_;
                   2695:     my $hashid="$udom:$unam:$courseid";
                   2696:     &devalidate_cache_new('getsection',$hashid);
                   2697: }
1.298     matthew  2698: 
1.815     albertel 2699: sub courseid_to_courseurl {
                   2700:     my ($courseid) = @_;
                   2701:     #already url style courseid
                   2702:     return $courseid if ($courseid =~ m{^/});
                   2703: 
                   2704:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2705: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2706: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2707: 	return "/$cdom/$cnum";
                   2708:     }
                   2709: 
                   2710:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2711:     if (exists($courseinfo{'num'})) {
                   2712: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2713:     }
                   2714: 
                   2715:     return undef;
                   2716: }
                   2717: 
1.298     matthew  2718: sub getsection {
                   2719:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2720:     my $cachetime=1800;
1.551     albertel 2721: 
                   2722:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2723:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2724:     if (defined($cached)) { return $result; }
                   2725: 
1.298     matthew  2726:     my %Pending; 
                   2727:     my %Expired;
                   2728:     #
                   2729:     # Each role can either have not started yet (pending), be active, 
                   2730:     #    or have expired.
                   2731:     #
                   2732:     # If there is an active role, we are done.
                   2733:     #
                   2734:     # If there is more than one role which has not started yet, 
                   2735:     #     choose the one which will start sooner
                   2736:     # If there is one role which has not started yet, return it.
                   2737:     #
                   2738:     # If there is more than one expired role, choose the one which ended last.
                   2739:     # If there is a role which has expired, return it.
                   2740:     #
1.815     albertel 2741:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2742:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2743:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2744:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2745:         my $section=$1;
                   2746:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2747:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2748:         my $now=time;
1.548     albertel 2749:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2750:             $Expired{$end}=$section;
                   2751:             next;
                   2752:         }
1.548     albertel 2753:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2754:             $Pending{$start}=$section;
                   2755:             next;
                   2756:         }
1.599     albertel 2757:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2758:     }
                   2759:     #
                   2760:     # Presumedly there will be few matching roles from the above
                   2761:     # loop and the sorting time will be negligible.
                   2762:     if (scalar(keys(%Pending))) {
                   2763:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2764:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2765:     } 
                   2766:     if (scalar(keys(%Expired))) {
                   2767:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2768:         my $time = pop(@sorted);
1.599     albertel 2769:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2770:     }
1.599     albertel 2771:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2772: }
1.70      www      2773: 
1.599     albertel 2774: sub save_cache {
                   2775:     &purge_remembered();
1.722     albertel 2776:     #&Apache::loncommon::validate_page();
1.620     albertel 2777:     undef(%env);
1.780     albertel 2778:     undef($env_loaded);
1.599     albertel 2779: }
1.452     albertel 2780: 
1.599     albertel 2781: my $to_remember=-1;
                   2782: my %remembered;
                   2783: my %accessed;
                   2784: my $kicks=0;
                   2785: my $hits=0;
1.849     albertel 2786: sub make_key {
                   2787:     my ($name,$id) = @_;
1.872     albertel 2788:     if (length($id) > 65 
                   2789: 	&& length(&escape($id)) > 200) {
                   2790: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2791:     }
1.849     albertel 2792:     return &escape($name.':'.$id);
                   2793: }
                   2794: 
1.599     albertel 2795: sub devalidate_cache_new {
                   2796:     my ($name,$id,$debug) = @_;
                   2797:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2798:     my $remembered_id=$name.':'.$id;
1.849     albertel 2799:     $id=&make_key($name,$id);
1.599     albertel 2800:     $memcache->delete($id);
1.1172.2.81  raeburn  2801:     delete($remembered{$remembered_id});
                   2802:     delete($accessed{$remembered_id});
1.599     albertel 2803: }
                   2804: 
                   2805: sub is_cached_new {
                   2806:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2807:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2808:                                      # keys in %remembered hash, which persists for
                   2809:                                      # duration of request (no restriction on key length).
                   2810:     if (exists($remembered{$remembered_id})) {
                   2811: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2812: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2813: 	$hits++;
1.1172.2.81  raeburn  2814: 	return ($remembered{$remembered_id},1);
1.599     albertel 2815:     }
1.1172.2.81  raeburn  2816:     $id=&make_key($name,$id);
1.599     albertel 2817:     my $value = $memcache->get($id);
                   2818:     if (!(defined($value))) {
                   2819: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2820: 	return (undef,undef);
1.416     albertel 2821:     }
1.599     albertel 2822:     if ($value eq '__undef__') {
                   2823: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2824: 	$value=undef;
                   2825:     }
1.1172.2.81  raeburn  2826:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2827:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2828:     return ($value,1);
                   2829: }
                   2830: 
                   2831: sub do_cache_new {
                   2832:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2833:     my $remembered_id=$name.':'.$id;
1.849     albertel 2834:     $id=&make_key($name,$id);
1.599     albertel 2835:     my $setvalue=$value;
                   2836:     if (!defined($setvalue)) {
                   2837: 	$setvalue='__undef__';
                   2838:     }
1.623     albertel 2839:     if (!defined($time) ) {
                   2840: 	$time=600;
                   2841:     }
1.599     albertel 2842:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2843:     my $result = $memcache->set($id,$setvalue,$time);
                   2844:     if (! $result) {
1.872     albertel 2845: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2846: 	$memcache->disconnect_all();
1.872     albertel 2847:     }
1.600     albertel 2848:     # need to make a copy of $value
1.1172.2.81  raeburn  2849:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2850:     return $value;
                   2851: }
                   2852: 
                   2853: sub make_room {
1.1172.2.81  raeburn  2854:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2855: 
1.1172.2.81  raeburn  2856:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2857:                                     : $value;
1.599     albertel 2858:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2859:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2860:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2861:     my $to_kick;
                   2862:     my $max_time=0;
                   2863:     foreach my $other (keys(%accessed)) {
                   2864: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2865: 	    $to_kick=$other;
                   2866: 	    $max_time=&tv_interval($accessed{$other});
                   2867: 	}
                   2868:     }
                   2869:     delete($remembered{$to_kick});
                   2870:     delete($accessed{$to_kick});
                   2871:     $kicks++;
                   2872:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2873:     return;
                   2874: }
                   2875: 
1.599     albertel 2876: sub purge_remembered {
1.604     albertel 2877:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2878:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2879:     undef(%remembered);
                   2880:     undef(%accessed);
1.428     albertel 2881: }
1.70      www      2882: # ------------------------------------- Read an entry from a user's environment
                   2883: 
                   2884: sub userenvironment {
                   2885:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2886:     my $items;
                   2887:     foreach my $item (@what) {
                   2888:         $items.=&escape($item).'&';
                   2889:     }
                   2890:     $items=~s/\&$//;
1.70      www      2891:     my %returnhash=();
1.1009    raeburn  2892:     my $uhome = &homeserver($unam,$udom);
                   2893:     unless ($uhome eq 'no_host') {
                   2894:         my @answer=split(/\&/, 
                   2895:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2896:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2897:             return %returnhash;
                   2898:         }
1.1009    raeburn  2899:         my $i;
                   2900:         for ($i=0;$i<=$#what;$i++) {
                   2901: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2902:         }
1.70      www      2903:     }
                   2904:     return %returnhash;
1.1       albertel 2905: }
                   2906: 
1.617     albertel 2907: # ---------------------------------------------------------- Get a studentphoto
                   2908: sub studentphoto {
                   2909:     my ($udom,$unam,$ext) = @_;
                   2910:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2911:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2912:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2913:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2914:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2915:             } else {
                   2916:                 my ($result,$perm_reqd)=
1.707     albertel 2917: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2918:                 if ($result eq 'ok') {
                   2919:                     if (!($perm_reqd eq 'yes')) {
                   2920:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2921:                     }
                   2922:                 }
                   2923:             }
                   2924:         }
                   2925:     } else {
                   2926:         my ($result,$perm_reqd) = 
1.707     albertel 2927: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2928:         if ($result eq 'ok') {
                   2929:             if (!($perm_reqd eq 'yes')) {
                   2930:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2931:             }
                   2932:         }
                   2933:     }
                   2934:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2935: }
                   2936: 
                   2937: sub retrievestudentphoto {
                   2938:     my ($udom,$unam,$ext,$type) = @_;
                   2939:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2940:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2941:     if ($ret eq 'ok') {
                   2942:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2943:         if ($type eq 'thumbnail') {
                   2944:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2945:         }
                   2946:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2947:         return $tokenurl;
                   2948:     } else {
                   2949:         if ($type eq 'thumbnail') {
                   2950:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2951:         } else { 
                   2952:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2953:         }
1.617     albertel 2954:     }
                   2955: }
                   2956: 
1.263     www      2957: # -------------------------------------------------------------------- New chat
                   2958: 
                   2959: sub chatsend {
1.724     raeburn  2960:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2961:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2962:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2963:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2964:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2965: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2966: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2967: }
                   2968: 
                   2969: # ------------------------------------------ Find current version of a resource
                   2970: 
                   2971: sub getversion {
                   2972:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2973:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2974:     return &currentversion(&filelocation('',$fname));
                   2975: }
                   2976: 
                   2977: sub currentversion {
                   2978:     my $fname=shift;
                   2979:     my $author=$fname;
                   2980:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2981:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2982:     my $home=&homeserver($uname,$udom);
1.292     www      2983:     if ($home eq 'no_host') { 
                   2984:         return -1; 
                   2985:     }
1.1112    www      2986:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2987:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2988: 	return -1;
                   2989:     }
1.1112    www      2990:     return $answer;
1.263     www      2991: }
                   2992: 
1.1111    www      2993: #
                   2994: # Return special version number of resource if set by override, empty otherwise
                   2995: #
                   2996: sub usedversion {
                   2997:     my $fname=shift;
                   2998:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2999:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3000:     if ($urlversion) { return $urlversion; }
                   3001:     return '';
                   3002: }
                   3003: 
1.1       albertel 3004: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3005: 
1.1       albertel 3006: sub subscribe {
                   3007:     my $fname=shift;
1.761     raeburn  3008:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3009:     $fname=~s/[\n\r]//g;
1.1       albertel 3010:     my $author=$fname;
                   3011:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3012:     my ($udom,$uname)=split(/\//,$author);
                   3013:     my $home=homeserver($uname,$udom);
1.335     albertel 3014:     if ($home eq 'no_host') {
                   3015:         return 'not_found';
1.1       albertel 3016:     }
                   3017:     my $answer=reply("sub:$fname",$home);
1.64      www      3018:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3019: 	$answer.=' by '.$home;
                   3020:     }
1.1       albertel 3021:     return $answer;
                   3022: }
                   3023:     
1.8       www      3024: # -------------------------------------------------------------- Replicate file
                   3025: 
                   3026: sub repcopy {
                   3027:     my $filename=shift;
1.23      www      3028:     $filename=~s/\/+/\//g;
1.1142    raeburn  3029:     my $londocroot = $perlvar{'lonDocRoot'};
                   3030:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3031:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3032:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3033: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3034: 	return &repcopy_userfile($filename);
                   3035:     }
1.532     albertel 3036:     $filename=~s/[\n\r]//g;
1.8       www      3037:     my $transname="$filename.in.transfer";
1.828     www      3038: # FIXME: this should flock
1.607     raeburn  3039:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3040:     my $remoteurl=subscribe($filename);
1.64      www      3041:     if ($remoteurl =~ /^con_lost by/) {
                   3042: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3043:            return 'unavailable';
1.8       www      3044:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3045: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3046: 	   return 'not_found';
1.64      www      3047:     } elsif ($remoteurl =~ /^rejected by/) {
                   3048: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3049:            return 'forbidden';
1.20      www      3050:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3051:            return 'ok';
1.8       www      3052:     } else {
1.290     www      3053:         my $author=$filename;
                   3054:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3055:         my ($udom,$uname)=split(/\//,$author);
                   3056:         my $home=homeserver($uname,$udom);
                   3057:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3058:            my @parts=split(/\//,$filename);
                   3059:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3060:            if ($path ne "$londocroot/res") {
1.8       www      3061:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3062: 	       return 'bad_request';
1.8       www      3063:            }
                   3064:            my $count;
                   3065:            for ($count=5;$count<$#parts;$count++) {
                   3066:                $path.="/$parts[$count]";
                   3067:                if ((-e $path)!=1) {
                   3068: 		   mkdir($path,0777);
                   3069:                }
                   3070:            }
                   3071:            my $ua=new LWP::UserAgent;
                   3072:            my $request=new HTTP::Request('GET',"$remoteurl");
                   3073:            my $response=$ua->request($request,$transname);
                   3074:            if ($response->is_error()) {
                   3075: 	       unlink($transname);
                   3076:                my $message=$response->status_line;
1.672     albertel 3077:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3078:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3079:                return 'unavailable';
1.8       www      3080:            } else {
1.16      www      3081: 	       if ($remoteurl!~/\.meta$/) {
                   3082:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   3083:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   3084:                   if ($mresponse->is_error()) {
                   3085: 		      unlink($filename.'.meta');
                   3086:                       &logthis(
1.672     albertel 3087:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3088:                   }
                   3089: 	       }
1.8       www      3090:                rename($transname,$filename);
1.607     raeburn  3091:                return 'ok';
1.8       www      3092:            }
1.290     www      3093:        }
1.8       www      3094:     }
1.330     www      3095: }
                   3096: 
1.1172.2.118.  .5(raebu 3097:20): # ------------------------------------------------- Unsubscribe from a resource
                   3098:20): 
                   3099:20): sub unsubscribe {
                   3100:20):     my ($fname) = @_;
                   3101:20):     my $answer;
                   3102:20):     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3103:20):     $fname=~s/[\n\r]//g;
                   3104:20):     my $author=$fname;
                   3105:20):     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3106:20):     my ($udom,$uname)=split(/\//,$author);
                   3107:20):     my $home=homeserver($uname,$udom);
                   3108:20):     if ($home eq 'no_host') {
                   3109:20):         $answer = 'no_host';
                   3110:20):     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3111:20):         $answer = 'home';
                   3112:20):     } else {
          .7(raebu 3113:20):         $answer = reply("unsub:$fname",$home);
          .5(raebu 3114:20):     }
                   3115:20):     return $answer;
                   3116:20): }
                   3117:20): 
1.330     www      3118: # ------------------------------------------------ Get server side include body
                   3119: sub ssi_body {
1.381     albertel 3120:     my ($filelink,%form)=@_;
1.606     matthew  3121:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3122:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3123:     }
1.953     www      3124:     my $output='';
                   3125:     my $response;
1.980     raeburn  3126:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3127:        ($output,$response)=&externalssi($filelink);
1.953     www      3128:     } else {
1.1004    droeschl 3129:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3130:        $filelink .= 'inhibitmenu=yes';
1.953     www      3131:        ($output,$response)=&ssi($filelink,%form);
                   3132:     }
1.778     albertel 3133:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3134:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3135:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3136:     if (wantarray) {
                   3137:         return ($output, $response);
                   3138:     } else {
                   3139:         return $output;
                   3140:     }
1.8       www      3141: }
                   3142: 
1.15      www      3143: # --------------------------------------------------------- Server Side Include
                   3144: 
1.782     albertel 3145: sub absolute_url {
                   3146:     my ($host_name) = @_;
                   3147:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3148:     if ($host_name eq '') {
                   3149: 	$host_name = $ENV{'SERVER_NAME'};
                   3150:     }
                   3151:     return $protocol.$host_name;
                   3152: }
                   3153: 
1.942     foxr     3154: #
                   3155: #   Server side include.
                   3156: # Parameters:
                   3157: #  fn     Possibly encrypted resource name/id.
                   3158: #  form   Hash that describes how the rendering should be done
                   3159: #         and other things.
1.944     foxr     3160: # Returns:
1.950     raeburn  3161: #   Scalar context: The content of the response.
                   3162: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3163: #     
1.15      www      3164: sub ssi {
                   3165: 
1.944     foxr     3166:     my ($fn,%form)=@_;
1.1172.2.100  raeburn  3167:     my ($request,$response);
1.711     albertel 3168: 
                   3169:     $form{'no_update_last_known'}=1;
1.895     albertel 3170:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3171:     if (%form) {
1.782     albertel 3172:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  3173:       $request->content(join('&',map {
                   3174:             my $name = escape($_);
                   3175:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3176:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3177:             : &escape($form{$_}) );
                   3178:         } keys(%form)));
1.23      www      3179:     } else {
1.782     albertel 3180:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3181:     }
                   3182: 
1.15      www      3183:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3184: 
1.1172.2.101  raeburn  3185:     if (($env{'request.course.id'}) &&
                   3186:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3187:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3188:         ($form{'grade_symb'} ne '') &&
                   3189:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3190:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3191:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3192:             my $ua=new LWP::UserAgent;
                   3193:             $ua->local_address('127.0.0.1');
                   3194:             $response = $ua->request($request);
                   3195:         } else {
                   3196:             {
                   3197:                 require LWP::Protocol::http;
                   3198:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3199:                 my $ua=new LWP::UserAgent;
                   3200:                 $response = $ua->request($request);
                   3201:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3202:             }
                   3203:         }
                   3204:     } else {
                   3205:         my $ua=new LWP::UserAgent;
                   3206:         $response = $ua->request($request);
                   3207:     }
1.944     foxr     3208:     if (wantarray) {
1.1172.2.3  raeburn  3209: 	return ($response->content, $response);
1.944     foxr     3210:     } else {
1.1172.2.3  raeburn  3211: 	return $response->content;
1.942     foxr     3212:     }
1.324     www      3213: }
                   3214: 
                   3215: sub externalssi {
                   3216:     my ($url)=@_;
                   3217:     my $ua=new LWP::UserAgent;
                   3218:     my $request=new HTTP::Request('GET',$url);
                   3219:     my $response=$ua->request($request);
1.954     raeburn  3220:     if (wantarray) {
                   3221:         return ($response->content, $response);
                   3222:     } else {
                   3223:         return $response->content;
                   3224:     }
1.15      www      3225: }
1.254     www      3226: 
1.1172.2.98  raeburn  3227: # If the local copy of a replicated resource is outdated, trigger a
                   3228: # connection from the homeserver to flush the delayed queue. If no update
                   3229: # happens, remove local copies of outdated resource (and corresponding
                   3230: # metadata file).
                   3231: 
                   3232: sub remove_stale_resfile {
                   3233:     my ($url) = @_;
                   3234:     my $removed;
                   3235:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3236:         my $audom = $1;
                   3237:         my $auname = $2;
                   3238:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3239:             my $homeserver = &homeserver($auname,$audom);
                   3240:             unless (($homeserver eq 'no_host') ||
                   3241:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3242:                 my $fname = &filelocation('',$url);
                   3243:                 if (-e $fname) {
                   3244:                     my $hostname = &hostname($homeserver);
                   3245:                     if ($hostname) {
1.1172.2.118.  .3(raebu 3246:20):                         my $protocol = $protocol{$homeserver};
                   3247:20):                         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98  raeburn  3248:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.118.  .3(raebu 3249:20):                         my $ua=new LWP::UserAgent;
                   3250:20):                         $ua->timeout(5);
1.1172.2.98  raeburn  3251:                         my $request=new HTTP::Request('HEAD',$uri);
                   3252:                         my $response=$ua->request($request);
                   3253:                         if ($response->is_success()) {
                   3254:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3255:                             my $locmodtime = (stat($fname))[9];
                   3256:                             if ($locmodtime < $remmodtime) {
                   3257:                                 my $stale;
                   3258:                                 my $answer = &reply('pong',$homeserver);
                   3259:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3260:                                     sleep(0.2);
                   3261:                                     $locmodtime = (stat($fname))[9];
                   3262:                                     if ($locmodtime < $remmodtime) {
                   3263:                                         my $posstransfer = $fname.'.in.transfer';
                   3264:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3265:                                             $removed = 1;
                   3266:                                         } else {
                   3267:                                             $stale = 1;
                   3268:                                         }
                   3269:                                     } else {
                   3270:                                         $removed = 1;
                   3271:                                     }
                   3272:                                 } else {
                   3273:                                     $stale = 1;
                   3274:                                 }
                   3275:                                 if ($stale) {
1.1172.2.118.  .5(raebu 3276:20):                                     if (unlink($fname)) {
                   3277:20):                                         if ($uri!~/\.meta$/) {
                   3278:20):                                             if (-e $fname.'.meta') {
                   3279:20):                                                 unlink($fname.'.meta');
                   3280:20):                                             }
                   3281:20):                                         }
                   3282:20):                                         my $unsubresult = &unsubscribe($fname);
                   3283:20):                                         unless ($unsubresult eq 'ok') {
                   3284:20):                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3285:20):                                         }
                   3286:20):                                         $removed = 1;
1.1172.2.98  raeburn  3287:                                     }
                   3288:                                 }
                   3289:                             }
                   3290:                         }
                   3291:                     }
                   3292:                 }
                   3293:             }
                   3294:         }
                   3295:     }
                   3296:     return $removed;
                   3297: }
                   3298: 
1.492     albertel 3299: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3300: 
                   3301: sub allowuploaded {
                   3302:     my ($srcurl,$url)=@_;
                   3303:     $url=&clutter(&declutter($url));
                   3304:     my $dir=$url;
                   3305:     $dir=~s/\/[^\/]+$//;
                   3306:     my %httpref=();
                   3307:     my $httpurl=&hreflocation('',$url);
                   3308:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3309:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3310: }
1.477     raeburn  3311: 
1.1172.2.13  raeburn  3312: #
                   3313: # Determine if the current user should be able to edit a particular resource,
                   3314: # when viewing in course context.
                   3315: # (a) When viewing resource used to determine if "Edit" item is included in
                   3316: #     Functions.
                   3317: # (b) When displaying folder contents in course editor, used to determine if
                   3318: #     "Edit" link will be displayed alongside resource.
                   3319: #
                   3320: #  input: six args -- filename (decluttered), course number, course domain,
                   3321: #                   url, symb (if registered) and group (if this is a group
                   3322: #                   item -- e.g., bulletin board, group page etc.).
                   3323: #  output: array of five scalars --
                   3324: #          $cfile -- url for file editing if editable on current server
                   3325: #          $home -- homeserver of resource (i.e., for author if published,
                   3326: #                                           or course if uploaded.).
                   3327: #          $switchserver --  1 if server switch will be needed.
                   3328: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3329: #          $forceview -- 1 if icon/link should be to go to view mode
                   3330: #
                   3331: 
                   3332: sub can_edit_resource {
                   3333:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3334:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3335: #
                   3336: # For aboutme pages user can only edit his/her own.
                   3337: #
                   3338:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3339:         my ($sdom,$sname) = ($1,$2);
                   3340:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3341:             $home = $env{'user.home'};
                   3342:             $cfile = $resurl;
                   3343:             if ($env{'form.forceedit'}) {
                   3344:                 $forceview = 1;
                   3345:             } else {
                   3346:                 $forceedit = 1;
                   3347:             }
                   3348:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3349:         } else {
                   3350:             return;
                   3351:         }
                   3352:     }
                   3353: 
                   3354:     if ($env{'request.course.id'}) {
                   3355:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3356:         if ($group ne '') {
                   3357: # if this is a group homepage or group bulletin board, check group privs
                   3358:             my $allowed = 0;
                   3359:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3360:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3361:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3362:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3363:                     $allowed = 1;
                   3364:                 }
                   3365:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3366:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3367:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3368:                     $allowed = 1;
                   3369:                 }
                   3370:             }
                   3371:             if ($allowed) {
                   3372:                 $home=&homeserver($cnum,$cdom);
                   3373:                 if ($env{'form.forceedit'}) {
                   3374:                     $forceview = 1;
                   3375:                 } else {
                   3376:                     $forceedit = 1;
                   3377:                 }
                   3378:                 $cfile = $resurl;
                   3379:             } else {
                   3380:                 return;
                   3381:             }
                   3382:         } else {
1.1172.2.15  raeburn  3383:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3384:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3385:                     return;
                   3386:                 }
                   3387:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3388: #
                   3389: # No edit allowed where CC has switched to student role.
                   3390: #
                   3391:                 return;
                   3392:             }
                   3393:         }
                   3394:     }
                   3395: 
                   3396:     if ($file ne '') {
                   3397:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3398:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3399:                 $uploaded = 1;
                   3400:                 $incourse = 1;
                   3401:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3402:                     $cfile = &hreflocation('',$file);
                   3403:                     if ($env{'form.forceedit'}) {
                   3404:                         $forceview = 1;
                   3405:                     } else {
                   3406:                         $forceedit = 1;
                   3407:                     }
                   3408:                 }
                   3409:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3410:                 $incourse = 1;
                   3411:                 if ($env{'form.forceedit'}) {
                   3412:                     $forceview = 1;
                   3413:                 } else {
                   3414:                     $forceedit = 1;
                   3415:                 }
                   3416:                 $cfile = $resurl;
                   3417:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3418:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3419:                     $incourse = 1;
                   3420:                     if ($env{'form.forceedit'}) {
                   3421:                         $forceview = 1;
                   3422:                     } else {
                   3423:                         $forceedit = 1;
                   3424:                     }
                   3425:                     $cfile = $resurl;
                   3426:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3427:                     $incourse = 1;
                   3428:                     $cfile = $resurl.'/smpedit';
                   3429:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3430:                     $incourse = 1;
                   3431:                     if ($env{'form.forceedit'}) {
                   3432:                         $forceview = 1;
                   3433:                     } else {
                   3434:                         $forceedit = 1;
                   3435:                     }
                   3436:                     $cfile = $resurl;
1.1172.2.118.  .5(raebu 3437:20):                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3438:20):                     my ($map,$id,$res) = &decode_symb($symb);
                   3439:20):                     if ($map =~ /\.page$/) {
                   3440:20):                         $incourse = 1;
                   3441:20):                         if ($env{'form.forceedit'}) {
                   3442:20):                             $forceview = 1;
                   3443:20):                             $cfile = $map;
                   3444:20):                         } else {
                   3445:20):                             $forceedit = 1;
                   3446:20):                             $cfile =  '/adm/wrapper'.$resurl;
                   3447:20):                         }
                   3448:20):                     }
          .1(raebu 3449:20):                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3450:20):                     $incourse = 1;
                   3451:20):                     if ($env{'form.forceedit'}) {
                   3452:20):                         $forceview = 1;
                   3453:20):                     } else {
                   3454:20):                         $forceedit = 1;
                   3455:20):                     }
                   3456:20):                     $cfile = $resurl;
1.1172.2.15  raeburn  3457:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3458:                     $incourse = 1;
                   3459:                     if ($env{'form.forceedit'}) {
                   3460:                         $forceview = 1;
                   3461:                     } else {
                   3462:                         $forceedit = 1;
                   3463:                     }
                   3464:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3465:                 }
                   3466:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3467:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3468:                 if (&is_on_map($template)) {
                   3469:                     $incourse = 1;
                   3470:                     $forceview = 1;
                   3471:                     $cfile = $template;
                   3472:                 }
                   3473:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118  raeburn  3474:                 $incourse = 1;
                   3475:                 if ($env{'form.forceedit'}) {
                   3476:                     $forceview = 1;
                   3477:                 } else {
                   3478:                     $forceedit = 1;
                   3479:                 }
                   3480:                 $cfile = $resurl;
1.1172.2.118.  .1(raebu 3481:20):             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3482:20):                 $incourse = 1;
                   3483:20):                 if ($env{'form.forceedit'}) {
                   3484:20):                     $forceview = 1;
                   3485:20):                 } else {
                   3486:20):                     $forceedit = 1;
                   3487:20):                 }
                   3488:20):                 $cfile = $resurl;
1.1172.2.13  raeburn  3489:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3490:                 $incourse = 1;
                   3491:                 $forceview = 1;
                   3492:                 if ($symb) {
                   3493:                     my ($map,$id,$res)=&decode_symb($symb);
                   3494:                     $env{'request.symb'} = $symb;
                   3495:                     $cfile = &clutter($res);
                   3496:                 } else {
                   3497:                     $cfile = $env{'form.suppurl'};
1.1172.2.118.  .1(raebu 3498:20):                     my $escfile = &unescape($cfile);
                   3499:20):                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3500:20):                         $cfile = '/adm/wrapper'.$escfile;
                   3501:20):                     } else {
                   3502:20):                         $escfile =~ s{^http://}{};
                   3503:20):                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3504:20):                     }
1.1172.2.13  raeburn  3505:                 }
1.1172.2.31  raeburn  3506:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3507:                 if ($env{'form.forceedit'}) {
                   3508:                     $forceview = 1;
                   3509:                 } else {
                   3510:                     $forceedit = 1;
                   3511:                 }
                   3512:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3513:             }
                   3514:         }
                   3515:         if ($uploaded || $incourse) {
                   3516:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3517:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3518:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3519:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3520:             # Check that the user has permission to edit this resource
                   3521:             my $setpriv = 1;
                   3522:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3523:             if (defined($cfudom)) {
                   3524:                 $home=&homeserver($cfuname,$cfudom);
                   3525:                 $cfile=$file;
                   3526:             }
                   3527:         }
                   3528:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3529:             (($home ne '') && ($home ne 'no_host'))) {
                   3530:             my @ids=&current_machine_ids();
                   3531:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3532:                 $switchserver=1;
                   3533:             }
                   3534:         }
                   3535:     }
                   3536:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3537: }
                   3538: 
                   3539: sub is_course_upload {
                   3540:     my ($file,$cnum,$cdom) = @_;
                   3541:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3542:     $uploadpath =~ s{^\/}{};
                   3543:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3544:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3545:         return 1;
                   3546:     }
                   3547:     return;
                   3548: }
                   3549: 
                   3550: sub in_course {
                   3551:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3552:     if ($hideprivileged) {
                   3553:         my $skipuser;
1.1172.2.23  raeburn  3554:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3555:         my @possdoms = ($cdom);
                   3556:         if ($coursehash{'checkforpriv'}) {
                   3557:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3558:         }
                   3559:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3560:             $skipuser = 1;
                   3561:             if ($coursehash{'nothideprivileged'}) {
                   3562:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3563:                     my $user;
                   3564:                     if ($item =~ /:/) {
                   3565:                         $user = $item;
                   3566:                     } else {
                   3567:                         $user = join(':',split(/[\@]/,$item));
                   3568:                     }
                   3569:                     if ($user eq $uname.':'.$udom) {
                   3570:                         undef($skipuser);
                   3571:                         last;
                   3572:                     }
                   3573:                 }
                   3574:             }
                   3575:             if ($skipuser) {
                   3576:                 return 0;
                   3577:             }
                   3578:         }
                   3579:     }
                   3580:     $type ||= 'any';
                   3581:     if (!defined($cdom) || !defined($cnum)) {
                   3582:         my $cid  = $env{'request.course.id'};
                   3583:         $cdom = $env{'course.'.$cid.'.domain'};
                   3584:         $cnum = $env{'course.'.$cid.'.num'};
                   3585:     }
                   3586:     my $typesref;
                   3587:     if (($type eq 'any') || ($type eq 'all')) {
                   3588:         $typesref = ['active','previous','future'];
                   3589:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3590:         $typesref = [$type];
                   3591:     }
                   3592:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3593:                               $typesref,undef,[$cdom]);
                   3594:     my ($tmp) = keys(%roles);
                   3595:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3596:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3597:     if (@course_roles > 0) {
                   3598:         return 1;
                   3599:     }
                   3600:     return 0;
                   3601: }
                   3602: 
1.478     albertel 3603: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3604: # input: action, courseID, current domain, intended
1.637     raeburn  3605: #        path to file, source of file, instruction to parse file for objects,
                   3606: #        ref to hash for embedded objects,
                   3607: #        ref to hash for codebase of java objects.
1.1095    raeburn  3608: #        reference to scalar to accommodate mime type determined
                   3609: #          from File::MMagic if $parser = parse.
1.637     raeburn  3610: #
1.485     raeburn  3611: # output: url to file (if action was uploaddoc), 
                   3612: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3613: #
1.478     albertel 3614: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3615: # course.
1.477     raeburn  3616: #
1.478     albertel 3617: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3618: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3619: #          course's home server.
1.477     raeburn  3620: #
1.478     albertel 3621: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3622: #          be copied from $source (current location) to 
                   3623: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3624: #         and will then be copied to
                   3625: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3626: #         course's home server.
1.485     raeburn  3627: #
1.481     raeburn  3628: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3629: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3630: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3631: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3632: #         in course's home server.
1.637     raeburn  3633: #
1.477     raeburn  3634: 
                   3635: sub process_coursefile {
1.1095    raeburn  3636:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3637:         $mimetype)=@_;
1.477     raeburn  3638:     my $fetchresult;
1.638     albertel 3639:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3640:     if ($action eq 'propagate') {
1.638     albertel 3641:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3642: 			     $home);
1.481     raeburn  3643:     } else {
1.477     raeburn  3644:         my $fpath = '';
                   3645:         my $fname = $file;
1.478     albertel 3646:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3647:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3648:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3649:         if ($action eq 'copy') {
                   3650:             if ($source eq '') {
                   3651:                 $fetchresult = 'no source file';
                   3652:                 return $fetchresult;
                   3653:             } else {
                   3654:                 my $destination = $filepath.'/'.$fname;
                   3655:                 rename($source,$destination);
                   3656:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3657:                                  $home);
1.481     raeburn  3658:             }
                   3659:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3660:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3661:             print $fh $env{'form.'.$source};
1.481     raeburn  3662:             close($fh);
1.637     raeburn  3663:             if ($parser eq 'parse') {
1.1024    raeburn  3664:                 my $mm = new File::MMagic;
1.1095    raeburn  3665:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3666:                 if ($type eq 'text/html') {
1.1024    raeburn  3667:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3668:                     unless ($parse_result eq 'ok') {
                   3669:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3670:                     }
1.637     raeburn  3671:                 }
1.1095    raeburn  3672:                 if (ref($mimetype)) {
                   3673:                     $$mimetype = $type;
                   3674:                 } 
1.637     raeburn  3675:             }
1.477     raeburn  3676:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3677:                                  $home);
1.481     raeburn  3678:             if ($fetchresult eq 'ok') {
                   3679:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3680:             } else {
                   3681:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3682:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3683:                 return '/adm/notfound.html';
                   3684:             }
1.477     raeburn  3685:         }
                   3686:     }
1.485     raeburn  3687:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3688:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3689:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3690:     }
                   3691:     return $fetchresult;
                   3692: }
                   3693: 
1.637     raeburn  3694: sub build_filepath {
                   3695:     my ($fpath) = @_;
                   3696:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3697:     unless ($fpath eq '') {
                   3698:         my @parts=split('/',$fpath);
                   3699:         foreach my $part (@parts) {
                   3700:             $filepath.= '/'.$part;
                   3701:             if ((-e $filepath)!=1) {
                   3702:                 mkdir($filepath,0777);
                   3703:             }
                   3704:         }
                   3705:     }
                   3706:     return $filepath;
                   3707: }
                   3708: 
                   3709: sub store_edited_file {
1.638     albertel 3710:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3711:     my $file = $primary_url;
                   3712:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3713:     my $fpath = '';
                   3714:     my $fname = $file;
                   3715:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3716:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3717:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3718:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3719:     print $fh $content;
                   3720:     close($fh);
1.638     albertel 3721:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3722:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3723: 			  $home);
1.637     raeburn  3724:     if ($$fetchresult eq 'ok') {
                   3725:         return '/uploaded/'.$fpath.'/'.$fname;
                   3726:     } else {
1.638     albertel 3727:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3728: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3729:         return '/adm/notfound.html';
                   3730:     }
                   3731: }
                   3732: 
1.531     albertel 3733: sub clean_filename {
1.831     albertel 3734:     my ($fname,$args)=@_;
1.315     www      3735: # Replace Windows backslashes by forward slashes
1.257     www      3736:     $fname=~s/\\/\//g;
1.831     albertel 3737:     if (!$args->{'keep_path'}) {
                   3738:         # Get rid of everything but the actual filename
                   3739: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3740:     }
1.315     www      3741: # Replace spaces by underscores
                   3742:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  3743: # Transliterate non-ascii text to ascii
                   3744:     my $lang = &Apache::lonlocal::current_language();
                   3745:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3746: # Replace all other weird characters by nothing
1.831     albertel 3747:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3748: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3749: # numbers
                   3750:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3751:     return $fname;
                   3752: }
1.1172.2.110  raeburn  3753: 
1.1051    raeburn  3754: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3755: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3756: # image with the same aspect ratio as the original, but with dimensions which do 
                   3757: # not exceed $resizewidth and $resizeheight.
                   3758:  
1.984     neumanie 3759: sub resizeImage {
1.1051    raeburn  3760:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3761:     my $ima = Image::Magick->new;
                   3762:     my $resized;
                   3763:     if (-e $img_path) {
                   3764:         $ima->Read($img_path);
                   3765:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3766:             my $width = $ima->Get('width');
                   3767:             my $height = $ima->Get('height');
                   3768:             if ($width > $resizewidth) {
                   3769: 	        my $factor = $width/$resizewidth;
                   3770:                 my $newheight = $height/$factor;
                   3771:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3772:                 $resized = 1;
                   3773:             }
                   3774:         }
                   3775:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3776:             my $width = $ima->Get('width');
                   3777:             my $height = $ima->Get('height');
                   3778:             if ($height > $resizeheight) {
                   3779:                 my $factor = $height/$resizeheight;
                   3780:                 my $newwidth = $width/$factor;
                   3781:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3782:                 $resized = 1;
                   3783:             }
                   3784:         }
                   3785:         if ($resized) {
                   3786:             $ima->Write($img_path);
                   3787:         }
                   3788:     }
                   3789:     return;
1.977     amueller 3790: }
                   3791: 
1.608     albertel 3792: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3793: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3794: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3795: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.109  raeburn  3796: #                                    canceloverwrite, scantron or ''. 
1.1090    raeburn  3797: #                   if 'coursedoc': upload to the current course
                   3798: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3799: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3800: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3801: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  3802: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3803: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3804: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   3805: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3806: #        $allfiles - reference to hash for embedded objects
                   3807: #        $codebase - reference to hash for codebase of java objects
                   3808: #        $desuname - username for permanent storage of uploaded file
                   3809: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3810: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3811: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3812: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3813: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3814: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3815: #                    from File::MMagic.
1.858     raeburn  3816: # 
1.686     albertel 3817: # output: url of file in userspace, or error: <message> 
                   3818: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3819: 
1.531     albertel 3820: sub userfileupload {
1.1090    raeburn  3821:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3822:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3823:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3824:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3825:     $fname=&clean_filename($fname);
1.1090    raeburn  3826:     # See if there is anything left
1.257     www      3827:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  3828:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   3829:     if ($fname =~ /^\./) {
                   3830:         my ($s,$usec) = &gettimeofday();
                   3831:         while (length($usec) < 6) {
                   3832:             $usec = '0'.$usec;
                   3833:         }
                   3834:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   3835:     }
1.1090    raeburn  3836:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3837:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3838:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3839:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3840:         my $now = time;
1.1090    raeburn  3841:         my $filepath;
1.1095    raeburn  3842:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3843:              $filepath = 'tmp/helprequests/'.$now;
                   3844:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3845:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3846:                          '_'.$env{'user.domain'}.'/pending';
                   3847:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3848:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3849:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3850:                 $docudom = $destudom;
                   3851:             } else {
                   3852:                 $docudom = $env{'user.domain'};
                   3853:             }
1.1172.2.96  raeburn  3854:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3855:                 $docuname = $destuname;
                   3856:             } else {
                   3857:                 $docuname = $env{'user.name'};
                   3858:             }
                   3859:             if (exists($env{'form.group'})) {
                   3860:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3861:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3862:             }
                   3863:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3864:             if ($context eq 'canceloverwrite') {
                   3865:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3866:                 if (-e  $tempfile) {
                   3867:                     my @info = stat($tempfile);
                   3868:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3869:                         unlink($tempfile);
                   3870:                     }
                   3871:                 }
                   3872:                 return;
1.523     raeburn  3873:             }
                   3874:         }
1.1090    raeburn  3875:         # Create the directory if not present
1.741     raeburn  3876:         my @parts=split(/\//,$filepath);
                   3877:         my $fullpath = $perlvar{'lonDaemons'};
                   3878:         for (my $i=0;$i<@parts;$i++) {
                   3879:             $fullpath .= '/'.$parts[$i];
                   3880:             if ((-e $fullpath)!=1) {
                   3881:                 mkdir($fullpath,0777);
                   3882:             }
                   3883:         }
1.1172.2.96  raeburn  3884:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3885:         print $fh $env{'form.'.$formname};
                   3886:         close($fh);
1.1090    raeburn  3887:         if ($context eq 'existingfile') {
                   3888:             my @info = stat($fullpath.'/'.$fname);
                   3889:             return ($fullpath.'/'.$fname,$info[9]);
                   3890:         } else {
                   3891:             return $fullpath.'/'.$fname;
                   3892:         }
1.523     raeburn  3893:     }
1.995     raeburn  3894:     if ($subdir eq 'scantron') {
                   3895:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3896:     } else {
1.995     raeburn  3897:         $fname="$subdir/$fname";
                   3898:     }
1.1090    raeburn  3899:     if ($context eq 'coursedoc') {
1.638     albertel 3900: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3901: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3902:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3903:             return &finishuserfileupload($docuname,$docudom,
                   3904: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3905: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3906:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3907:         } else {
1.1172.2.21  raeburn  3908:             if ($env{'form.folder'}) {
                   3909:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3910:             }
1.638     albertel 3911:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3912: 				       $fname,$formname,$parser,
1.1095    raeburn  3913: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3914:         }
1.719     banghart 3915:     } elsif (defined($destuname)) {
                   3916:         my $docuname=$destuname;
                   3917:         my $docudom=$destudom;
1.860     raeburn  3918: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3919: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3920:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3921:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3922:     } else {
1.638     albertel 3923:         my $docuname=$env{'user.name'};
                   3924:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3925:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3926:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3927:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3928:         }
1.860     raeburn  3929: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3930: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3931:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3932:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3933:     }
1.271     www      3934: }
                   3935: 
                   3936: sub finishuserfileupload {
1.860     raeburn  3937:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3938:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3939:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3940:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3941:   
1.860     raeburn  3942:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3943:     $file=$fname;
                   3944:     if ($fname=~m|/|) {
                   3945:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3946: 	$path.=$fnamepath.'/';
                   3947:     }
1.259     www      3948:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3949:     my $count;
                   3950:     for ($count=4;$count<=$#parts;$count++) {
                   3951:         $filepath.="/$parts[$count]";
                   3952:         if ((-e $filepath)!=1) {
                   3953: 	    mkdir($filepath,0777);
                   3954:         }
                   3955:     }
1.984     neumanie 3956: 
1.258     www      3957: # Save the file
                   3958:     {
1.1172.2.96  raeburn  3959: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3960: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3961: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3962: 	    return '/adm/notfound.html';
                   3963: 	}
1.1090    raeburn  3964:         if ($context eq 'overwrite') {
1.1117    foxr     3965:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3966:             my $target = $filepath.'/'.$file;
                   3967:             if (-e $source) {
                   3968:                 my @info = stat($source);
                   3969:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3970:                     unless (&File::Copy::move($source,$target)) {
                   3971:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3972:                         return "Moving from $source failed";
                   3973:                     }
                   3974:                 } else {
                   3975:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3976:                 }
                   3977:             } else {
                   3978:                 return "Temporary file: $source missing";
                   3979:             }
                   3980:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3981: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3982: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3983: 	    return '/adm/notfound.html';
                   3984: 	}
1.570     albertel 3985: 	close(FH);
1.1051    raeburn  3986:         if ($resizewidth && $resizeheight) {
                   3987:             my $mm = new File::MMagic;
                   3988:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3989:             if ($mime_type =~ m{^image/}) {
                   3990: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3991:             }  
1.977     amueller 3992: 	}
1.258     www      3993:     }
1.1152    raeburn  3994:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3995:         if (ref($mimetype)) {
                   3996:             if ($$mimetype eq '') {
                   3997:                 my $mm = new File::MMagic;
                   3998:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3999:                 $$mimetype = $type;
                   4000:             }
                   4001:         }
                   4002:     }
1.1172.2.109  raeburn  4003:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4004:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4005:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4006:                                                        $allfiles,$codebase);
                   4007:             unless ($parse_result eq 'ok') {
                   4008:                 &logthis('Failed to parse '.$filepath.$file.
                   4009: 	   	         ' for embedded media: '.$parse_result); 
                   4010:             }
1.637     raeburn  4011:         }
1.1172.2.109  raeburn  4012:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4013:         my $format = $env{'form.scantron_format'};
                   4014:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4015:     }
1.860     raeburn  4016:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4017:         my $input = $filepath.'/'.$file;
                   4018:         my $output = $filepath.'/'.'tn-'.$file;
                   4019:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  4020:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4021:         system({$args[0]} @args);
1.860     raeburn  4022:         if (-e $filepath.'/'.'tn-'.$file) {
                   4023:             $fetchthumb  = 1; 
                   4024:         }
                   4025:     }
1.858     raeburn  4026:  
1.259     www      4027: # Notify homeserver to grep it
                   4028: #
1.984     neumanie 4029:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4030:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4031:     if ($fetchresult eq 'ok') {
1.860     raeburn  4032:         if ($fetchthumb) {
                   4033:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4034:             if ($thumbresult ne 'ok') {
                   4035:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4036:                          $docuhome.': '.$thumbresult);
                   4037:             }
                   4038:         }
1.259     www      4039: #
1.258     www      4040: # Return the URL to it
1.494     albertel 4041:         return '/uploaded/'.$path.$file;
1.263     www      4042:     } else {
1.494     albertel 4043:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4044: 		 ': '.$fetchresult);
1.263     www      4045:         return '/adm/notfound.html';
1.858     raeburn  4046:     }
1.493     albertel 4047: }
                   4048: 
1.637     raeburn  4049: sub extract_embedded_items {
1.961     raeburn  4050:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4051:     my @state = ();
1.1164    raeburn  4052:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4053:     my %javafiles = (
                   4054:                       codebase => '',
                   4055:                       code => '',
                   4056:                       archive => ''
                   4057:                     );
                   4058:     my %mediafiles = (
                   4059:                       src => '',
                   4060:                       movie => '',
                   4061:                      );
1.648     raeburn  4062:     my $p;
                   4063:     if ($content) {
                   4064:         $p = HTML::LCParser->new($content);
                   4065:     } else {
1.961     raeburn  4066:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4067:     }
1.641     albertel 4068:     while (my $t=$p->get_token()) {
1.640     albertel 4069: 	if ($t->[0] eq 'S') {
                   4070: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4071: 	    push(@state, $tagname);
1.648     raeburn  4072:             if (lc($tagname) eq 'allow') {
                   4073:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4074:             }
1.640     albertel 4075: 	    if (lc($tagname) eq 'img') {
                   4076: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4077: 	    }
1.886     albertel 4078: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  4079:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   4080: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   4081:                 }
1.886     albertel 4082: 	    }
1.645     raeburn  4083:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4084:                 my $src;
1.645     raeburn  4085:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4086:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4087:                 } else {
1.1164    raeburn  4088:                     if ($attr->{'src'} ne '') {
                   4089:                         $src = $attr->{'src'};
                   4090:                         &add_filetype($allfiles,$src,'src');
                   4091:                     }
                   4092:                 }
                   4093:                 my $text = $p->get_trimmed_text();
                   4094:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4095:                     my @swfargs = split(/,/,$1);
                   4096:                     foreach my $item (@swfargs) {
                   4097:                         $item =~ s/["']//g;
                   4098:                         $item =~ s/^\s+//;
                   4099:                         $item =~ s/\s+$//;
                   4100:                     }
                   4101:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4102:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4103:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4104:                         } else {
                   4105:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4106:                         }
                   4107:                     }
1.645     raeburn  4108:                 }
                   4109:             }
                   4110:             if (lc($tagname) eq 'link') {
                   4111:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4112:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4113:                 }
                   4114:             }
1.640     albertel 4115: 	    if (lc($tagname) eq 'object' ||
                   4116: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4117: 		foreach my $item (keys(%javafiles)) {
                   4118: 		    $javafiles{$item} = '';
                   4119: 		}
1.1164    raeburn  4120:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4121:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4122:                 }
1.640     albertel 4123: 	    }
                   4124: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4125: 		my $name = lc($attr->{'name'});
                   4126: 		foreach my $item (keys(%javafiles)) {
                   4127: 		    if ($name eq $item) {
                   4128: 			$javafiles{$item} = $attr->{'value'};
                   4129: 			last;
                   4130: 		    }
                   4131: 		}
1.1164    raeburn  4132:                 my $pathfrom;
1.640     albertel 4133: 		foreach my $item (keys(%mediafiles)) {
                   4134: 		    if ($name eq $item) {
1.1164    raeburn  4135:                         $pathfrom = $attr->{'value'};
                   4136:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4137: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4138: 			last;
                   4139: 		    }
                   4140: 		}
1.1164    raeburn  4141:                 if ($name eq 'flashvars') {
                   4142:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4143:                 }
                   4144:                 if ($pathfrom ne '') {
                   4145:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4146:                                          $pathfrom);
                   4147:                 }
1.640     albertel 4148: 	    }
                   4149: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4150: 		foreach my $item (keys(%javafiles)) {
                   4151: 		    if ($attr->{$item}) {
                   4152: 			$javafiles{$item} = $attr->{$item};
                   4153: 			last;
                   4154: 		    }
                   4155: 		}
                   4156: 		foreach my $item (keys(%mediafiles)) {
                   4157: 		    if ($attr->{$item}) {
                   4158: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4159: 			last;
                   4160: 		    }
                   4161: 		}
1.1164    raeburn  4162:                 if (lc($tagname) eq 'embed') {
                   4163:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4164:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4165:                                              $attr->{'src'});
                   4166:                     }
                   4167:                 }
1.640     albertel 4168: 	    }
1.1172.2.35  raeburn  4169:             if (lc($tagname) eq 'iframe') {
                   4170:                 my $src = $attr->{'src'} ;
                   4171:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4172:                     &add_filetype($allfiles,$src,'src');
                   4173:                 } elsif ($src =~ m{^/}) {
                   4174:                     if ($env{'request.course.id'}) {
                   4175:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4176:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4177:                         my $url = &hreflocation('',$fullpath);
                   4178:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4179:                             my $relpath = $1;
                   4180:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4181:                                 &add_filetype($allfiles,$1,'src');
                   4182:                             }
                   4183:                         }
                   4184:                     }
                   4185:                 }
                   4186:             }
1.1164    raeburn  4187:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4188:                 pop(@state);
1.1164    raeburn  4189:             }
1.640     albertel 4190: 	} elsif ($t->[0] eq 'E') {
                   4191: 	    my ($tagname) = ($t->[1]);
                   4192: 	    if ($javafiles{'codebase'} ne '') {
                   4193: 		$javafiles{'codebase'} .= '/';
                   4194: 	    }  
                   4195: 	    if (lc($tagname) eq 'applet' ||
                   4196: 		lc($tagname) eq 'object' ||
                   4197: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4198: 		) {
                   4199: 		foreach my $item (keys(%javafiles)) {
                   4200: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4201: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4202: 			&add_filetype($allfiles,$file,$item);
                   4203: 		    }
                   4204: 		}
                   4205: 	    } 
                   4206: 	    pop @state;
                   4207: 	}
                   4208:     }
1.1164    raeburn  4209:     foreach my $id (sort(keys(%flashvars))) {
                   4210:         if ($shockwave{$id} ne '') {
                   4211:             my @pairs = split(/\&/,$flashvars{$id});
                   4212:             foreach my $pair (@pairs) {
                   4213:                 my ($key,$value) = split(/\=/,$pair);
                   4214:                 if ($key eq 'thumb') {
                   4215:                     &add_filetype($allfiles,$value,$key);
                   4216:                 } elsif ($key eq 'content') {
                   4217:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4218:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4219:                     if ($ext ne '') {
                   4220:                         &add_filetype($allfiles,$path.$value,$ext);
                   4221:                     }
                   4222:                 }
                   4223:             }
                   4224:         }
                   4225:     }
1.637     raeburn  4226:     return 'ok';
                   4227: }
                   4228: 
1.639     albertel 4229: sub add_filetype {
                   4230:     my ($allfiles,$file,$type)=@_;
                   4231:     if (exists($allfiles->{$file})) {
                   4232: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4233: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4234: 	}
                   4235:     } else {
                   4236: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4237:     }
                   4238: }
                   4239: 
1.1164    raeburn  4240: sub embedded_dependency {
                   4241:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4242:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4243:         if (($identifier ne '') &&
                   4244:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4245:             ($pathfrom ne '')) {
                   4246:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4247:             foreach my $dep (@{$related->{$identifier}}) {
                   4248:                 &add_filetype($allfiles,$path.$dep,'object');
                   4249:             }
                   4250:         }
                   4251:     }
                   4252:     return;
                   4253: }
                   4254: 
1.1172.2.109  raeburn  4255: sub bubblesheet_converter {
                   4256:     my ($cdom,$fullpath,$config,$format) = @_;
                   4257:     if ((&domain($cdom) ne '') &&
                   4258:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4259:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4260:         my (%csvcols,%csvoptions);
                   4261:         if (ref($config->{'fields'}) eq 'HASH') {
                   4262:             %csvcols = %{$config->{'fields'}};
                   4263:         }
                   4264:         if (ref($config->{'options'}) eq 'HASH') {
                   4265:             %csvoptions = %{$config->{'options'}};
                   4266:         }
                   4267:         my %csvbynum = reverse(%csvcols);
                   4268:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4269:         if (keys(%scantronconf)) {
                   4270:             my %bynum = (
                   4271:                           $scantronconf{CODEstart} => 'CODEstart',
                   4272:                           $scantronconf{IDstart}   => 'IDstart',
                   4273:                           $scantronconf{PaperID}   => 'PaperID',
                   4274:                           $scantronconf{FirstName} => 'FirstName',
                   4275:                           $scantronconf{LastName}  => 'LastName',
                   4276:                           $scantronconf{Qstart}    => 'Qstart',
                   4277:                         );
                   4278:             my @ordered;
                   4279:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4280:                 push(@ordered,$bynum{$item});
                   4281:             }
                   4282:             my %mapstart = (
                   4283:                               CODEstart => 'CODE',
                   4284:                               IDstart   => 'ID',
                   4285:                               PaperID   => 'PaperID',
                   4286:                               FirstName => 'FirstName',
                   4287:                               LastName  => 'LastName',
                   4288:                               Qstart    => 'FirstQuestion',
                   4289:                            );
                   4290:             my %maplength = (
                   4291:                               CODEstart => 'CODElength',
                   4292:                               IDstart   => 'IDlength',
                   4293:                               PaperID   => 'PaperIDlength',
                   4294:                               FirstName => 'FirstNamelength',
                   4295:                               LastName  => 'LastNamelength',
                   4296:             );
                   4297:             if (open(my $fh,'<',$fullpath)) {
                   4298:                 my $output;
                   4299:                 my %lettdig = &letter_to_digits();
                   4300:                 my %diglett = reverse(%lettdig);
                   4301:                 my $numletts = scalar(keys(%lettdig));
                   4302:                 my $num = 0;
                   4303:                 while (my $line=<$fh>) {
                   4304:                     $num ++;
                   4305:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4306:                     $line =~ s{[\r\n]+$}{};
                   4307:                     my %found;
                   4308:                     my @values = split(/,/,$line);
                   4309:                     my ($qstart,$record);
                   4310:                     for (my $i=0; $i<@values; $i++) {
                   4311:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4312:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4313:                             if ($values[$i] eq '') {
                   4314:                                 $values[$i] = $scantronconf{'Qoff'};
                   4315:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4316:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4317:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4318:                                 }
                   4319:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4320:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4321:                                     $values[$i] = $diglett{$values[$i]};
                   4322:                                 }
                   4323:                             } else {
                   4324:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4325:                                     my $digit;
                   4326:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4327:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4328:                                         if ($values[$i] eq 'J') {
                   4329:                                             $digit += $numletts;
                   4330:                                         }
                   4331:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4332:                                         $digit = $values[$i]-1;
                   4333:                                         if ($values[$i] eq '0') {
                   4334:                                             $digit += $numletts;
                   4335:                                         }
                   4336:                                     }
                   4337:                                     my $qval='';
                   4338:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4339:                                         if ($j == $digit) {
                   4340:                                             $qval .= $scantronconf{'Qon'};
                   4341:                                         } else {
                   4342:                                             $qval .= $scantronconf{'Qoff'};
                   4343:                                         }
                   4344:                                     }
                   4345:                                     $values[$i] = $qval;
                   4346:                                 }
                   4347:                             }
                   4348:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4349:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4350:                             }
                   4351:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4352:                             if ($numblank > 0) {
                   4353:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4354:                             }
                   4355:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4356:                                 $qstart = $i;
                   4357:                                 $found{$csvbynum{$i}} = $values[$i];
                   4358:                             } else {
                   4359:                                 $found{'FirstQuestion'} .= $values[$i];
                   4360:                             }
                   4361:                         } elsif (exists($csvbynum{$i})) {
                   4362:                             if ($csvoptions{'rem'}) {
                   4363:                                 $values[$i] =~ s/^\s+//;
                   4364:                             }
                   4365:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4366:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4367:                                     $values[$i] = '0'.$values[$i];
                   4368:                                 }
                   4369:                             }
                   4370:                             $found{$csvbynum{$i}} = $values[$i];
                   4371:                         }
                   4372:                     }
                   4373:                     foreach my $item (@ordered) {
                   4374:                         my $currlength = 1+length($record);
                   4375:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4376:                         if ($numspaces > 0) {
                   4377:                             $record .= (' ' x $numspaces);
                   4378:                         }
                   4379:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4380:                             unless ($item eq 'Qstart') {
                   4381:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4382:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4383:                                 }
                   4384:                             }
                   4385:                             $record .= $found{$mapstart{$item}};
                   4386:                         }
                   4387:                     }
                   4388:                     $output .= "$record\n";
                   4389:                 }
                   4390:                 close($fh);
                   4391:                 if ($output) {
                   4392:                     if (open(my $fh,'>',$fullpath)) {
                   4393:                         print $fh $output;
                   4394:                         close($fh);
                   4395:                     }
                   4396:                 }
                   4397:             }
                   4398:         }
                   4399:         return;
                   4400:     }
                   4401: }
                   4402: 
                   4403: sub letter_to_digits {
                   4404:     my %lettdig = (
                   4405:                     A => 1,
                   4406:                     B => 2,
                   4407:                     C => 3,
                   4408:                     D => 4,
                   4409:                     E => 5,
                   4410:                     F => 6,
                   4411:                     G => 7,
                   4412:                     H => 8,
                   4413:                     I => 9,
                   4414:                     J => 0,
                   4415:                   );
                   4416:     return %lettdig;
                   4417: }
                   4418: 
                   4419: sub get_scantron_config {
                   4420:     my ($which,$cdom) = @_;
                   4421:     my @lines = &get_scantronformat_file($cdom);
                   4422:     my %config;
                   4423:     #FIXME probably should move to XML it has already gotten a bit much now
                   4424:     foreach my $line (@lines) {
                   4425:         my ($name,$descrip)=split(/:/,$line);
                   4426:         if ($name ne $which ) { next; }
                   4427:         chomp($line);
                   4428:         my @config=split(/:/,$line);
                   4429:         $config{'name'}=$config[0];
                   4430:         $config{'description'}=$config[1];
                   4431:         $config{'CODElocation'}=$config[2];
                   4432:         $config{'CODEstart'}=$config[3];
                   4433:         $config{'CODElength'}=$config[4];
                   4434:         $config{'IDstart'}=$config[5];
                   4435:         $config{'IDlength'}=$config[6];
                   4436:         $config{'Qstart'}=$config[7];
                   4437:         $config{'Qlength'}=$config[8];
                   4438:         $config{'Qoff'}=$config[9];
                   4439:         $config{'Qon'}=$config[10];
                   4440:         $config{'PaperID'}=$config[11];
                   4441:         $config{'PaperIDlength'}=$config[12];
                   4442:         $config{'FirstName'}=$config[13];
                   4443:         $config{'FirstNamelength'}=$config[14];
                   4444:         $config{'LastName'}=$config[15];
                   4445:         $config{'LastNamelength'}=$config[16];
                   4446:         $config{'BubblesPerRow'}=$config[17];
                   4447:         last;
                   4448:     }
                   4449:     return %config;
                   4450: }
                   4451: 
                   4452: sub get_scantronformat_file {
                   4453:     my ($cdom) = @_;
                   4454:     if ($cdom eq '') {
                   4455:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4456:     }
                   4457:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4458:     my $gottab = 0;
                   4459:     my @lines;
                   4460:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4461:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4462:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4463:             if ($formatfile ne '-1') {
                   4464:                 @lines = split("\n",$formatfile,-1);
                   4465:                 $gottab = 1;
                   4466:             }
                   4467:         }
                   4468:     }
                   4469:     if (!$gottab) {
                   4470:         my $confname = $cdom.'-domainconfig';
                   4471:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4472:         my $formatfile = &getfile($default);
                   4473:         if ($formatfile ne '-1') {
                   4474:             @lines = split("\n",$formatfile,-1);
                   4475:             $gottab = 1;
                   4476:         }
                   4477:     }
                   4478:     if (!$gottab) {
                   4479:         my @domains = &current_machine_domains();
                   4480:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4481:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4482:                 @lines = <$fh>;
                   4483:                 close($fh);
                   4484:             }
                   4485:         } else {
                   4486:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4487:                 @lines = <$fh>;
                   4488:                 close($fh);
                   4489:             }
                   4490:         }
                   4491:     }
                   4492:     return @lines;
                   4493: }
                   4494: 
1.493     albertel 4495: sub removeuploadedurl {
1.984     neumanie 4496:     my ($url)=@_;	
                   4497:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4498:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4499: }
                   4500: 
                   4501: sub removeuserfile {
                   4502:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4503:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4504:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4505:     if ($result eq 'ok') {	
1.798     raeburn  4506:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4507:             my $metafile = $fname.'.meta';
                   4508:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4509: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4510:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4511:             my $sqlresult = 
1.823     albertel 4512:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4513:                                         'portfolio_metadata',$group,
                   4514:                                         'delete');
1.798     raeburn  4515:         }
                   4516:     }
                   4517:     return $result;
1.257     www      4518: }
1.15      www      4519: 
1.530     albertel 4520: sub mkdiruserfile {
                   4521:     my ($docuname,$docudom,$dir)=@_;
                   4522:     my $home=&homeserver($docuname,$docudom);
                   4523:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4524: }
                   4525: 
1.531     albertel 4526: sub renameuserfile {
                   4527:     my ($docuname,$docudom,$old,$new)=@_;
                   4528:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4529:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4530:                         &escape("$old").':'.&escape("$new"),$home);
                   4531:     if ($result eq 'ok') {
                   4532:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4533:             my $oldmeta = $old.'.meta';
                   4534:             my $newmeta = $new.'.meta';
                   4535:             my $metaresult = 
                   4536:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4537: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4538:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4539:             my $sqlresult = 
1.823     albertel 4540:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4541:                                         'portfolio_metadata',$group,
                   4542:                                         'delete');
1.798     raeburn  4543:         }
                   4544:     }
                   4545:     return $result;
1.531     albertel 4546: }
                   4547: 
1.14      www      4548: # ------------------------------------------------------------------------- Log
                   4549: 
                   4550: sub log {
                   4551:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4552:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4553: }
                   4554: 
                   4555: # ------------------------------------------------------------------ Course Log
1.352     www      4556: #
                   4557: # This routine flushes several buffers of non-mission-critical nature
                   4558: #
1.157     www      4559: 
                   4560: sub flushcourselogs {
1.352     www      4561:     &logthis('Flushing log buffers');
                   4562: #
                   4563: # course logs
                   4564: # This is a log of all transactions in a course, which can be used
                   4565: # for data mining purposes
                   4566: #
                   4567: # It also collects the courseid database, which lists last transaction
                   4568: # times and course titles for all courseids
                   4569: #
                   4570:     my %courseidbuffer=();
1.921     raeburn  4571:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4572:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4573: 		          &escape($courselogs{$crsid}),
                   4574: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4575: 	    delete $courselogs{$crsid};
                   4576:         } else {
                   4577:             &logthis('Failed to flush log buffer for '.$crsid);
                   4578:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4579:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4580:                         " exceeded maximum size, deleting.</font>");
                   4581:                delete $courselogs{$crsid};
                   4582:             }
1.352     www      4583:         }
1.920     raeburn  4584:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4585:             'description' => $coursedescrbuf{$crsid},
                   4586:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4587:             'type'        => $coursetypebuf{$crsid},
                   4588:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4589:         };
1.191     harris41 4590:     }
1.352     www      4591: #
                   4592: # Write course id database (reverse lookup) to homeserver of courses 
                   4593: # Is used in pickcourse
                   4594: #
1.840     albertel 4595:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4596:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4597:                                     $courseidbuffer{$crs_home},
                   4598:                                     $crs_home,'timeonly');
1.352     www      4599:     }
                   4600: #
                   4601: # File accesses
                   4602: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4603: #
1.449     matthew  4604:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4605:         if ($entry =~ /___count$/) {
                   4606:             my ($dom,$name);
1.807     albertel 4607:             ($dom,$name,undef)=
1.811     albertel 4608: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4609:             if (! defined($dom) || $dom eq '' || 
                   4610:                 ! defined($name) || $name eq '') {
1.620     albertel 4611:                 my $cid = $env{'request.course.id'};
                   4612:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4613:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4614:             }
1.450     matthew  4615:             my $value = $accesshash{$entry};
                   4616:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4617:             my %temphash=($url => $value);
1.449     matthew  4618:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4619:             if ($result eq 'ok') {
                   4620:                 delete $accesshash{$entry};
                   4621:             }
                   4622:         } else {
1.811     albertel 4623:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4624:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4625:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4626:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4627:                 delete $accesshash{$entry};
                   4628:             }
1.185     www      4629:         }
1.191     harris41 4630:     }
1.352     www      4631: #
                   4632: # Roles
                   4633: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4634: #
1.800     albertel 4635:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4636:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4637: 	    split(/\:/,$entry);
                   4638:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4639:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4640:                 $rudom,$runame) eq 'ok') {
                   4641: 	    delete $userrolehash{$entry};
                   4642:         }
                   4643:     }
1.662     raeburn  4644: #
1.1172.2.90  raeburn  4645: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4646: #
                   4647:     my %domrolebuffer = ();
1.1000    raeburn  4648:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4649:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4650:         if ($domrolebuffer{$rudom}) {
                   4651:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4652:                       '='.&escape($domainrolehash{$entry});
                   4653:         } else {
                   4654:             $domrolebuffer{$rudom}.=&escape($entry).
                   4655:                       '='.&escape($domainrolehash{$entry});
                   4656:         }
                   4657:         delete $domainrolehash{$entry};
                   4658:     }
                   4659:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4660:         my %servers;
                   4661:         if (defined(&domain($dom,'primary'))) {
                   4662:             my $primary=&domain($dom,'primary');
                   4663:             my $hostname=&hostname($primary);
                   4664:             $servers{$primary} = $hostname;
                   4665:         } else {
                   4666:             %servers = &get_servers($dom,'library');
                   4667:         }
1.841     albertel 4668: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4669: 	    if (&reply('domroleput:'.$dom.':'.
                   4670: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4671: 	        last;
                   4672: 	    } else {
1.841     albertel 4673: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4674: 	    }
1.662     raeburn  4675:         }
                   4676:     }
1.186     www      4677:     $dumpcount++;
1.157     www      4678: }
                   4679: 
                   4680: sub courselog {
                   4681:     my $what=shift;
1.158     www      4682:     $what=time.':'.$what;
1.620     albertel 4683:     unless ($env{'request.course.id'}) { return ''; }
                   4684:     $coursedombuf{$env{'request.course.id'}}=
                   4685:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4686:     $coursenumbuf{$env{'request.course.id'}}=
                   4687:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4688:     $coursehombuf{$env{'request.course.id'}}=
                   4689:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4690:     $coursedescrbuf{$env{'request.course.id'}}=
                   4691:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4692:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4693:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4694:     $courseownerbuf{$env{'request.course.id'}}=
                   4695:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4696:     $coursetypebuf{$env{'request.course.id'}}=
                   4697:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4698:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4699: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4700:     } else {
1.620     albertel 4701: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4702:     }
1.620     albertel 4703:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4704: 	&flushcourselogs();
                   4705:     }
1.158     www      4706: }
                   4707: 
                   4708: sub courseacclog {
                   4709:     my $fnsymb=shift;
1.620     albertel 4710:     unless ($env{'request.course.id'}) { return ''; }
                   4711:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4712:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4713:         $what.=':POST';
1.583     matthew  4714:         # FIXME: Probably ought to escape things....
1.800     albertel 4715: 	foreach my $key (keys(%env)) {
                   4716:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4717:                 my $formitem = $1;
                   4718:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4719:                     $what.=':'.$formitem.'='.$env{$key};
                   4720:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4721:                     $what.=':'.$formitem.'='.$env{$key};
                   4722:                 }
1.158     www      4723:             }
1.191     harris41 4724:         }
1.583     matthew  4725:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4726:         # FIXME: We should not be depending on a form parameter that someone
                   4727:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4728:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4729:             $what.= ':POST';
                   4730:             # FIXME: Probably ought to escape things....
                   4731:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4732:                                  'crsdiscuss') {
1.620     albertel 4733:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4734:             }
                   4735:         }
1.158     www      4736:     }
                   4737:     &courselog($what);
1.149     www      4738: }
                   4739: 
1.185     www      4740: sub countacc {
                   4741:     my $url=&declutter(shift);
1.458     matthew  4742:     return if (! defined($url) || $url eq '');
1.620     albertel 4743:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4744: #
                   4745: # Mark that this url was used in this course
                   4746: #
1.620     albertel 4747:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4748: #
                   4749: # Increase the access count for this resource in this child process
                   4750: #
1.281     www      4751:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4752:     $accesshash{$key}++;
1.185     www      4753: }
1.349     www      4754: 
1.361     www      4755: sub linklog {
                   4756:     my ($from,$to)=@_;
                   4757:     $from=&declutter($from);
                   4758:     $to=&declutter($to);
                   4759:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4760:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4761: }
1.1160    www      4762: 
                   4763: sub statslog {
                   4764:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4765:     if ($users<2) { return; }
                   4766:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4767:             'course'       => $env{'request.course.id'},
                   4768:             'sections'     => '"all"',
                   4769:             'num_students' => $users,
                   4770:             'part'         => $part,
                   4771:             'symb'         => $symb,
                   4772:             'mean_tries'   => $av_attempts,
                   4773:             'deg_of_diff'  => $degdiff});
                   4774:     foreach my $key (keys(%dynstore)) {
                   4775:         $accesshash{$key}=$dynstore{$key};
                   4776:     }
                   4777: }
1.361     www      4778:   
1.349     www      4779: sub userrolelog {
                   4780:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4781:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4782:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4783:        $userrolehash
                   4784:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4785:                     =$tend.':'.$tstart;
1.662     raeburn  4786:     }
1.1169    droeschl 4787:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4788:        $userrolehash
                   4789:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4790:                     =$tend.':'.$tstart;
                   4791:     }
1.1172.2.90  raeburn  4792:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4793:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4794:        $domainrolehash
                   4795:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4796:                     = $tend.':'.$tstart;
                   4797:     }
1.351     www      4798: }
                   4799: 
1.957     raeburn  4800: sub courserolelog {
                   4801:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4802:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4803:         my $cdom = $1;
                   4804:         my $cnum = $2;
                   4805:         my $sec = $3;
                   4806:         my $namespace = 'rolelog';
                   4807:         my %storehash = (
                   4808:                            role    => $trole,
                   4809:                            start   => $tstart,
                   4810:                            end     => $tend,
                   4811:                            selfenroll => $selfenroll,
                   4812:                            context    => $context,
                   4813:                         );
                   4814:         if ($trole eq 'gr') {
                   4815:             $namespace = 'groupslog';
                   4816:             $storehash{'group'} = $sec;
                   4817:         } else {
                   4818:             $storehash{'section'} = $sec;
                   4819:         }
                   4820:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4821:                    $domain,$cnum,$cdom);
                   4822:         if (($trole ne 'st') || ($sec ne '')) {
                   4823:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4824:         }
                   4825:     }
                   4826:     return;
                   4827: }
                   4828: 
1.1172.2.9  raeburn  4829: sub domainrolelog {
                   4830:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4831:     if ($area =~ m{^/($match_domain)/$}) {
                   4832:         my $cdom = $1;
                   4833:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4834:         my $namespace = 'rolelog';
                   4835:         my %storehash = (
                   4836:                            role    => $trole,
                   4837:                            start   => $tstart,
                   4838:                            end     => $tend,
                   4839:                            context => $context,
                   4840:                         );
                   4841:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4842:                    $domain,$domconfiguser,$cdom);
                   4843:     }
                   4844:     return;
                   4845: 
                   4846: }
                   4847: 
                   4848: sub coauthorrolelog {
                   4849:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4850:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4851:         my $audom = $1;
                   4852:         my $auname = $2;
                   4853:         my $namespace = 'rolelog';
                   4854:         my %storehash = (
                   4855:                            role    => $trole,
                   4856:                            start   => $tstart,
                   4857:                            end     => $tend,
                   4858:                            context => $context,
                   4859:                         );
                   4860:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4861:                    $domain,$auname,$audom);
                   4862:     }
                   4863:     return;
                   4864: }
                   4865: 
1.351     www      4866: sub get_course_adv_roles {
1.948     raeburn  4867:     my ($cid,$codes) = @_;
1.620     albertel 4868:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4869:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4870:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4871:     my %nothide=();
1.800     albertel 4872:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4873:         if ($user !~ /:/) {
                   4874: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4875:         } else {
                   4876:             $nothide{$user}=1;
                   4877:         }
1.470     www      4878:     }
1.1172.2.23  raeburn  4879:     my @possdoms = ($coursehash{'domain'});
                   4880:     if ($coursehash{'checkforpriv'}) {
                   4881:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4882:     }
1.351     www      4883:     my %returnhash=();
                   4884:     my %dumphash=
                   4885:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4886:     my $now=time;
1.997     raeburn  4887:     my %privileged;
1.1000    raeburn  4888:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4889: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4890:         if (($tstart) && ($tstart<0)) { next; }
                   4891:         if (($tend) && ($tend<$now)) { next; }
                   4892:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4893:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4894: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4895:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4896:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4897: 	if ($role eq 'cr') { next; }
1.948     raeburn  4898:         if ($codes) {
                   4899:             if ($section) { $role .= ':'.$section; }
                   4900:             if ($returnhash{$role}) {
                   4901:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4902:             } else {
                   4903:                 $returnhash{$role}=$username.':'.$domain;
                   4904:             }
1.351     www      4905:         } else {
1.988     raeburn  4906:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4907:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4908:             if ($returnhash{$key}) {
                   4909: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4910:             } else {
                   4911:                 $returnhash{$key}=$username.':'.$domain;
                   4912:             }
1.351     www      4913:         }
1.948     raeburn  4914:     }
1.400     www      4915:     return %returnhash;
                   4916: }
                   4917: 
                   4918: sub get_my_roles {
1.937     raeburn  4919:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4920:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4921:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4922:     my (%dumphash,%nothide);
1.1086    raeburn  4923:     if ($context eq 'userroles') {
1.1166    raeburn  4924:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4925:     } else {
1.1172.2.23  raeburn  4926:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4927:         if ($hidepriv) {
                   4928:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4929:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4930:                 if ($user !~ /:/) {
                   4931:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4932:                 } else {
                   4933:                     $nothide{$user} = 1;
                   4934:                 }
                   4935:             }
                   4936:         }
1.858     raeburn  4937:     }
1.400     www      4938:     my %returnhash=();
                   4939:     my $now=time;
1.999     raeburn  4940:     my %privileged;
1.800     albertel 4941:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4942:         my ($role,$tend,$tstart);
                   4943:         if ($context eq 'userroles') {
1.1149    raeburn  4944:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4945: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4946:         } else {
                   4947:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4948:         }
1.400     www      4949:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4950:         my $status = 'active';
1.939     raeburn  4951:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4952:             $status = 'previous';
                   4953:         } 
                   4954:         if (($tstart) && ($now<$tstart)) {
                   4955:             $status = 'future';
                   4956:         }
                   4957:         if (ref($types) eq 'ARRAY') {
                   4958:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4959:                 next;
                   4960:             } 
                   4961:         } else {
                   4962:             if ($status ne 'active') {
                   4963:                 next;
                   4964:             }
                   4965:         }
1.867     raeburn  4966:         my ($rolecode,$username,$domain,$section,$area);
                   4967:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4968:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4969:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4970:         } else {
                   4971:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4972:         }
1.832     raeburn  4973:         if (ref($roledoms) eq 'ARRAY') {
                   4974:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4975:                 next;
                   4976:             }
                   4977:         }
                   4978:         if (ref($roles) eq 'ARRAY') {
                   4979:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4980:                 if ($role =~ /^cr\//) {
                   4981:                     if (!grep(/^cr$/,@{$roles})) {
                   4982:                         next;
                   4983:                     }
1.1104    raeburn  4984:                 } elsif ($role =~ /^gr\//) {
                   4985:                     if (!grep(/^gr$/,@{$roles})) {
                   4986:                         next;
                   4987:                     }
1.922     raeburn  4988:                 } else {
                   4989:                     next;
                   4990:                 }
1.832     raeburn  4991:             }
1.867     raeburn  4992:         }
1.937     raeburn  4993:         if ($hidepriv) {
1.1172.2.23  raeburn  4994:             my @privroles = ('dc','su');
1.999     raeburn  4995:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  4996:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4997:             } else {
1.1172.2.23  raeburn  4998:                 my $possdoms = [$domain];
                   4999:                 if (ref($roledoms) eq 'ARRAY') {
                   5000:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  5001:                 }
1.1172.2.23  raeburn  5002:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5003:                     if (!$nothide{$username.':'.$domain}) {
                   5004:                         next;
                   5005:                     }
                   5006:                 }
1.937     raeburn  5007:             }
                   5008:         }
1.933     raeburn  5009:         if ($withsec) {
                   5010:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5011:                 $tstart.':'.$tend;
                   5012:         } else {
                   5013:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5014:         }
1.832     raeburn  5015:     }
1.373     www      5016:     return %returnhash;
1.399     www      5017: }
                   5018: 
1.1172.2.89  raeburn  5019: sub get_all_adhocroles {
                   5020:     my ($dom) = @_;
                   5021:     my @roles_by_num = ();
                   5022:     my %domdefaults = &get_domain_defaults($dom);
                   5023:     my (%description,%access_in_dom,%access_info);
                   5024:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5025:         my $count = 0;
                   5026:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5027:         my %ordered;
                   5028:         foreach my $role (sort(keys(%domcurrent))) {
                   5029:             my ($order,$desc,$access_in_dom);
                   5030:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5031:                 $order = $domcurrent{$role}{'order'};
                   5032:                 $desc = $domcurrent{$role}{'desc'};
                   5033:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5034:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5035:             }
                   5036:             if ($order eq '') {
                   5037:                 $order = $count;
                   5038:             }
                   5039:             $ordered{$order} = $role;
                   5040:             if ($desc ne '') {
                   5041:                 $description{$role} = $desc;
                   5042:             } else {
                   5043:                 $description{$role}= $role;
                   5044:             }
                   5045:             $count++;
                   5046:         }
                   5047:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5048:             push(@roles_by_num,$ordered{$item});
                   5049:         }
                   5050:     }
                   5051:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5052: }
                   5053: 
                   5054: sub get_my_adhocroles {
                   5055:     my ($cid,$checkreg) = @_;
                   5056:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5057:     if ($env{'request.course.id'} eq $cid) {
                   5058:         $cdom = $env{'course.'.$cid.'.domain'};
                   5059:         $cnum = $env{'course.'.$cid.'.num'};
                   5060:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5061:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5062:         $cdom = $1;
                   5063:         $cnum = $2;
                   5064:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5065:                                      $cdom,$cnum);
                   5066:     }
                   5067:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5068:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5069:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5070:         if ($rosterhash{$user} ne '') {
                   5071:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5072:             return ([],{}) if ($type eq 'auto');
                   5073:         }
                   5074:     }
                   5075:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5076:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5077:             my $then=$env{'user.login.time'};
                   5078:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5079:             if (!$update) {
                   5080:                 $update = $then;
                   5081:             }
                   5082:             my @liveroles;
                   5083:             foreach my $role ('dh','da') {
                   5084:                 if ($env{"user.role.$role./$cdom/"}) {
                   5085:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5086:                     my $limit = $update;
                   5087:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5088:                         $limit = $then;
                   5089:                     }
                   5090:                     my $activerole = 1;
                   5091:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5092:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5093:                     if ($activerole) {
                   5094:                         push(@liveroles,$role);
                   5095:                     }
                   5096:                 }
                   5097:             }
                   5098:             if (@liveroles) {
1.1172.2.89  raeburn  5099:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5100:                     my ($accessref,$accessinfo,%access_in_dom);
                   5101:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5102:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5103:                         if (@{$roles_by_num}) {
                   5104:                             my %settings;
                   5105:                             if ($env{'request.course.id'} eq $cid) {
                   5106:                                 foreach my $envkey (keys(%env)) {
                   5107:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5108:                                         $settings{$1} = $env{$envkey};
                   5109:                                     }
                   5110:                                 }
                   5111:                             } else {
                   5112:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5113:                             }
                   5114:                             my %setincrs;
                   5115:                             if ($settings{'internal.adhocaccess'}) {
                   5116:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5117:                             }
                   5118:                             my @statuses;
                   5119:                             if ($env{'environment.inststatus'}) {
                   5120:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5121:                             }
                   5122:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5123:                             if (ref($accessref) eq 'HASH') {
                   5124:                                 %access_in_dom = %{$accessref};
                   5125:                             }
                   5126:                             foreach my $role (@{$roles_by_num}) {
                   5127:                                 my ($curraccess,@okstatus,@personnel);
                   5128:                                 if ($setincrs{$role}) {
                   5129:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5130:                                     if ($curraccess eq 'status') {
                   5131:                                         @okstatus = split(/\&/,$rest);
                   5132:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5133:                                         @personnel = split(/\&/,$rest);
                   5134:                                     }
                   5135:                                 } else {
                   5136:                                     $curraccess = $access_in_dom{$role};
                   5137:                                     if (ref($accessinfo) eq 'HASH') {
                   5138:                                         if ($curraccess eq 'status') {
                   5139:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5140:                                                 @okstatus = @{$accessinfo->{$role}};
                   5141:                                             }
                   5142:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5143:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5144:                                                 @personnel = @{$accessinfo->{$role}};
                   5145:                                             }
                   5146:                                         }
                   5147:                                     }
                   5148:                                 }
                   5149:                                 if ($curraccess eq 'none') {
                   5150:                                     next;
                   5151:                                 } elsif ($curraccess eq 'all') {
                   5152:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5153:                                 } elsif ($curraccess eq 'dh') {
                   5154:                                     if (grep(/^dh$/,@liveroles)) {
                   5155:                                         push(@possroles,$role);
                   5156:                                     } else {
                   5157:                                         next;
                   5158:                                     }
                   5159:                                 } elsif ($curraccess eq 'da') {
                   5160:                                     if (grep(/^da$/,@liveroles)) {
                   5161:                                         push(@possroles,$role);
                   5162:                                     } else {
                   5163:                                         next;
                   5164:                                     }
1.1172.2.89  raeburn  5165:                                 } elsif ($curraccess eq 'status') {
                   5166:                                     if (@okstatus) {
                   5167:                                         if (!@statuses) {
                   5168:                                             if (grep(/^default$/,@okstatus)) {
                   5169:                                                 push(@possroles,$role);
                   5170:                                             }
                   5171:                                         } else {
                   5172:                                             foreach my $status (@okstatus) {
                   5173:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5174:                                                     push(@possroles,$role);
                   5175:                                                     last;
                   5176:                                                 }
                   5177:                                             }
                   5178:                                         }
                   5179:                                     }
                   5180:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5181:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5182:                                         if ($curraccess eq 'exc') {
                   5183:                                             push(@possroles,$role);
                   5184:                                         }
                   5185:                                     } elsif ($curraccess eq 'inc') {
                   5186:                                         push(@possroles,$role);
                   5187:                                     }
                   5188:                                 }
                   5189:                             }
                   5190:                         }
                   5191:                     }
                   5192:                 }
                   5193:             }
                   5194:         }
                   5195:     }
                   5196:     unless (ref($description) eq 'HASH') {
                   5197:         if (ref($roles_by_num) eq 'ARRAY') {
                   5198:             my %desc;
                   5199:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5200:             $description = \%desc;
                   5201:         } else {
                   5202:             $description = {};
                   5203:         }
                   5204:     }
                   5205:     return (\@possroles,$description);
                   5206: }
                   5207: 
1.399     www      5208: # ----------------------------------------------------- Frontpage Announcements
                   5209: #
                   5210: #
                   5211: 
                   5212: sub postannounce {
                   5213:     my ($server,$text)=@_;
1.844     albertel 5214:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5215:     unless ($text=~/\w/) { $text=''; }
                   5216:     return &reply('setannounce:'.&escape($text),$server);
                   5217: }
                   5218: 
                   5219: sub getannounce {
1.448     albertel 5220: 
1.1172.2.96  raeburn  5221:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5222: 	my $announcement='';
1.800     albertel 5223: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5224: 	close($fh);
1.399     www      5225: 	if ($announcement=~/\w/) { 
                   5226: 	    return 
                   5227:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5228:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5229: 	} else {
                   5230: 	    return '';
                   5231: 	}
                   5232:     } else {
                   5233: 	return '';
                   5234:     }
1.351     www      5235: }
1.353     www      5236: 
                   5237: # ---------------------------------------------------------- Course ID routines
                   5238: # Deal with domain's nohist_courseid.db files
                   5239: #
                   5240: 
                   5241: sub courseidput {
1.921     raeburn  5242:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5243:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5244:     my $outcome;
                   5245:     if ($caller eq 'timeonly') {
                   5246:         my $cids = '';
                   5247:         foreach my $item (keys(%$storehash)) {
                   5248:             $cids.=&escape($item).'&';
                   5249:         }
                   5250:         $cids=~s/\&$//;
                   5251:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5252:                           $coursehome);       
                   5253:     } else {
                   5254:         my $items = '';
                   5255:         foreach my $item (keys(%$storehash)) {
                   5256:             $items.= &escape($item).'='.
                   5257:                      &freeze_escape($$storehash{$item}).'&';
                   5258:         }
                   5259:         $items=~s/\&$//;
                   5260:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5261:                           $coursehome);
1.918     raeburn  5262:     }
                   5263:     if ($outcome eq 'unknown_cmd') {
                   5264:         my $what;
                   5265:         foreach my $cid (keys(%$storehash)) {
                   5266:             $what .= &escape($cid).'=';
1.921     raeburn  5267:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5268:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5269:             }
                   5270:             $what =~ s/\:$/&/;
                   5271:         }
                   5272:         $what =~ s/\&$//;  
                   5273:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5274:     } else {
                   5275:         return $outcome;
                   5276:     }
1.353     www      5277: }
                   5278: 
                   5279: sub courseiddump {
1.921     raeburn  5280:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5281:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5282:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5283:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5284:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5285:     my $as_hash = 1;
                   5286:     my %returnhash;
                   5287:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5288:     my %libserv = &all_library();
                   5289:     foreach my $tryserver (keys(%libserv)) {
                   5290:         if ( (  $hostidflag == 1 
                   5291: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5292: 	     || (!defined($hostidflag)) ) {
                   5293: 
1.918     raeburn  5294: 	    if (($domfilter eq '') ||
                   5295: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5296:                 my $rep;
                   5297:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5298:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5299:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5300:                                 &escape($descfilter), &escape($instcodefilter),
                   5301:                                 &escape($ownerfilter), &escape($coursefilter),
                   5302:                                 &escape($typefilter), &escape($regexp_ok),
                   5303:                                 $as_hash, &escape($selfenrollonly),
                   5304:                                 &escape($catfilter), $showhidden, $caller,
                   5305:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5306:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5307:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5308:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5309:                 } else {
                   5310:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5311:                              $sincefilter.':'.&escape($descfilter).':'.
                   5312:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5313:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5314:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5315:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5316:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5317:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5318:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5319:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5320:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5321:                 }
                   5322: 
1.918     raeburn  5323:                 my @pairs=split(/\&/,$rep);
                   5324:                 foreach my $item (@pairs) {
                   5325:                     my ($key,$value)=split(/\=/,$item,2);
                   5326:                     $key = &unescape($key);
                   5327:                     next if ($key =~ /^error: 2 /);
                   5328:                     my $result = &thaw_unescape($value);
                   5329:                     if (ref($result) eq 'HASH') {
                   5330:                         $returnhash{$key}=$result;
                   5331:                     } else {
1.921     raeburn  5332:                         my @responses = split(/:/,$value);
                   5333:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5334:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5335:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5336:                         }
1.1008    raeburn  5337:                     }
1.353     www      5338:                 }
                   5339:             }
                   5340:         }
                   5341:     }
                   5342:     return %returnhash;
                   5343: }
                   5344: 
1.1055    raeburn  5345: sub courselastaccess {
                   5346:     my ($cdom,$cnum,$hostidref) = @_;
                   5347:     my %returnhash;
                   5348:     if ($cdom && $cnum) {
                   5349:         my $chome = &homeserver($cnum,$cdom);
                   5350:         if ($chome ne 'no_host') {
                   5351:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5352:             &extract_lastaccess(\%returnhash,$rep);
                   5353:         }
                   5354:     } else {
                   5355:         if (!$cdom) { $cdom=''; }
                   5356:         my %libserv = &all_library();
                   5357:         foreach my $tryserver (keys(%libserv)) {
                   5358:             if (ref($hostidref) eq 'ARRAY') {
                   5359:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5360:             } 
                   5361:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5362:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5363:                 &extract_lastaccess(\%returnhash,$rep);
                   5364:             }
                   5365:         }
                   5366:     }
                   5367:     return %returnhash;
                   5368: }
                   5369: 
                   5370: sub extract_lastaccess {
                   5371:     my ($returnhash,$rep) = @_;
                   5372:     if (ref($returnhash) eq 'HASH') {
                   5373:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5374:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5375:                  $rep eq '') {
                   5376:             my @pairs=split(/\&/,$rep);
                   5377:             foreach my $item (@pairs) {
                   5378:                 my ($key,$value)=split(/\=/,$item,2);
                   5379:                 $key = &unescape($key);
                   5380:                 next if ($key =~ /^error: 2 /);
                   5381:                 $returnhash->{$key} = &thaw_unescape($value);
                   5382:             }
                   5383:         }
                   5384:     }
                   5385:     return;
                   5386: }
                   5387: 
1.658     raeburn  5388: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5389: 
                   5390: sub dcmailput {
1.685     raeburn  5391:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5392:     my $status = &Apache::lonnet::critical(
1.740     www      5393:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5394:        &escape($message),$server);
1.662     raeburn  5395:     return $status;
                   5396: }
                   5397: 
1.658     raeburn  5398: sub dcmaildump {
                   5399:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5400:     my %returnhash=();
1.846     albertel 5401: 
                   5402:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5403:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5404:                                                          &escape($enddate).':';
                   5405: 	my @esc_senders=map { &escape($_)} @$senders;
                   5406: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5407: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5408:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5409:             if (($key) && ($value)) {
                   5410:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5411:             }
                   5412:         }
                   5413:     }
                   5414:     return %returnhash;
                   5415: }
1.662     raeburn  5416: # ---------------------------------------------------------- Domain roles
                   5417: 
                   5418: sub get_domain_roles {
                   5419:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5420:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5421:         $startdate = '.';
                   5422:     }
1.1018    raeburn  5423:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5424:         $enddate = '.';
                   5425:     }
1.922     raeburn  5426:     my $rolelist;
                   5427:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5428:         $rolelist = join('&',@{$roles});
1.922     raeburn  5429:     }
1.662     raeburn  5430:     my %personnel = ();
1.841     albertel 5431: 
                   5432:     my %servers = &get_servers($dom,'library');
                   5433:     foreach my $tryserver (keys(%servers)) {
                   5434: 	%{$personnel{$tryserver}}=();
                   5435: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5436: 					    &escape($startdate).':'.
                   5437: 					    &escape($enddate).':'.
                   5438: 					    &escape($rolelist), $tryserver))) {
                   5439: 	    my ($key,$value) = split(/\=/,$line,2);
                   5440: 	    if (($key) && ($value)) {
                   5441: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5442: 	    }
                   5443: 	}
1.662     raeburn  5444:     }
                   5445:     return %personnel;
                   5446: }
1.658     raeburn  5447: 
1.1172.2.89  raeburn  5448: sub get_active_domroles {
                   5449:     my ($dom,$roles) = @_;
                   5450:     return () unless (ref($roles) eq 'ARRAY');
                   5451:     my $now = time;
                   5452:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5453:     my %domroles;
                   5454:     foreach my $server (keys(%dompersonnel)) {
                   5455:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5456:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5457:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5458:         }
                   5459:     }
                   5460:     return %domroles;
                   5461: }
                   5462: 
1.1057    www      5463: # ----------------------------------------------------------- Interval timing 
1.149     www      5464: 
1.1153    www      5465: {
                   5466: # Caches needed for speedup of navmaps
                   5467: # We don't want to cache this for very long at all (5 seconds at most)
                   5468: # 
                   5469: # The user for whom we cache
                   5470: my $cachedkey='';
                   5471: # The cached times for this user
                   5472: my %cachedtimes=();
                   5473: # When this was last done
1.1172.2.66  raeburn  5474: my $cachedtime='';
1.1153    www      5475: 
                   5476: sub load_all_first_access {
1.1172.2.118.  .1(raebu 5477:20):     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5478:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.118.  .1(raebu 5479:20):         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5480:20):         (!$ignorecache)) {
1.1154    raeburn  5481:         return;
                   5482:     }
                   5483:     $cachedtime=time;
                   5484:     $cachedkey=$uname.':'.$udom;
                   5485:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5486: }
                   5487: 
1.504     albertel 5488: sub get_first_access {
1.1172.2.118.  .1(raebu 5489:20):     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5490:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5491:     if ($argsymb) { $symb=$argsymb; }
                   5492:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5493:     if ($argmap) { $map = $argmap; }
1.926     albertel 5494:     if ($type eq 'course') {
                   5495: 	$res='course';
                   5496:     } elsif ($type eq 'map') {
1.588     albertel 5497: 	$res=&symbread($map);
                   5498:     } else {
                   5499: 	$res=$symb;
                   5500:     }
1.1172.2.118.  .1(raebu 5501:20):     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5502:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5503: }
                   5504: 
                   5505: sub set_first_access {
1.1162    raeburn  5506:     my ($type,$interval)=@_;
1.790     albertel 5507:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5508:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5509:     if ($type eq 'course') {
                   5510: 	$res='course';
                   5511:     } elsif ($type eq 'map') {
1.588     albertel 5512: 	$res=&symbread($map);
                   5513:     } else {
                   5514: 	$res=$symb;
                   5515:     }
1.1153    www      5516:     $cachedkey='';
1.1162    raeburn  5517:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5518:     if ($firstaccess) {
                   5519:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5520:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5521:                  "in $courseid");
                   5522:         return 'already_set';
                   5523:     } else {
1.1162    raeburn  5524:         my $start = time;
                   5525: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5526:                           $udom,$uname);
                   5527:         if ($putres eq 'ok') {
                   5528:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5529:                  $udom,$uname); 
                   5530:             &appenv(
                   5531:                      {
                   5532:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5533:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5534:                      }
                   5535:                   );
1.1172.2.97  raeburn  5536:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5537:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5538:             }
1.1172.2.102  raeburn  5539:         } elsif ($putres ne 'refused') {
                   5540:             &logthis("Result: $putres when attempting to set first access time ".
                   5541:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5542:         }
                   5543:         return $putres;
1.505     albertel 5544:     }
                   5545:     return 'already_set';
1.504     albertel 5546: }
1.1153    www      5547: }
1.1172.2.32  raeburn  5548: 
                   5549: sub checkout {
                   5550:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5551:     my $now=time;
                   5552:     my $lonhost=$perlvar{'lonHostID'};
                   5553:     my $infostr=&escape(
                   5554:                  'CHECKOUTTOKEN&'.
                   5555:                  $tuname.'&'.
                   5556:                  $tudom.'&'.
                   5557:                  $tcrsid.'&'.
                   5558:                  $symb.'&'.
                   5559:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   5560:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5561:     if ($token=~/^error\:/) {
                   5562:         &logthis("<font color=\"blue\">WARNING: ".
                   5563:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5564:                  "</font>");
                   5565:         return '';
                   5566:     }
                   5567: 
                   5568:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5569:     $token=~tr/a-z/A-Z/;
                   5570: 
                   5571:     my %infohash=('resource.0.outtoken' => $token,
                   5572:                   'resource.0.checkouttime' => $now,
                   5573:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   5574: 
                   5575:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5576:        return '';
                   5577:     } else {
                   5578:         &logthis("<font color=\"blue\">WARNING: ".
                   5579:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5580:                  "</font>");
                   5581:     }
                   5582: 
                   5583:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5584:                          &escape('Checkout '.$infostr.' - '.
                   5585:                                                  $token)) ne 'ok') {
                   5586:         return '';
                   5587:     } else {
                   5588:         &logthis("<font color=\"blue\">WARNING: ".
                   5589:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5590:                  "</font>");
                   5591:     }
                   5592:     return $token;
                   5593: }
                   5594: 
                   5595: # ------------------------------------------------------------ Check in an item
                   5596: 
                   5597: sub checkin {
                   5598:     my $token=shift;
                   5599:     my $now=time;
                   5600:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5601:     $lonhost=~tr/A-Z/a-z/;
                   5602:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5603:     $dtoken=~s/\W/\_/g;
                   5604:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5605:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5606: 
                   5607:     unless (($tuname) && ($tudom)) {
                   5608:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5609:         return '';
                   5610:     }
                   5611: 
                   5612:     unless (&allowed('mgr',$tcrsid)) {
                   5613:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5614:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5615:         return '';
                   5616:     }
                   5617: 
                   5618:     my %infohash=('resource.0.intoken' => $token,
                   5619:                   'resource.0.checkintime' => $now,
                   5620:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   5621: 
                   5622:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5623:        return '';
                   5624:     }
                   5625: 
                   5626:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5627:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5628:         return '';
                   5629:     }
                   5630: 
                   5631:     return ($symb,$tuname,$tudom,$tcrsid);
                   5632: }
                   5633: 
1.110     www      5634: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5635: 
                   5636: sub expirespread {
                   5637:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5638:     my $cid=$env{'request.course.id'}; 
1.110     www      5639:     if ($cid) {
                   5640:        my $now=time;
                   5641:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5642:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5643:                             $env{'course.'.$cid.'.num'}.
1.110     www      5644: 	        	    ':nohist_expirationdates:'.
                   5645:                             &escape($key).'='.$now,
1.620     albertel 5646:                             $env{'course.'.$cid.'.home'})
1.110     www      5647:     }
                   5648:     return 'ok';
1.14      www      5649: }
                   5650: 
1.109     www      5651: # ----------------------------------------------------- Devalidate Spreadsheets
                   5652: 
                   5653: sub devalidate {
1.325     www      5654:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5655:     my $cid=$env{'request.course.id'}; 
1.109     www      5656:     if ($cid) {
1.391     matthew  5657:         # delete the stored spreadsheets for
                   5658:         # - the student level sheet of this user in course's homespace
                   5659:         # - the assessment level sheet for this resource 
                   5660:         #   for this user in user's homespace
1.553     albertel 5661: 	# - current conditional state info
1.325     www      5662: 	my $key=$uname.':'.$udom.':';
1.109     www      5663:         my $status=
1.299     matthew  5664: 	    &del('nohist_calculatedsheets',
1.391     matthew  5665: 		 [$key.'studentcalc:'],
1.620     albertel 5666: 		 $env{'course.'.$cid.'.domain'},
                   5667: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5668: 		.' '.
                   5669: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5670: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5671:         unless ($status eq 'ok ok') {
                   5672:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5673:                     $uname.' at '.$udom.' for '.
1.109     www      5674: 		    $symb.': '.$status);
1.133     albertel 5675:         }
1.553     albertel 5676: 	&delenv('user.state.'.$cid);
1.109     www      5677:     }
                   5678: }
                   5679: 
1.265     albertel 5680: sub get_scalar {
                   5681:     my ($string,$end) = @_;
                   5682:     my $value;
                   5683:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5684: 	$value = $1;
                   5685:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5686: 	$value = $1;
                   5687:     }
                   5688:     return &unescape($value);
                   5689: }
                   5690: 
                   5691: sub array2str {
                   5692:   my (@array) = @_;
                   5693:   my $result=&arrayref2str(\@array);
                   5694:   $result=~s/^__ARRAY_REF__//;
                   5695:   $result=~s/__END_ARRAY_REF__$//;
                   5696:   return $result;
                   5697: }
                   5698: 
1.204     albertel 5699: sub arrayref2str {
                   5700:   my ($arrayref) = @_;
1.265     albertel 5701:   my $result='__ARRAY_REF__';
1.204     albertel 5702:   foreach my $elem (@$arrayref) {
1.265     albertel 5703:     if(ref($elem) eq 'ARRAY') {
                   5704:       $result.=&arrayref2str($elem).'&';
                   5705:     } elsif(ref($elem) eq 'HASH') {
                   5706:       $result.=&hashref2str($elem).'&';
                   5707:     } elsif(ref($elem)) {
                   5708:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5709:     } else {
                   5710:       $result.=&escape($elem).'&';
                   5711:     }
                   5712:   }
                   5713:   $result=~s/\&$//;
1.265     albertel 5714:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5715:   return $result;
                   5716: }
                   5717: 
1.168     albertel 5718: sub hash2str {
1.204     albertel 5719:   my (%hash) = @_;
                   5720:   my $result=&hashref2str(\%hash);
1.265     albertel 5721:   $result=~s/^__HASH_REF__//;
                   5722:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5723:   return $result;
                   5724: }
                   5725: 
                   5726: sub hashref2str {
                   5727:   my ($hashref)=@_;
1.265     albertel 5728:   my $result='__HASH_REF__';
1.800     albertel 5729:   foreach my $key (sort(keys(%$hashref))) {
                   5730:     if (ref($key) eq 'ARRAY') {
                   5731:       $result.=&arrayref2str($key).'=';
                   5732:     } elsif (ref($key) eq 'HASH') {
                   5733:       $result.=&hashref2str($key).'=';
                   5734:     } elsif (ref($key)) {
1.265     albertel 5735:       $result.='=';
1.800     albertel 5736:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5737:     } else {
1.1132    raeburn  5738: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5739:     }
                   5740: 
1.800     albertel 5741:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5742:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5743:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5744:       $result.=&hashref2str($hashref->{$key}).'&';
                   5745:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5746:        $result.='&';
1.800     albertel 5747:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5748:     } else {
1.800     albertel 5749:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5750:     }
                   5751:   }
1.168     albertel 5752:   $result=~s/\&$//;
1.265     albertel 5753:   $result .= '__END_HASH_REF__';
1.168     albertel 5754:   return $result;
                   5755: }
                   5756: 
                   5757: sub str2hash {
1.265     albertel 5758:     my ($string)=@_;
                   5759:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5760:     return %$hash;
                   5761: }
                   5762: 
                   5763: sub str2hashref {
1.168     albertel 5764:   my ($string) = @_;
1.265     albertel 5765: 
                   5766:   my %hash;
                   5767: 
                   5768:   if($string !~ /^__HASH_REF__/) {
                   5769:       if (! ($string eq '' || !defined($string))) {
                   5770: 	  $hash{'error'}='Not hash reference';
                   5771:       }
                   5772:       return (\%hash, $string);
                   5773:   }
                   5774: 
                   5775:   $string =~ s/^__HASH_REF__//;
                   5776: 
                   5777:   while($string !~ /^__END_HASH_REF__/) {
                   5778:       #key
                   5779:       my $key='';
                   5780:       if($string =~ /^__HASH_REF__/) {
                   5781:           ($key, $string)=&str2hashref($string);
                   5782:           if(defined($key->{'error'})) {
                   5783:               $hash{'error'}='Bad data';
                   5784:               return (\%hash, $string);
                   5785:           }
                   5786:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5787:           ($key, $string)=&str2arrayref($string);
                   5788:           if($key->[0] eq 'Array reference error') {
                   5789:               $hash{'error'}='Bad data';
                   5790:               return (\%hash, $string);
                   5791:           }
                   5792:       } else {
                   5793:           $string =~ s/^(.*?)=//;
1.267     albertel 5794: 	  $key=&unescape($1);
1.265     albertel 5795:       }
                   5796:       $string =~ s/^=//;
                   5797: 
                   5798:       #value
                   5799:       my $value='';
                   5800:       if($string =~ /^__HASH_REF__/) {
                   5801:           ($value, $string)=&str2hashref($string);
                   5802:           if(defined($value->{'error'})) {
                   5803:               $hash{'error'}='Bad data';
                   5804:               return (\%hash, $string);
                   5805:           }
                   5806:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5807:           ($value, $string)=&str2arrayref($string);
                   5808:           if($value->[0] eq 'Array reference error') {
                   5809:               $hash{'error'}='Bad data';
                   5810:               return (\%hash, $string);
                   5811:           }
                   5812:       } else {
                   5813: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5814:       }
                   5815:       $string =~ s/^&//;
                   5816: 
                   5817:       $hash{$key}=$value;
1.204     albertel 5818:   }
1.265     albertel 5819: 
                   5820:   $string =~ s/^__END_HASH_REF__//;
                   5821: 
                   5822:   return (\%hash, $string);
1.204     albertel 5823: }
                   5824: 
                   5825: sub str2array {
1.265     albertel 5826:     my ($string)=@_;
                   5827:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5828:     return @$array;
                   5829: }
                   5830: 
                   5831: sub str2arrayref {
1.204     albertel 5832:   my ($string) = @_;
1.265     albertel 5833:   my @array;
                   5834: 
                   5835:   if($string !~ /^__ARRAY_REF__/) {
                   5836:       if (! ($string eq '' || !defined($string))) {
                   5837: 	  $array[0]='Array reference error';
                   5838:       }
                   5839:       return (\@array, $string);
                   5840:   }
                   5841: 
                   5842:   $string =~ s/^__ARRAY_REF__//;
                   5843: 
                   5844:   while($string !~ /^__END_ARRAY_REF__/) {
                   5845:       my $value='';
                   5846:       if($string =~ /^__HASH_REF__/) {
                   5847:           ($value, $string)=&str2hashref($string);
                   5848:           if(defined($value->{'error'})) {
                   5849:               $array[0] ='Array reference error';
                   5850:               return (\@array, $string);
                   5851:           }
                   5852:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5853:           ($value, $string)=&str2arrayref($string);
                   5854:           if($value->[0] eq 'Array reference error') {
                   5855:               $array[0] ='Array reference error';
                   5856:               return (\@array, $string);
                   5857:           }
                   5858:       } else {
                   5859: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5860:       }
                   5861:       $string =~ s/^&//;
                   5862: 
                   5863:       push(@array, $value);
1.191     harris41 5864:   }
1.265     albertel 5865: 
                   5866:   $string =~ s/^__END_ARRAY_REF__//;
                   5867: 
                   5868:   return (\@array, $string);
1.168     albertel 5869: }
                   5870: 
1.167     albertel 5871: # -------------------------------------------------------------------Temp Store
                   5872: 
1.168     albertel 5873: sub tmpreset {
                   5874:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5875:   if (!$symb) {
                   5876:     $symb=&symbread();
1.620     albertel 5877:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5878:   }
                   5879:   $symb=escape($symb);
                   5880: 
1.620     albertel 5881:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5882:   $namespace=~s/\//\_/g;
                   5883:   $namespace=~s/\W//g;
                   5884: 
1.620     albertel 5885:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5886:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5887:   if ($domain eq 'public' && $stuname eq 'public') {
                   5888:       $stuname=$ENV{'REMOTE_ADDR'};
                   5889:   }
1.1117    foxr     5890:   my $path=LONCAPA::tempdir();
1.168     albertel 5891:   my %hash;
                   5892:   if (tie(%hash,'GDBM_File',
                   5893: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5894: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5895:     foreach my $key (keys(%hash)) {
1.180     albertel 5896:       if ($key=~ /:$symb/) {
1.168     albertel 5897: 	delete($hash{$key});
                   5898:       }
                   5899:     }
                   5900:   }
                   5901: }
                   5902: 
1.167     albertel 5903: sub tmpstore {
1.168     albertel 5904:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5905: 
                   5906:   if (!$symb) {
                   5907:     $symb=&symbread();
1.620     albertel 5908:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5909:   }
                   5910:   $symb=escape($symb);
                   5911: 
                   5912:   if (!$namespace) {
                   5913:     # I don't think we would ever want to store this for a course.
                   5914:     # it seems this will only be used if we don't have a course.
1.620     albertel 5915:     #$namespace=$env{'request.course.id'};
1.168     albertel 5916:     #if (!$namespace) {
1.620     albertel 5917:       $namespace=$env{'request.state'};
1.168     albertel 5918:     #}
                   5919:   }
                   5920:   $namespace=~s/\//\_/g;
                   5921:   $namespace=~s/\W//g;
1.620     albertel 5922:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5923:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5924:   if ($domain eq 'public' && $stuname eq 'public') {
                   5925:       $stuname=$ENV{'REMOTE_ADDR'};
                   5926:   }
1.168     albertel 5927:   my $now=time;
                   5928:   my %hash;
1.1117    foxr     5929:   my $path=LONCAPA::tempdir();
1.168     albertel 5930:   if (tie(%hash,'GDBM_File',
                   5931: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5932: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5933:     $hash{"version:$symb"}++;
                   5934:     my $version=$hash{"version:$symb"};
                   5935:     my $allkeys=''; 
                   5936:     foreach my $key (keys(%$storehash)) {
                   5937:       $allkeys.=$key.':';
1.591     albertel 5938:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5939:     }
                   5940:     $hash{"$version:$symb:timestamp"}=$now;
                   5941:     $allkeys.='timestamp';
                   5942:     $hash{"$version:keys:$symb"}=$allkeys;
                   5943:     if (untie(%hash)) {
                   5944:       return 'ok';
                   5945:     } else {
                   5946:       return "error:$!";
                   5947:     }
                   5948:   } else {
                   5949:     return "error:$!";
                   5950:   }
                   5951: }
1.167     albertel 5952: 
1.168     albertel 5953: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5954: 
1.168     albertel 5955: sub tmprestore {
                   5956:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5957: 
1.168     albertel 5958:   if (!$symb) {
                   5959:     $symb=&symbread();
1.620     albertel 5960:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5961:   }
                   5962:   $symb=escape($symb);
                   5963: 
1.620     albertel 5964:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5965: 
1.620     albertel 5966:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5967:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5968:   if ($domain eq 'public' && $stuname eq 'public') {
                   5969:       $stuname=$ENV{'REMOTE_ADDR'};
                   5970:   }
1.168     albertel 5971:   my %returnhash;
                   5972:   $namespace=~s/\//\_/g;
                   5973:   $namespace=~s/\W//g;
                   5974:   my %hash;
1.1117    foxr     5975:   my $path=LONCAPA::tempdir();
1.168     albertel 5976:   if (tie(%hash,'GDBM_File',
                   5977: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5978: 	  &GDBM_READER(),0640)) {
1.168     albertel 5979:     my $version=$hash{"version:$symb"};
                   5980:     $returnhash{'version'}=$version;
                   5981:     my $scope;
                   5982:     for ($scope=1;$scope<=$version;$scope++) {
                   5983:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5984:       my @keys=split(/:/,$vkeys);
                   5985:       my $key;
                   5986:       $returnhash{"$scope:keys"}=$vkeys;
                   5987:       foreach $key (@keys) {
1.591     albertel 5988: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5989: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5990:       }
                   5991:     }
1.168     albertel 5992:     if (!(untie(%hash))) {
                   5993:       return "error:$!";
                   5994:     }
                   5995:   } else {
                   5996:     return "error:$!";
                   5997:   }
                   5998:   return %returnhash;
1.167     albertel 5999: }
                   6000: 
1.9       www      6001: # ----------------------------------------------------------------------- Store
                   6002: 
                   6003: sub store {
1.1172.2.64  raeburn  6004:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6005:     my $home='';
                   6006: 
1.168     albertel 6007:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6008: 
1.213     www      6009:     $symb=&symbclean($symb);
1.122     albertel 6010:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6011: 
1.620     albertel 6012:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6013:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6014: 
                   6015:     &devalidate($symb,$stuname,$domain);
1.109     www      6016: 
                   6017:     $symb=escape($symb);
1.187     www      6018:     if (!$namespace) { 
1.620     albertel 6019:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6020:           return ''; 
                   6021:        } 
                   6022:     }
1.620     albertel 6023:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6024: 
                   6025:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   6026:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6027: 
1.12      www      6028:     my $namevalue='';
1.800     albertel 6029:     foreach my $key (keys(%$storehash)) {
                   6030:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6031:     }
1.12      www      6032:     $namevalue=~s/\&$//;
1.187     www      6033:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  6034:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6035: }
                   6036: 
1.47      www      6037: # -------------------------------------------------------------- Critical Store
                   6038: 
                   6039: sub cstore {
1.1172.2.64  raeburn  6040:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6041:     my $home='';
                   6042: 
1.168     albertel 6043:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6044: 
1.213     www      6045:     $symb=&symbclean($symb);
1.122     albertel 6046:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6047: 
1.620     albertel 6048:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6049:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6050: 
                   6051:     &devalidate($symb,$stuname,$domain);
1.109     www      6052: 
                   6053:     $symb=escape($symb);
1.187     www      6054:     if (!$namespace) { 
1.620     albertel 6055:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6056:           return ''; 
                   6057:        } 
                   6058:     }
1.620     albertel 6059:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6060: 
                   6061:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   6062:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6063: 
1.47      www      6064:     my $namevalue='';
1.800     albertel 6065:     foreach my $key (keys(%$storehash)) {
                   6066:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6067:     }
1.47      www      6068:     $namevalue=~s/\&$//;
1.187     www      6069:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6070:     return critical
1.1172.2.64  raeburn  6071:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6072: }
                   6073: 
1.9       www      6074: # --------------------------------------------------------------------- Restore
                   6075: 
                   6076: sub restore {
1.124     www      6077:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6078:     my $home='';
                   6079: 
1.168     albertel 6080:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6081: 
1.122     albertel 6082:     if (!$symb) {
1.1172.2.26  raeburn  6083:         return if ($namespace eq 'courserequests');
                   6084:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6085:     } else {
1.1172.2.26  raeburn  6086:         unless ($namespace eq 'courserequests') {
                   6087:             $symb=&escape(&symbclean($symb));
                   6088:         }
1.122     albertel 6089:     }
1.188     www      6090:     if (!$namespace) { 
1.620     albertel 6091:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6092:           return ''; 
                   6093:        } 
                   6094:     }
1.620     albertel 6095:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6096:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6097:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6098:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6099: 
1.12      www      6100:     my %returnhash=();
1.800     albertel 6101:     foreach my $line (split(/\&/,$answer)) {
                   6102: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6103:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6104:     }
1.75      www      6105:     my $version;
                   6106:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6107:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6108:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6109:        }
1.75      www      6110:     }
1.13      www      6111:     return %returnhash;
1.34      www      6112: }
                   6113: 
                   6114: # ---------------------------------------------------------- Course Description
1.1118    foxr     6115: #
                   6116: #  
1.34      www      6117: 
                   6118: sub coursedescription {
1.731     albertel 6119:     my ($courseid,$args)=@_;
1.34      www      6120:     $courseid=~s/^\///;
1.49      www      6121:     $courseid=~s/\_/\//g;
1.34      www      6122:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6123:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6124:     my $normalid=$cdomain.'_'.$cnum;
                   6125:     # need to always cache even if we get errors otherwise we keep 
                   6126:     # trying and trying and trying to get the course description.
                   6127:     my %envhash=();
                   6128:     my %returnhash=();
1.731     albertel 6129:     
                   6130:     my $expiretime=600;
                   6131:     if ($env{'request.course.id'} eq $normalid) {
                   6132: 	$expiretime=120;
                   6133:     }
                   6134: 
                   6135:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6136:     if (!$args->{'freshen_cache'}
                   6137: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6138: 	foreach my $key (keys(%env)) {
                   6139: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6140: 	    my ($setting) = $1;
                   6141: 	    $returnhash{$setting} = $env{$key};
                   6142: 	}
                   6143: 	return %returnhash;
                   6144:     }
                   6145: 
1.1118    foxr     6146:     # get the data again
                   6147: 
1.731     albertel 6148:     if (!$args->{'one_time'}) {
                   6149: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6150:     }
1.811     albertel 6151: 
1.34      www      6152:     if ($chome ne 'no_host') {
1.302     albertel 6153:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6154:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6155: 	   my $username = $env{'user.name'}; # Defult username
                   6156: 	   if(defined $args->{'user'}) {
                   6157: 	       $username = $args->{'user'};
                   6158: 	   }
1.129     albertel 6159:            $returnhash{'home'}= $chome;
                   6160: 	   $returnhash{'domain'} = $cdomain;
                   6161: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6162:            if (!defined($returnhash{'type'})) {
                   6163:                $returnhash{'type'} = 'Course';
                   6164:            }
1.130     albertel 6165:            while (my ($name,$value) = each %returnhash) {
1.53      www      6166:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6167:            }
1.270     www      6168:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6169:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6170: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6171:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6172:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6173:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6174:        }
                   6175:     }
1.731     albertel 6176:     if (!$args->{'one_time'}) {
1.949     raeburn  6177: 	&appenv(\%envhash);
1.731     albertel 6178:     }
1.302     albertel 6179:     return %returnhash;
1.461     www      6180: }
                   6181: 
1.1080    raeburn  6182: sub update_released_required {
                   6183:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6184:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6185:         $cid = $env{'request.course.id'};
                   6186:         $cdom = $env{'course.'.$cid.'.domain'};
                   6187:         $cnum = $env{'course.'.$cid.'.num'};
                   6188:         $chome = $env{'course.'.$cid.'.home'};
                   6189:     }
                   6190:     if ($needsrelease) {
                   6191:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6192:         my $needsupdate;
                   6193:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6194:             $needsupdate = 1;
                   6195:         } else {
                   6196:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6197:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6198:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6199:                 $needsupdate = 1;
                   6200:             }
                   6201:         }
                   6202:         if ($needsupdate) {
                   6203:             my %needshash = (
                   6204:                              'internal.releaserequired' => $needsrelease,
                   6205:                             );
                   6206:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6207:             if ($putresult eq 'ok') {
                   6208:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6209:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6210:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6211:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6212:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6213:                 }
                   6214:             }
                   6215:         }
                   6216:     }
                   6217:     return;
                   6218: }
                   6219: 
1.461     www      6220: # -------------------------------------------------See if a user is privileged
                   6221: 
                   6222: sub privileged {
1.1172.2.23  raeburn  6223:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6224:     my $now = time;
1.1172.2.23  raeburn  6225:     my $roles;
                   6226:     if (ref($possroles) eq 'ARRAY') {
                   6227:         $roles = $possroles;
                   6228:     } else {
                   6229:         $roles = ['dc','su'];
                   6230:     }
                   6231:     if (ref($possdomains) eq 'ARRAY') {
                   6232:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6233:         foreach my $dom (@{$possdomains}) {
                   6234:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6235:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6236:                 foreach my $role (@{$roles}) {
                   6237:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6238:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6239:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6240:                             return 1 unless (($end && $end < $now) ||
                   6241:                                              ($start && $start > $now));
                   6242:                         }
                   6243:                     }
                   6244:                 }
                   6245:             }
                   6246:         }
                   6247:     } else {
                   6248:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6249:         my $now = time;
1.1170    droeschl 6250: 
1.1172.2.58  raeburn  6251:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6252:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6253:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6254:                 return 1 unless ($tend && $tend < $now)
                   6255:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6256:             }
1.1172.2.23  raeburn  6257:         }
                   6258:     }
1.461     www      6259:     return 0;
1.9       www      6260: }
1.1       albertel 6261: 
1.1172.2.23  raeburn  6262: sub privileged_by_domain {
                   6263:     my ($domains,$roles) = @_;
                   6264:     my %privileged = ();
                   6265:     my $cachetime = 60*60*24;
                   6266:     my $now = time;
                   6267:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6268:         return %privileged;
                   6269:     }
                   6270:     foreach my $dom (@{$domains}) {
                   6271:         next if (ref($privileged{$dom}) eq 'HASH');
                   6272:         my $needroles;
                   6273:         foreach my $role (@{$roles}) {
                   6274:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6275:             if (defined($cached)) {
                   6276:                 if (ref($result) eq 'HASH') {
                   6277:                     $privileged{$dom}{$role} = $result;
                   6278:                 }
                   6279:             } else {
                   6280:                 $needroles = 1;
                   6281:             }
                   6282:         }
                   6283:         if ($needroles) {
                   6284:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6285:             $privileged{$dom} = {};
                   6286:             foreach my $server (keys(%dompersonnel)) {
                   6287:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6288:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6289:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6290:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6291:                         next if ($end && $end < $now);
                   6292:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6293:                             $dompersonnel{$server}{$item};
                   6294:                     }
                   6295:                 }
                   6296:             }
                   6297:             if (ref($privileged{$dom}) eq 'HASH') {
                   6298:                 foreach my $role (@{$roles}) {
                   6299:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6300:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6301:                     } else {
                   6302:                         my %hash = ();
                   6303:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6304:                     }
                   6305:                 }
                   6306:             }
                   6307:         }
                   6308:     }
                   6309:     return %privileged;
                   6310: }
                   6311: 
1.103     harris41 6312: # -------------------------------------------------------- Get user privileges
1.11      www      6313: 
                   6314: sub rolesinit {
1.1169    droeschl 6315:     my ($domain, $username) = @_;
                   6316:     my %userroles = ('user.login.time' => time);
                   6317:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6318: 
                   6319:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6320:     # also, blocking can be triggered by an activating timer
                   6321:     # it's saved in the user's %env.
                   6322:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6323:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6324:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6325:         %timerintchk, %timerintenv);
                   6326: 
1.1162    raeburn  6327:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6328:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6329:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6330:     }
1.1169    droeschl 6331: 
1.1162    raeburn  6332:     foreach my $key (keys(%timerinterval)) {
                   6333:         my ($cid,$rest) = split(/\0/,$key);
                   6334:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6335:     }
1.1169    droeschl 6336: 
1.11      www      6337:     my %allroles=();
1.1162    raeburn  6338:     my %allgroups=();
1.11      www      6339: 
1.1172.2.58  raeburn  6340:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6341:         my $role = $rolesdump{$area};
                   6342:         $area =~ s/\_\w\w$//;
                   6343: 
                   6344:         my ($trole, $tend, $tstart, $group_privs);
                   6345: 
                   6346:         if ($role =~ /^cr/) {
                   6347:         # Custom role, defined by a user 
                   6348:         # e.g., user.role.cr/msu/smith/mynewrole
                   6349:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6350:                 $trole = $1;
                   6351:                 ($tend, $tstart) = split('_', $2);
                   6352:             } else {
                   6353:                 $trole = $role;
                   6354:             }
                   6355:         } elsif ($role =~ m|^gr/|) {
                   6356:         # Role of member in a group, defined within a course/community
                   6357:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6358:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6359:             next if $tstart eq '-1';
                   6360:             ($trole, $group_privs) = split(/\//, $trole);
                   6361:             $group_privs = &unescape($group_privs);
                   6362:         } else {
                   6363:         # Just a normal role, defined in roles.tab
                   6364:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6365:         }
                   6366: 
                   6367:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6368:                  $username);
                   6369:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6370: 
                   6371:         # role expired or not available yet?
                   6372:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6373:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6374: 
                   6375:         next if $area eq '' or $trole eq '';
                   6376: 
                   6377:         my $spec = "$trole.$area";
                   6378:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6379: 
                   6380:         if ($trole =~ /^cr\//) {
                   6381:         # Custom role, defined by a user
                   6382:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6383:         } elsif ($trole eq 'gr') {
                   6384:         # Role of a member in a group, defined within a course/community
                   6385:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6386:             next;
                   6387:         } else {
                   6388:         # Normal role, defined in roles.tab
                   6389:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6390:         }
                   6391: 
                   6392:         my $cid = $tdomain.'_'.$trest;
                   6393:         unless ($firstaccchk{$cid}) {
                   6394:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6395:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6396:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6397:                         $coursetimerstarts{$cid}{$item}; 
                   6398:                 }
                   6399:             }
                   6400:             $firstaccchk{$cid} = 1;
                   6401:         }
                   6402:         unless ($timerintchk{$cid}) {
                   6403:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6404:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6405:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6406:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6407:                 }
1.12      www      6408:             }
1.1169    droeschl 6409:             $timerintchk{$cid} = 1;
1.191     harris41 6410:         }
1.11      www      6411:     }
1.1169    droeschl 6412: 
1.1172.2.91  raeburn  6413:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6414:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6415:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6416:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6417: 
1.1162    raeburn  6418:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6419: }
                   6420: 
1.567     raeburn  6421: sub set_arearole {
1.1172.2.19  raeburn  6422:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6423:     unless ($nolog) {
1.567     raeburn  6424: # log the associated role with the area
1.1172.2.19  raeburn  6425:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6426:     }
1.743     albertel 6427:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6428: }
                   6429: 
                   6430: sub custom_roleprivs {
                   6431:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6432:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6433:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6434:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6435:         my ($rdummy,$roledef)=
                   6436:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6437:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6438:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6439:             if (defined($syspriv)) {
1.1043    raeburn  6440:                 if ($trest =~ /^$match_community$/) {
                   6441:                     $syspriv =~ s/bre\&S//; 
                   6442:                 }
1.567     raeburn  6443:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6444:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6445:             }
                   6446:             if ($tdomain ne '') {
                   6447:                 if (defined($dompriv)) {
                   6448:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6449:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6450:                 }
                   6451:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6452:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6453:                         my $rolename = $1;
                   6454:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6455:                     }
1.567     raeburn  6456:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6457:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6458:                 }
                   6459:             }
                   6460:         }
                   6461:     }
                   6462: }
                   6463: 
1.1172.2.89  raeburn  6464: sub course_adhocrole_privs {
                   6465:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6466:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6467:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6468:         my (%currprivs,%storeprivs);
                   6469:         foreach my $item (split(/:/,$coursepriv)) {
                   6470:             my ($priv,$restrict) = split(/\&/,$item);
                   6471:             $currprivs{$priv} = $restrict;
                   6472:         }
                   6473:         my (%possadd,%possremove,%full);
                   6474:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6475:             my ($priv,$restrict)=split(/\&/,$item);
                   6476:             $full{$priv} = $restrict;
                   6477:         }
                   6478:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6479:              next if ($item eq '');
                   6480:              my ($rule,$rest) = split(/=/,$item);
                   6481:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6482:              foreach my $priv (split(/:/,$rest)) {
                   6483:                  if ($priv ne '') {
                   6484:                      if ($rule eq 'off') {
                   6485:                          $possremove{$priv} = 1;
                   6486:                      } else {
                   6487:                          $possadd{$priv} = 1;
                   6488:                      }
                   6489:                  }
                   6490:              }
                   6491:          }
                   6492:          foreach my $priv (sort(keys(%full))) {
                   6493:              if (exists($currprivs{$priv})) {
                   6494:                  unless (exists($possremove{$priv})) {
                   6495:                      $storeprivs{$priv} = $currprivs{$priv};
                   6496:                  }
                   6497:              } elsif (exists($possadd{$priv})) {
                   6498:                  $storeprivs{$priv} = $full{$priv};
                   6499:              }
                   6500:          }
                   6501:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6502:      }
                   6503:      return $coursepriv;
                   6504: }
                   6505: 
1.678     raeburn  6506: sub group_roleprivs {
                   6507:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6508:     my $access = 1;
                   6509:     my $now = time;
                   6510:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6511:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6512:     if ($access) {
1.811     albertel 6513:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6514:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6515:     }
                   6516: }
1.567     raeburn  6517: 
                   6518: sub standard_roleprivs {
                   6519:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6520:     if (defined($pr{$trole.':s'})) {
                   6521:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6522:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6523:     }
                   6524:     if ($tdomain ne '') {
                   6525:         if (defined($pr{$trole.':d'})) {
                   6526:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6527:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6528:         }
                   6529:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6530:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6531:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6532:         }
                   6533:     }
                   6534: }
                   6535: 
                   6536: sub set_userprivs {
1.1064    raeburn  6537:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6538:     my $author=0;
                   6539:     my $adv=0;
1.1172.2.91  raeburn  6540:     my $rar=0;
1.678     raeburn  6541:     my %grouproles = ();
                   6542:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6543:         my @groupkeys; 
1.1000    raeburn  6544:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6545:             push(@groupkeys,$role);
                   6546:         }
                   6547:         if (ref($groups_roles) eq 'HASH') {
                   6548:             foreach my $key (keys(%{$groups_roles})) {
                   6549:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6550:                     push(@groupkeys,$key);
                   6551:                 }
                   6552:             }
                   6553:         }
                   6554:         if (@groupkeys > 0) {
                   6555:             foreach my $role (@groupkeys) {
                   6556:                 my ($trole,$area,$sec,$extendedarea);
                   6557:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6558:                     $trole = $1;
                   6559:                     $area = $2;
                   6560:                     $sec = $3;
                   6561:                     $extendedarea = $area.$sec;
                   6562:                     if (exists($$allgroups{$area})) {
                   6563:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6564:                             my $spec = $trole.'.'.$extendedarea;
                   6565:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6566:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6567:                         }
1.678     raeburn  6568:                     }
                   6569:                 }
                   6570:             }
                   6571:         }
                   6572:     }
1.800     albertel 6573:     foreach my $group (keys(%grouproles)) {
                   6574:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6575:     }
1.800     albertel 6576:     foreach my $role (keys(%{$allroles})) {
                   6577:         my %thesepriv;
1.941     raeburn  6578:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6579:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6580:             if ($item ne '') {
                   6581:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6582:                 if ($restrictions eq '') {
                   6583:                     $thesepriv{$privilege}='F';
                   6584:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6585:                     $thesepriv{$privilege}.=$restrictions;
                   6586:                 }
                   6587:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6588:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6589:             }
                   6590:         }
                   6591:         my $thesestr='';
1.1104    raeburn  6592:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6593: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6594: 	}
                   6595:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6596:     }
1.1172.2.91  raeburn  6597:     return ($author,$adv,$rar);
1.567     raeburn  6598: }
                   6599: 
1.994     raeburn  6600: sub role_status {
1.1104    raeburn  6601:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6602:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6603:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6604:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6605:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6606:             $$where = '/'.$two;
1.994     raeburn  6607:             $$trolecode=$$role.'.'.$$where;
                   6608:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6609:             $$tstatus='is';
1.1104    raeburn  6610:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6611:                 $$tstatus='future';
1.1034    raeburn  6612:                 if ($$tstart<$now) {
                   6613:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6614:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6615:                             my (%allroles,%allgroups,$group_privs,
                   6616:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6617:                             my %userroles = (
                   6618:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6619:                             );
1.1064    raeburn  6620:                             @rolecodes = ('cm'); 
1.1002    raeburn  6621:                             my $spec=$$role.'.'.$$where;
                   6622:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6623:                             if ($$role =~ /^cr\//) {
                   6624:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6625:                                 push(@rolecodes,'cr');
1.1002    raeburn  6626:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6627:                                 push(@rolecodes,$$role);
1.1002    raeburn  6628:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6629:                                                     $env{'user.name'});
1.1064    raeburn  6630:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6631:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6632:                                 $group_privs = &unescape($group_privs);
                   6633:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6634:                                 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  6635:                                 &get_groups_roles($tdomain,$trest,
                   6636:                                                   \%course_roles,\@rolecodes,
                   6637:                                                   \%groups_roles);
1.1002    raeburn  6638:                             } else {
1.1064    raeburn  6639:                                 push(@rolecodes,$$role);
1.1002    raeburn  6640:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6641:                             }
1.1172.2.91  raeburn  6642:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6643:                                                                    \%groups_roles);
1.1064    raeburn  6644:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6645:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6646:                         }
                   6647:                     }
1.1034    raeburn  6648:                     $$tstatus = 'is';
1.1002    raeburn  6649:                 }
1.994     raeburn  6650:             }
                   6651:             if ($$tend) {
1.1104    raeburn  6652:                 if ($$tend<$update) {
1.994     raeburn  6653:                     $$tstatus='expired';
                   6654:                 } elsif ($$tend<$now) {
                   6655:                     $$tstatus='will_not';
                   6656:                 }
                   6657:             }
                   6658:         }
                   6659:     }
                   6660: }
                   6661: 
1.1104    raeburn  6662: sub get_groups_roles {
                   6663:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6664:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6665:                   (ref($rolecodes) eq 'ARRAY') && 
                   6666:                   (ref($groups_roles) eq 'HASH')); 
                   6667:     if (keys(%{$cdom_courseroles}) > 0) {
                   6668:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6669:         if ($cdom ne '' && $cnum ne '') {
                   6670:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6671:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6672:                     my $crsrole = $1;
                   6673:                     my $crssec = $2;
                   6674:                     if ($crsrole =~ /^cr/) {
                   6675:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6676:                             push(@{$rolecodes},'cr');
                   6677:                         }
                   6678:                     } else {
                   6679:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6680:                             push(@{$rolecodes},$crsrole);
                   6681:                         }
                   6682:                     }
                   6683:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6684:                     if ($crssec ne '') {
                   6685:                         $rolekey .= "/$crssec";
                   6686:                     }
                   6687:                     $rolekey .= './';
                   6688:                     $groups_roles->{$rolekey} = $rolecodes;
                   6689:                 }
                   6690:             }
                   6691:         }
                   6692:     }
                   6693:     return;
                   6694: }
                   6695: 
                   6696: sub delete_env_groupprivs {
                   6697:     my ($where,$courseroles,$possroles) = @_;
                   6698:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6699:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6700:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6701:         %{$courseroles->{$udom}} =
                   6702:             &get_my_roles('','','userroles',['active'],
                   6703:                           $possroles,[$udom],1);
                   6704:     }
                   6705:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6706:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6707:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6708:             my $area = '/'.$cdom.'/'.$cnum;
                   6709:             my $privkey = "user.priv.$crsrole.$area";
                   6710:             if ($crssec ne '') {
                   6711:                 $privkey .= '/'.$crssec;
                   6712:             }
                   6713:             $privkey .= ".$area/$group";
                   6714:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6715:         }
                   6716:     }
                   6717:     return;
                   6718: }
                   6719: 
1.994     raeburn  6720: sub check_adhoc_privs {
1.1172.2.86  raeburn  6721:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6722:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6723:     if ($sec) {
                   6724:         $cckey .= '/'.$sec;
                   6725:     }
1.1172.2.9  raeburn  6726:     my $setprivs;
1.994     raeburn  6727:     if ($env{$cckey}) {
                   6728:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6729:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6730:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6731:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6732:             $setprivs = 1;
1.994     raeburn  6733:         }
                   6734:     } else {
1.1172.2.87  raeburn  6735:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6736:         $setprivs = 1;
1.994     raeburn  6737:     }
1.1172.2.9  raeburn  6738:     return $setprivs;
1.994     raeburn  6739: }
                   6740: 
                   6741: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6742: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6743:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6744:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6745:     if ($sec ne '') {
                   6746:         $area .= '/'.$sec;
                   6747:     }
1.994     raeburn  6748:     my $spec = $role.'.'.$area;
                   6749:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6750:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6751:     my %rolehash = ();
1.1172.2.89  raeburn  6752:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6753:         my $rolename = $1;
1.1172.2.84  raeburn  6754:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6755:         my %domdef = &get_domain_defaults($dcdom);
                   6756:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6757:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6758:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6759:             }
                   6760:         }
1.1172.2.84  raeburn  6761:     } else {
                   6762:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6763:     }
1.1172.2.91  raeburn  6764:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6765:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6766:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6767:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6768:         &appenv( {'request.role'        => $spec,
                   6769:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6770:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6771:                  }
                   6772:                );
                   6773:         my $tadv=0;
                   6774:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6775:         &appenv({'request.role.adv'    => $tadv});
                   6776:     }
1.994     raeburn  6777: }
                   6778: 
1.12      www      6779: # --------------------------------------------------------------- get interface
                   6780: 
                   6781: sub get {
1.131     albertel 6782:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6783:    my $items='';
1.800     albertel 6784:    foreach my $item (@$storearr) {
                   6785:        $items.=&escape($item).'&';
1.191     harris41 6786:    }
1.12      www      6787:    $items=~s/\&$//;
1.620     albertel 6788:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6789:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6790:    my $uhome=&homeserver($uname,$udomain);
                   6791: 
1.133     albertel 6792:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6793:    my @pairs=split(/\&/,$rep);
1.273     albertel 6794:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6795:      return @pairs;
                   6796:    }
1.15      www      6797:    my %returnhash=();
1.42      www      6798:    my $i=0;
1.800     albertel 6799:    foreach my $item (@$storearr) {
                   6800:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6801:       $i++;
1.191     harris41 6802:    }
1.15      www      6803:    return %returnhash;
1.27      www      6804: }
                   6805: 
                   6806: # --------------------------------------------------------------- del interface
                   6807: 
                   6808: sub del {
1.133     albertel 6809:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6810:    my $items='';
1.800     albertel 6811:    foreach my $item (@$storearr) {
                   6812:        $items.=&escape($item).'&';
1.191     harris41 6813:    }
1.984     neumanie 6814: 
1.27      www      6815:    $items=~s/\&$//;
1.620     albertel 6816:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6817:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6818:    my $uhome=&homeserver($uname,$udomain);
                   6819:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6820: }
                   6821: 
                   6822: # -------------------------------------------------------------- dump interface
                   6823: 
1.1172.2.22  raeburn  6824: sub unserialize {
                   6825:     my ($rep, $escapedkeys) = @_;
                   6826: 
                   6827:     return {} if $rep =~ /^error/;
                   6828: 
                   6829:     my %returnhash=();
                   6830:     foreach my $item (split(/\&/,$rep)) {
                   6831:         my ($key, $value) = split(/=/, $item, 2);
                   6832:         $key = unescape($key) unless $escapedkeys;
                   6833:         next if $key =~ /^error: 2 /;
                   6834:         $returnhash{$key} = &thaw_unescape($value);
                   6835:     }
                   6836:     return \%returnhash;
                   6837: }
                   6838: 
                   6839: # see Lond::dump_with_regexp
                   6840: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6841: sub dump {
1.1172.2.22  raeburn  6842:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6843:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6844:     if (!$uname) { $uname=$env{'user.name'}; }
                   6845:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6846: 
1.1172.2.55  raeburn  6847:     if ($regexp) {
                   6848:         $regexp=&escape($regexp);
                   6849:     } else {
                   6850:         $regexp='.';
                   6851:     }
1.1172.2.22  raeburn  6852:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6853:         # user is hosted on this machine
1.1172.2.55  raeburn  6854:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6855:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6856:         return %{&unserialize($reply, $escapedkeys)};
                   6857:     }
1.1166    raeburn  6858:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6859:     my @pairs=split(/\&/,$rep);
                   6860:     my %returnhash=();
1.1098    foxr     6861:     if (!($rep =~ /^error/ )) {
                   6862: 	foreach my $item (@pairs) {
                   6863: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6864:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6865: 	    next if ($key =~ /^error: 2 /);
                   6866: 	    $returnhash{$key}=&thaw_unescape($value);
                   6867: 	}
1.755     albertel 6868:     }
                   6869:     return %returnhash;
1.407     www      6870: }
                   6871: 
1.1098    foxr     6872: 
1.717     albertel 6873: # --------------------------------------------------------- dumpstore interface
                   6874: 
                   6875: sub dumpstore {
                   6876:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6877:    # same as dump but keys must be escaped. They may contain colon separated
                   6878:    # lists of values that may themself contain colons (e.g. symbs).
                   6879:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6880: }
                   6881: 
1.407     www      6882: # -------------------------------------------------------------- keys interface
                   6883: 
                   6884: sub getkeys {
                   6885:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6886:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6887:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6888:    my $uhome=&homeserver($uname,$udomain);
                   6889:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6890:    my @keyarray=();
1.800     albertel 6891:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6892:       next if ($key =~ /^error: 2 /);
1.800     albertel 6893:       push(@keyarray,&unescape($key));
1.407     www      6894:    }
                   6895:    return @keyarray;
1.318     matthew  6896: }
                   6897: 
1.319     matthew  6898: # --------------------------------------------------------------- currentdump
                   6899: sub currentdump {
1.328     matthew  6900:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6901:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6902:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6903:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6904:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6905:    my $rep;
                   6906: 
                   6907:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6908:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6909:                    $courseid)));
                   6910:    } else {
                   6911:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6912:    }
                   6913: 
1.318     matthew  6914:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6915:    #
1.318     matthew  6916:    my %returnhash=();
1.319     matthew  6917:    #
1.1172.2.118.  .1(raebu 6918:20):    if ($rep eq 'unknown_cmd') {
1.319     matthew  6919:        # an old lond will not know currentdump
                   6920:        # Do a dump and make it look like a currentdump
1.822     albertel 6921:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6922:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6923:        my %hash = @tmp;
                   6924:        @tmp=();
1.424     matthew  6925:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6926:    } else {
                   6927:        my @pairs=split(/\&/,$rep);
1.800     albertel 6928:        foreach my $pair (@pairs) {
                   6929:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6930:            my ($symb,$param) = split(/:/,$key);
                   6931:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6932:                                                         &thaw_unescape($value);
1.319     matthew  6933:        }
1.191     harris41 6934:    }
1.12      www      6935:    return %returnhash;
1.424     matthew  6936: }
                   6937: 
                   6938: sub convert_dump_to_currentdump{
                   6939:     my %hash = %{shift()};
                   6940:     my %returnhash;
                   6941:     # Code ripped from lond, essentially.  The only difference
                   6942:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6943:     # we might run in to problems with parameter names =~ /^v\./
                   6944:     while (my ($key,$value) = each(%hash)) {
                   6945:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6946: 	$symb  = &unescape($symb);
                   6947: 	$param = &unescape($param);
1.424     matthew  6948:         next if ($v eq 'version' || $symb eq 'keys');
                   6949:         next if (exists($returnhash{$symb}) &&
                   6950:                  exists($returnhash{$symb}->{$param}) &&
                   6951:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6952:         $returnhash{$symb}->{$param}=$value;
                   6953:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6954:     }
                   6955:     #
                   6956:     # Remove all of the keys in the hashes which keep track of
                   6957:     # the version of the parameter.
                   6958:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6959:         # use a foreach because we are going to delete from the hash.
                   6960:         foreach my $key (keys(%$param_hash)) {
                   6961:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6962:         }
                   6963:     }
                   6964:     return \%returnhash;
1.12      www      6965: }
                   6966: 
1.627     albertel 6967: # ------------------------------------------------------ critical inc interface
                   6968: 
                   6969: sub cinc {
                   6970:     return &inc(@_,'critical');
                   6971: }
                   6972: 
1.449     matthew  6973: # --------------------------------------------------------------- inc interface
                   6974: 
                   6975: sub inc {
1.627     albertel 6976:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6977:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6978:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6979:     my $uhome=&homeserver($uname,$udomain);
                   6980:     my $items='';
                   6981:     if (! ref($store)) {
                   6982:         # got a single value, so use that instead
                   6983:         $items = &escape($store).'=&';
                   6984:     } elsif (ref($store) eq 'SCALAR') {
                   6985:         $items = &escape($$store).'=&';        
                   6986:     } elsif (ref($store) eq 'ARRAY') {
                   6987:         $items = join('=&',map {&escape($_);} @{$store});
                   6988:     } elsif (ref($store) eq 'HASH') {
                   6989:         while (my($key,$value) = each(%{$store})) {
                   6990:             $items.= &escape($key).'='.&escape($value).'&';
                   6991:         }
                   6992:     }
                   6993:     $items=~s/\&$//;
1.627     albertel 6994:     if ($critical) {
                   6995: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6996:     } else {
                   6997: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6998:     }
1.449     matthew  6999: }
                   7000: 
1.12      www      7001: # --------------------------------------------------------------- put interface
                   7002: 
                   7003: sub put {
1.134     albertel 7004:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7005:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7006:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7007:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7008:    my $items='';
1.800     albertel 7009:    foreach my $item (keys(%$storehash)) {
                   7010:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7011:    }
1.12      www      7012:    $items=~s/\&$//;
1.134     albertel 7013:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      7014: }
                   7015: 
1.631     albertel 7016: # ------------------------------------------------------------ newput interface
                   7017: 
                   7018: sub newput {
                   7019:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7020:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7021:    if (!$uname) { $uname=$env{'user.name'}; }
                   7022:    my $uhome=&homeserver($uname,$udomain);
                   7023:    my $items='';
                   7024:    foreach my $key (keys(%$storehash)) {
                   7025:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7026:    }
                   7027:    $items=~s/\&$//;
                   7028:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7029: }
                   7030: 
                   7031: # ---------------------------------------------------------  putstore interface
                   7032: 
1.524     raeburn  7033: sub putstore {
1.1172.2.59  raeburn  7034:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7035:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7036:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7037:    my $uhome=&homeserver($uname,$udomain);
                   7038:    my $items='';
1.715     albertel 7039:    foreach my $key (keys(%$storehash)) {
                   7040:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7041:    }
1.715     albertel 7042:    $items=~s/\&$//;
1.716     albertel 7043:    my $esc_symb=&escape($symb);
                   7044:    my $esc_v=&escape($version);
1.715     albertel 7045:    my $reply =
1.716     albertel 7046:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7047: 	      $uhome);
1.1172.2.59  raeburn  7048:    if (($tolog) && ($reply eq 'ok')) {
                   7049:        my $namevalue='';
                   7050:        foreach my $key (keys(%{$storehash})) {
                   7051:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7052:        }
                   7053:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   7054:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7055:                      '&version='.$esc_v.
                   7056:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7057:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7058:    }
1.715     albertel 7059:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7060:        # gfall back to way things use to be done
1.715     albertel 7061:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7062: 			    $uname);
1.524     raeburn  7063:    }
1.715     albertel 7064:    return $reply;
                   7065: }
                   7066: 
                   7067: sub old_putstore {
1.716     albertel 7068:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7069:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7070:     if (!$uname) { $uname=$env{'user.name'}; }
                   7071:     my $uhome=&homeserver($uname,$udomain);
                   7072:     my %newstorehash;
1.800     albertel 7073:     foreach my $item (keys(%$storehash)) {
                   7074: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7075: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7076:     }
                   7077:     my $items='';
                   7078:     my %allitems = ();
1.800     albertel 7079:     foreach my $item (keys(%newstorehash)) {
                   7080: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7081: 	    my $key = $1.':keys:'.$2;
                   7082: 	    $allitems{$key} .= $3.':';
                   7083: 	}
1.800     albertel 7084: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7085:     }
1.800     albertel 7086:     foreach my $item (keys(%allitems)) {
                   7087: 	$allitems{$item} =~ s/\:$//;
                   7088: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7089:     }
                   7090:     $items=~s/\&$//;
                   7091:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7092: }
                   7093: 
1.47      www      7094: # ------------------------------------------------------ critical put interface
                   7095: 
                   7096: sub cput {
1.134     albertel 7097:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7098:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7099:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7100:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7101:    my $items='';
1.800     albertel 7102:    foreach my $item (keys(%$storehash)) {
                   7103:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7104:    }
1.47      www      7105:    $items=~s/\&$//;
1.134     albertel 7106:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7107: }
                   7108: 
                   7109: # -------------------------------------------------------------- eget interface
                   7110: 
                   7111: sub eget {
1.133     albertel 7112:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7113:    my $items='';
1.800     albertel 7114:    foreach my $item (@$storearr) {
                   7115:        $items.=&escape($item).'&';
1.191     harris41 7116:    }
1.12      www      7117:    $items=~s/\&$//;
1.620     albertel 7118:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7119:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7120:    my $uhome=&homeserver($uname,$udomain);
                   7121:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7122:    my @pairs=split(/\&/,$rep);
                   7123:    my %returnhash=();
1.42      www      7124:    my $i=0;
1.800     albertel 7125:    foreach my $item (@$storearr) {
                   7126:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7127:       $i++;
1.191     harris41 7128:    }
1.12      www      7129:    return %returnhash;
                   7130: }
                   7131: 
1.667     albertel 7132: # ------------------------------------------------------------ tmpput interface
                   7133: sub tmpput {
1.802     raeburn  7134:     my ($storehash,$server,$context)=@_;
1.667     albertel 7135:     my $items='';
1.800     albertel 7136:     foreach my $item (keys(%$storehash)) {
                   7137: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7138:     }
                   7139:     $items=~s/\&$//;
1.802     raeburn  7140:     if (defined($context)) {
                   7141:         $items .= ':'.&escape($context);
                   7142:     }
1.667     albertel 7143:     return &reply("tmpput:$items",$server);
                   7144: }
                   7145: 
                   7146: # ------------------------------------------------------------ tmpget interface
                   7147: sub tmpget {
1.688     albertel 7148:     my ($token,$server)=@_;
                   7149:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7150:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7151:     my %returnhash;
1.1172.2.85  raeburn  7152:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7153:         return %returnhash;
                   7154:     }
1.667     albertel 7155:     foreach my $item (split(/\&/,$rep)) {
                   7156: 	my ($key,$value)=split(/=/,$item);
                   7157: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7158:     }
                   7159:     return %returnhash;
                   7160: }
                   7161: 
1.1113    raeburn  7162: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7163: sub tmpdel {
                   7164:     my ($token,$server)=@_;
                   7165:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7166:     return &reply("tmpdel:$token",$server);
                   7167: }
                   7168: 
1.1172.2.13  raeburn  7169: # ------------------------------------------------------------ get_timebased_id
                   7170: 
                   7171: sub get_timebased_id {
                   7172:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7173:         $maxtries) = @_;
                   7174:     my ($newid,$error,$dellock);
                   7175:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7176:         return ('','ok','invalid call to get suffix');
                   7177:     }
                   7178: 
                   7179: # set defaults for any optional args for which values were not supplied
                   7180:     if ($who eq '') {
                   7181:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7182:     }
                   7183:     if (!$locktries) {
                   7184:         $locktries = 3;
                   7185:     }
                   7186:     if (!$maxtries) {
                   7187:         $maxtries = 10;
                   7188:     }
                   7189: 
                   7190:     if (($cdom eq '') || ($cnum eq '')) {
                   7191:         if ($env{'request.course.id'}) {
                   7192:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7193:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7194:         }
                   7195:         if (($cdom eq '') || ($cnum eq '')) {
                   7196:             return ('','ok','call to get suffix not in course context');
                   7197:         }
                   7198:     }
                   7199: 
                   7200: # construct locking item
                   7201:     my $lockhash = {
                   7202:                       $prefix."\0".'locked_'.$keyid => $who,
                   7203:                    };
                   7204:     my $tries = 0;
                   7205: 
                   7206: # attempt to get lock on nohist_$namespace file
                   7207:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7208:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7209:         $tries ++;
                   7210:         sleep 1;
                   7211:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7212:     }
                   7213: 
                   7214: # attempt to get unique identifier, based on current timestamp
                   7215:     if ($gotlock eq 'ok') {
                   7216:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7217:         my $id = time;
                   7218:         $newid = $id;
1.1172.2.56  raeburn  7219:         if ($idtype eq 'addcode') {
                   7220:             $newid .= &sixnum_code();
                   7221:         }
1.1172.2.13  raeburn  7222:         my $idtries = 0;
                   7223:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7224:             if ($idtype eq 'concat') {
                   7225:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7226:             } elsif ($idtype eq 'addcode') {
                   7227:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7228:             } else {
                   7229:                 $newid ++;
                   7230:             }
                   7231:             $idtries ++;
                   7232:         }
                   7233:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7234:             my %new_item =  (
                   7235:                               $prefix."\0".$newid => $who,
                   7236:                             );
                   7237:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7238:                                                  $cdom,$cnum);
                   7239:             if ($putresult ne 'ok') {
                   7240:                 undef($newid);
                   7241:                 $error = 'error saving new item: '.$putresult;
                   7242:             }
                   7243:         } else {
1.1172.2.56  raeburn  7244:              undef($newid);
1.1172.2.13  raeburn  7245:              $error = ('error: no unique suffix available for the new item ');
                   7246:         }
                   7247: #  remove lock
                   7248:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7249:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7250:     } else {
                   7251:         $error = "error: could not obtain lockfile\n";
                   7252:         $dellock = 'ok';
1.1172.2.58  raeburn  7253:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7254:             $dellock = 'nolock';
                   7255:         }
1.1172.2.13  raeburn  7256:     }
                   7257:     return ($newid,$dellock,$error);
                   7258: }
                   7259: 
1.1172.2.56  raeburn  7260: sub sixnum_code {
                   7261:     my $code;
                   7262:     for (0..6) {
                   7263:         $code .= int( rand(9) );
                   7264:     }
                   7265:     return $code;
                   7266: }
                   7267: 
1.765     albertel 7268: # -------------------------------------------------- portfolio access checking
                   7269: 
                   7270: sub portfolio_access {
1.1172.2.77  raeburn  7271:     my ($requrl,$clientip) = @_;
1.765     albertel 7272:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7273:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7274:     if ($result) {
                   7275:         my %setters;
                   7276:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7277:             my ($startblock,$endblock) =
                   7278:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7279:             if ($startblock && $endblock) {
                   7280:                 return 'B';
                   7281:             }
                   7282:         } else {
                   7283:             my ($startblock,$endblock) =
                   7284:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7285:             if ($startblock && $endblock) {
                   7286:                 return 'B';
                   7287:             }
                   7288:         }
                   7289:     }
1.765     albertel 7290:     if ($result eq 'ok') {
1.766     albertel 7291:        return 'F';
1.765     albertel 7292:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7293:        return 'A';
1.765     albertel 7294:     }
1.766     albertel 7295:     return '';
1.765     albertel 7296: }
                   7297: 
                   7298: sub get_portfolio_access {
1.1172.2.77  raeburn  7299:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7300: 
                   7301:     if (!ref($access_hash)) {
                   7302: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7303: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7304: 						   $file_name);
                   7305: 	$access_hash = $access_controls{$file_name};
                   7306:     }
                   7307: 
1.1172.2.77  raeburn  7308:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7309:     my $now = time;
                   7310:     if (ref($access_hash) eq 'HASH') {
                   7311:         foreach my $key (keys(%{$access_hash})) {
                   7312:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7313:             if ($start > $now) {
                   7314:                 next;
                   7315:             }
                   7316:             if ($end && $end<$now) {
                   7317:                 next;
                   7318:             }
                   7319:             if ($scope eq 'public') {
                   7320:                 $public = $key;
                   7321:                 last;
                   7322:             } elsif ($scope eq 'guest') {
                   7323:                 $guest = $key;
                   7324:             } elsif ($scope eq 'domains') {
                   7325:                 push(@domains,$key);
                   7326:             } elsif ($scope eq 'users') {
                   7327:                 push(@users,$key);
                   7328:             } elsif ($scope eq 'course') {
                   7329:                 push(@courses,$key);
                   7330:             } elsif ($scope eq 'group') {
                   7331:                 push(@groups,$key);
1.1172.2.77  raeburn  7332:             } elsif ($scope eq 'ip') {
                   7333:                 push(@ips,$key);
1.765     albertel 7334:             }
                   7335:         }
                   7336:         if ($public) {
                   7337:             return 'ok';
1.1172.2.77  raeburn  7338:         } elsif (@ips > 0) {
                   7339:             my $allowed;
                   7340:             foreach my $ipkey (@ips) {
                   7341:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7342:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7343:                         $allowed = 1;
                   7344:                         last;
                   7345:                     }
                   7346:                 }
                   7347:             }
                   7348:             if ($allowed) {
                   7349:                 return 'ok';
                   7350:             }
1.765     albertel 7351:         }
                   7352:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7353:             if ($guest) {
                   7354:                 return $guest;
                   7355:             }
                   7356:         } else {
                   7357:             if (@domains > 0) {
                   7358:                 foreach my $domkey (@domains) {
                   7359:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7360:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7361:                             return 'ok';
                   7362:                         }
                   7363:                     }
                   7364:                 }
                   7365:             }
                   7366:             if (@users > 0) {
                   7367:                 foreach my $userkey (@users) {
1.865     raeburn  7368:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7369:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7370:                             if (ref($item) eq 'HASH') {
                   7371:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7372:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7373:                                     return 'ok';
                   7374:                                 }
                   7375:                             }
                   7376:                         }
                   7377:                     } 
1.765     albertel 7378:                 }
                   7379:             }
                   7380:             my %roleshash;
                   7381:             my @courses_and_groups = @courses;
                   7382:             push(@courses_and_groups,@groups); 
                   7383:             if (@courses_and_groups > 0) {
                   7384:                 my (%allgroups,%allroles); 
                   7385:                 my ($start,$end,$role,$sec,$group);
                   7386:                 foreach my $envkey (%env) {
1.1060    raeburn  7387:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7388:                         my $cid = $2.'_'.$3; 
                   7389:                         if ($1 eq 'gr') {
                   7390:                             $group = $4;
                   7391:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7392:                         } else {
                   7393:                             if ($4 eq '') {
                   7394:                                 $sec = 'none';
                   7395:                             } else {
                   7396:                                 $sec = $4;
                   7397:                             }
                   7398:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7399:                         }
1.811     albertel 7400:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7401:                         my $cid = $2.'_'.$3;
                   7402:                         if ($4 eq '') {
                   7403:                             $sec = 'none';
                   7404:                         } else {
                   7405:                             $sec = $4;
                   7406:                         }
                   7407:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7408:                     }
                   7409:                 }
                   7410:                 if (keys(%allroles) == 0) {
                   7411:                     return;
                   7412:                 }
                   7413:                 foreach my $key (@courses_and_groups) {
                   7414:                     my %content = %{$$access_hash{$key}};
                   7415:                     my $cnum = $content{'number'};
                   7416:                     my $cdom = $content{'domain'};
                   7417:                     my $cid = $cdom.'_'.$cnum;
                   7418:                     if (!exists($allroles{$cid})) {
                   7419:                         next;
                   7420:                     }    
                   7421:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7422:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7423:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7424:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7425:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7426:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7427:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7428:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7429:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7430:                                         if (grep/^all$/,@sections) {
                   7431:                                             return 'ok';
                   7432:                                         } else {
                   7433:                                             if (grep/^$sec$/,@sections) {
                   7434:                                                 return 'ok';
                   7435:                                             }
                   7436:                                         }
                   7437:                                     }
                   7438:                                 }
                   7439:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7440:                                     if (grep/^none$/,@groups) {
                   7441:                                         return 'ok';
                   7442:                                     }
                   7443:                                 } else {
                   7444:                                     if (grep/^all$/,@groups) {
                   7445:                                         return 'ok';
                   7446:                                     } 
                   7447:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7448:                                         if (grep/^$group$/,@groups) {
                   7449:                                             return 'ok';
                   7450:                                         }
                   7451:                                     }
                   7452:                                 } 
                   7453:                             }
                   7454:                         }
                   7455:                     }
                   7456:                 }
                   7457:             }
                   7458:             if ($guest) {
                   7459:                 return $guest;
                   7460:             }
                   7461:         }
                   7462:     }
                   7463:     return;
                   7464: }
                   7465: 
                   7466: sub course_group_datechecker {
                   7467:     my ($dates,$now,$status) = @_;
                   7468:     my ($start,$end) = split(/\./,$dates);
                   7469:     if (!$start && !$end) {
                   7470:         return 'ok';
                   7471:     }
                   7472:     if (grep/^active$/,@{$status}) {
                   7473:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7474:             return 'ok';
                   7475:         }
                   7476:     }
                   7477:     if (grep/^previous$/,@{$status}) {
                   7478:         if ($end > $now ) {
                   7479:             return 'ok';
                   7480:         }
                   7481:     }
                   7482:     if (grep/^future$/,@{$status}) {
                   7483:         if ($start > $now) {
                   7484:             return 'ok';
                   7485:         }
                   7486:     }
                   7487:     return; 
                   7488: }
                   7489: 
                   7490: sub parse_portfolio_url {
                   7491:     my ($url) = @_;
                   7492: 
                   7493:     my ($type,$udom,$unum,$group,$file_name);
                   7494:     
1.823     albertel 7495:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7496: 	$type = 1;
                   7497:         $udom = $1;
                   7498:         $unum = $2;
                   7499:         $file_name = $3;
1.823     albertel 7500:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7501: 	$type = 2;
                   7502:         $udom = $1;
                   7503:         $unum = $2;
                   7504:         $group = $3;
                   7505:         $file_name = $3.'/'.$4;
                   7506:     }
                   7507:     if (wantarray) {
                   7508: 	return ($type,$udom,$unum,$file_name,$group);
                   7509:     }
                   7510:     return $type;
                   7511: }
                   7512: 
                   7513: sub is_portfolio_url {
                   7514:     my ($url) = @_;
                   7515:     return scalar(&parse_portfolio_url($url));
                   7516: }
                   7517: 
1.798     raeburn  7518: sub is_portfolio_file {
                   7519:     my ($file) = @_;
1.820     raeburn  7520:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7521:         return 1;
                   7522:     }
                   7523:     return;
                   7524: }
                   7525: 
1.976     raeburn  7526: sub usertools_access {
1.1084    raeburn  7527:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7528:     my ($access,%tools);
                   7529:     if ($context eq '') {
                   7530:         $context = 'tools';
                   7531:     }
                   7532:     if ($context eq 'requestcourses') {
                   7533:         %tools = (
                   7534:                       official   => 1,
                   7535:                       unofficial => 1,
1.1006    raeburn  7536:                       community  => 1,
1.1172.2.37  raeburn  7537:                       textbook   => 1,
1.985     raeburn  7538:                  );
1.1172.2.9  raeburn  7539:     } elsif ($context eq 'requestauthor') {
                   7540:         %tools = (
                   7541:                       requestauthor => 1,
                   7542:                  );
1.985     raeburn  7543:     } else {
                   7544:         %tools = (
                   7545:                       aboutme   => 1,
                   7546:                       blog      => 1,
1.1172.2.6  raeburn  7547:                       webdav    => 1,
1.985     raeburn  7548:                       portfolio => 1,
                   7549:                  );
                   7550:     }
1.976     raeburn  7551:     return if (!defined($tools{$tool}));
                   7552: 
1.1172.2.35  raeburn  7553:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7554:         $udom = $env{'user.domain'};
                   7555:         $uname = $env{'user.name'};
                   7556:     }
                   7557: 
1.978     raeburn  7558:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7559:         if ($action ne 'reload') {
1.985     raeburn  7560:             if ($context eq 'requestcourses') {
                   7561:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7562:             } elsif ($context eq 'requestauthor') {
                   7563:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7564:             } else {
                   7565:                 return $env{'environment.availabletools.'.$tool};
                   7566:             }
                   7567:         }
1.976     raeburn  7568:     }
                   7569: 
1.1172.2.9  raeburn  7570:     my ($toolstatus,$inststatus,$envkey);
                   7571:     if ($context eq 'requestauthor') {
                   7572:         $envkey = $context;
                   7573:     } else {
                   7574:         $envkey = $context.'.'.$tool;
                   7575:     }
1.976     raeburn  7576: 
1.985     raeburn  7577:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7578:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7579:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7580:         $inststatus = $env{'environment.inststatus'};
                   7581:     } else {
1.1084    raeburn  7582:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7583:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7584:             $inststatus = $userenvref->{'inststatus'};
                   7585:         } else {
1.1172.2.9  raeburn  7586:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7587:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7588:             $inststatus = $userenv{'inststatus'};
                   7589:         }
1.976     raeburn  7590:     }
                   7591: 
                   7592:     if ($toolstatus ne '') {
                   7593:         if ($toolstatus) {
                   7594:             $access = 1;
                   7595:         } else {
                   7596:             $access = 0;
                   7597:         }
                   7598:         return $access;
                   7599:     }
                   7600: 
1.1084    raeburn  7601:     my ($is_adv,%domdef);
                   7602:     if (ref($is_advref) eq 'HASH') {
                   7603:         $is_adv = $is_advref->{'is_adv'};
                   7604:     } else {
                   7605:         $is_adv = &is_advanced_user($udom,$uname);
                   7606:     }
                   7607:     if (ref($domdefref) eq 'HASH') {
                   7608:         %domdef = %{$domdefref};
                   7609:     } else {
                   7610:         %domdef = &get_domain_defaults($udom);
                   7611:     }
1.976     raeburn  7612:     if (ref($domdef{$tool}) eq 'HASH') {
                   7613:         if ($is_adv) {
                   7614:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7615:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7616:                     $access = 1;
                   7617:                 } else {
                   7618:                     $access = 0;
                   7619:                 }
                   7620:                 return $access;
                   7621:             }
                   7622:         }
                   7623:         if ($inststatus ne '') {
                   7624:             my ($hasaccess,$hasnoaccess);
                   7625:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7626:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7627:                     if ($domdef{$tool}{$affiliation}) {
                   7628:                         $hasaccess = 1;
                   7629:                     } else {
                   7630:                         $hasnoaccess = 1;
                   7631:                     }
                   7632:                 }
                   7633:             }
                   7634:             if ($hasaccess || $hasnoaccess) {
                   7635:                 if ($hasaccess) {
                   7636:                     $access = 1;
                   7637:                 } elsif ($hasnoaccess) {
                   7638:                     $access = 0; 
                   7639:                 }
                   7640:                 return $access;
                   7641:             }
                   7642:         } else {
                   7643:             if ($domdef{$tool}{'default'} ne '') {
                   7644:                 if ($domdef{$tool}{'default'}) {
                   7645:                     $access = 1;
                   7646:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7647:                     $access = 0;
                   7648:                 }
                   7649:                 return $access;
                   7650:             }
                   7651:         }
                   7652:     } else {
1.1172.2.6  raeburn  7653:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7654:             $access = 1;
                   7655:         } else {
                   7656:             $access = 0;
                   7657:         }
1.976     raeburn  7658:         return $access;
                   7659:     }
                   7660: }
                   7661: 
1.1050    raeburn  7662: sub is_course_owner {
                   7663:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7664:     if (($udom eq '') || ($uname eq '')) {
                   7665:         $udom = $env{'user.domain'};
                   7666:         $uname = $env{'user.name'};
                   7667:     }
                   7668:     unless (($udom eq '') || ($uname eq '')) {
                   7669:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7670:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7671:                 return 1;
                   7672:             } else {
                   7673:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7674:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7675:                     return 1;
                   7676:                 }
                   7677:             }
                   7678:         }
                   7679:     }
                   7680:     return;
                   7681: }
                   7682: 
1.976     raeburn  7683: sub is_advanced_user {
                   7684:     my ($udom,$uname) = @_;
1.1085    raeburn  7685:     if ($udom ne '' && $uname ne '') {
                   7686:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7687:             if (wantarray) {
                   7688:                 return ($env{'user.adv'},$env{'user.author'});
                   7689:             } else {
                   7690:                 return $env{'user.adv'};
                   7691:             }
1.1085    raeburn  7692:         }
                   7693:     }
1.976     raeburn  7694:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7695:     my %allroles;
1.1128    raeburn  7696:     my ($is_adv,$is_author);
1.976     raeburn  7697:     foreach my $role (keys(%roleshash)) {
                   7698:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7699:         my $area = '/'.$tdomain.'/'.$trest;
                   7700:         if ($sec ne '') {
                   7701:             $area .= '/'.$sec;
                   7702:         }
                   7703:         if (($area ne '') && ($trole ne '')) {
                   7704:             my $spec=$trole.'.'.$area;
                   7705:             if ($trole =~ /^cr\//) {
                   7706:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7707:             } elsif ($trole ne 'gr') {
                   7708:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7709:             }
1.1128    raeburn  7710:             if ($trole eq 'au') {
                   7711:                 $is_author = 1;
                   7712:             }
1.976     raeburn  7713:         }
                   7714:     }
                   7715:     foreach my $role (keys(%allroles)) {
                   7716:         last if ($is_adv);
                   7717:         foreach my $item (split(/:/,$allroles{$role})) {
                   7718:             if ($item ne '') {
                   7719:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7720:                 if ($privilege eq 'adv') {
                   7721:                     $is_adv = 1;
                   7722:                     last;
                   7723:                 }
                   7724:             }
                   7725:         }
                   7726:     }
1.1128    raeburn  7727:     if (wantarray) {
                   7728:         return ($is_adv,$is_author);
                   7729:     }
1.976     raeburn  7730:     return $is_adv;
                   7731: }
1.798     raeburn  7732: 
1.1035    raeburn  7733: sub check_can_request {
1.1036    raeburn  7734:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7735:     my $canreq = 0;
                   7736:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7737:     my @options = ('approval','validate','autolimit');
                   7738:     my $optregex = join('|',@options);
                   7739:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7740:         foreach my $type (@{$types}) {
                   7741:             if (&usertools_access($env{'user.name'},
                   7742:                                   $env{'user.domain'},
                   7743:                                   $type,undef,'requestcourses')) {
                   7744:                 $canreq ++;
1.1036    raeburn  7745:                 if (ref($request_domains) eq 'HASH') {
                   7746:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7747:                 }
1.1035    raeburn  7748:                 if ($dom eq $env{'user.domain'}) {
                   7749:                     $can_request->{$type} = 1;
                   7750:                 }
                   7751:             }
                   7752:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7753:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7754:                 if (@curr > 0) {
1.1036    raeburn  7755:                     foreach my $item (@curr) {
                   7756:                         if (ref($request_domains) eq 'HASH') {
                   7757:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7758:                             if ($otherdom ne '') {
                   7759:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7760:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7761:                                         push(@{$request_domains->{$type}},$otherdom);
                   7762:                                     }
                   7763:                                 } else {
                   7764:                                     push(@{$request_domains->{$type}},$otherdom);
                   7765:                                 }
                   7766:                             }
                   7767:                         }
                   7768:                     }
                   7769:                     unless($dom eq $env{'user.domain'}) {
                   7770:                         $canreq ++;
1.1035    raeburn  7771:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7772:                             $can_request->{$type} = 1;
                   7773:                         }
                   7774:                     }
                   7775:                 }
                   7776:             }
                   7777:         }
                   7778:     }
                   7779:     return $canreq;
                   7780: }
                   7781: 
1.341     www      7782: # ---------------------------------------------- Custom access rule evaluation
                   7783: 
                   7784: sub customaccess {
                   7785:     my ($priv,$uri)=@_;
1.807     albertel 7786:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7787:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7788:     $udom = &LONCAPA::clean_domain($udom);
                   7789:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7790:     my $access=0;
1.800     albertel 7791:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7792: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7793: 	if ($type eq 'user') {
                   7794: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7795: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7796: 		if ($tdom) {
                   7797: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7798: 		}
1.896     albertel 7799: 		if ($tuname) {
                   7800: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7801: 		}
                   7802: 		$access=($effect eq 'allow');
                   7803: 		last;
                   7804: 	    }
                   7805: 	} else {
                   7806: 	    if ($role) {
                   7807: 		if ($role ne $urole) { next; }
                   7808: 	    }
                   7809: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7810: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7811: 		if ($tdom) {
                   7812: 		    if ($tdom ne $udom) { next; }
                   7813: 		}
                   7814: 		if ($tcrs) {
                   7815: 		    if ($tcrs ne $ucrs) { next; }
                   7816: 		}
                   7817: 		if ($tsec) {
                   7818: 		    if ($tsec ne $usec) { next; }
                   7819: 		}
                   7820: 		$access=($effect eq 'allow');
                   7821: 		last;
                   7822: 	    }
                   7823: 	    if ($realm eq '' && $role eq '') {
                   7824: 		$access=($effect eq 'allow');
                   7825: 	    }
1.402     bowersj2 7826: 	}
1.341     www      7827:     }
                   7828:     return $access;
                   7829: }
                   7830: 
1.103     harris41 7831: # ------------------------------------------------- Check for a user privilege
1.12      www      7832: 
                   7833: sub allowed {
1.1172.2.65  raeburn  7834:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7835:     my $ver_orguri=$uri;
1.439     www      7836:     $uri=&deversion($uri);
1.152     www      7837:     my $orguri=$uri;
1.52      www      7838:     $uri=&declutter($uri);
1.809     raeburn  7839: 
1.810     raeburn  7840:     if ($priv eq 'evb') {
                   7841: # Evade communication block restrictions for specified role in a course
                   7842:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7843:             return $1;
                   7844:         } else {
                   7845:             return;
                   7846:         }
                   7847:     }
                   7848: 
1.620     albertel 7849:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7850: # Free bre access to adm and meta resources
1.1172.2.118.  .1(raebu 7851:20):     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
1.769     albertel 7852: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7853: 	&& ($priv eq 'bre')) {
1.14      www      7854: 	return 'F';
1.159     www      7855:     }
                   7856: 
1.545     banghart 7857: # Free bre access to user's own portfolio contents
1.714     raeburn  7858:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7859:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7860: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7861:         my %setters;
                   7862:         my ($startblock,$endblock) = 
                   7863:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7864:         if ($startblock && $endblock) {
                   7865:             return 'B';
                   7866:         } else {
                   7867:             return 'F';
                   7868:         }
1.545     banghart 7869:     }
                   7870: 
1.762     raeburn  7871: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7872:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7873:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7874:         if (exists($env{'request.course.id'})) {
                   7875:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7876:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7877:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7878:                 my $courseprivid=$env{'request.course.id'};
                   7879:                 $courseprivid=~s/\_/\//;
                   7880:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7881:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7882:                     return $1; 
1.762     raeburn  7883:                 } else {
                   7884:                     if ($env{'request.course.sec'}) {
                   7885:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7886:                     }
                   7887:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7888:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7889:                         return $2;
                   7890:                     }
1.714     raeburn  7891:                 }
                   7892:             }
                   7893:         }
                   7894:     }
                   7895: 
1.159     www      7896: # Free bre to public access
                   7897: 
                   7898:     if ($priv eq 'bre') {
1.238     www      7899:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7900: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7901:            return 'F'; 
                   7902:         }
1.238     www      7903:         if ($copyright eq 'priv') {
                   7904:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7905: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7906: 		return '';
                   7907:             }
                   7908:         }
                   7909:         if ($copyright eq 'domain') {
                   7910:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7911: 	    unless (($env{'user.domain'} eq $1) ||
                   7912:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7913: 		return '';
                   7914:             }
1.262     matthew  7915:         }
1.620     albertel 7916:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7917:             # Library role, so allow browsing of resources in this domain.
                   7918:             return 'F';
1.238     www      7919:         }
1.341     www      7920:         if ($copyright eq 'custom') {
                   7921: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7922:         }
1.14      www      7923:     }
1.264     matthew  7924:     # Domain coordinator is trying to create a course
1.620     albertel 7925:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7926:         # uri is the requested domain in this case.
                   7927:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7928:         # a role of dc for the domain in question.
1.620     albertel 7929:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7930:     }
1.29      www      7931: 
1.52      www      7932:     my $thisallowed='';
                   7933:     my $statecond=0;
                   7934:     my $courseprivid='';
                   7935: 
1.1039    raeburn  7936:     my $ownaccess;
1.1043    raeburn  7937:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7938:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7939:         if ($uri eq '') {
                   7940:             $ownaccess = 1;
                   7941:         } else {
                   7942:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7943:                 my $udom = $env{'user.domain'};
                   7944:                 my $uname = $env{'user.name'};
                   7945:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7946:                     $ownaccess = 1;
1.1040    raeburn  7947:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7948:                     unless ($uri =~ m{\.\./}) {
                   7949:                         $ownaccess = 1;
                   7950:                     }
                   7951:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7952:                     my $now = time;
                   7953:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7954:                         my $adom = $1;
                   7955:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7956:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7957:                                 my ($start,$end) = split('.',$env{$key});
                   7958:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7959:                                     $ownaccess = 1;
                   7960:                                     last;
                   7961:                                 }
                   7962:                             }
                   7963:                         }
                   7964:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7965:                         my $adom = $1;
                   7966:                         my $aname = $2;
1.1042    raeburn  7967:                         foreach my $role ('ca','aa') { 
                   7968:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7969:                                 my ($start,$end) =
                   7970:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7971:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7972:                                     $ownaccess = 1;
                   7973:                                     last;
                   7974:                                 }
1.1039    raeburn  7975:                             }
                   7976:                         }
                   7977:                     }
                   7978:                 }
                   7979:             }
                   7980:         }
                   7981:     }
                   7982: 
1.52      www      7983: # Course
                   7984: 
1.620     albertel 7985:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7986:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7987:             $thisallowed.=$1;
                   7988:         }
1.52      www      7989:     }
1.29      www      7990: 
1.52      www      7991: # Domain
                   7992: 
1.620     albertel 7993:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7994:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7995:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7996:             $thisallowed.=$1;
                   7997:         }
1.12      www      7998:     }
1.52      www      7999: 
1.1141    raeburn  8000: # User who is not author or co-author might still be able to edit
                   8001: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8002:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8003:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8004:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8005:             $thisallowed.=$1;
                   8006:         }
                   8007:     }
                   8008: 
1.52      www      8009: # Course: uri itself is a course
1.66      www      8010:     my $courseuri=$uri;
                   8011:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8012:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8013: 
1.620     albertel 8014:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8015:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  8016:         if ($priv eq 'mip') {
                   8017:             my $rem = $1;
                   8018:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8019:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8020:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8021:                 if ($cdom ne '') {
                   8022:                     my %passwdconf = &get_passwdconf($cdom);
                   8023:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8024:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8025:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8026:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8027:                                 unless (@inststatuses) {
                   8028:                                     @inststatuses = ('default');
                   8029:                                 }
                   8030:                                 foreach my $status (@inststatuses) {
                   8031:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8032:                                         $thisallowed.=$rem;
                   8033:                                     }
                   8034:                                 }
                   8035:                             }
                   8036:                         }
                   8037:                     }
                   8038:                 }
                   8039:             }
                   8040:         } else {
                   8041:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8042:                 $thisallowed.=$1;
                   8043:             }
1.1039    raeburn  8044:         }
1.12      www      8045:     }
1.29      www      8046: 
1.665     albertel 8047: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8048: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8049:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8050: 	$thisallowed='';
1.671     raeburn  8051:         my ($match)=&is_on_map($uri);
                   8052:         if ($match) {
                   8053:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8054:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  8055:                 my $value = $1;
                   8056:                 if ($noblockcheck) {
                   8057:                     $thisallowed.=$value;
1.1162    raeburn  8058:                 } else {
1.1172.2.65  raeburn  8059:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   8060:                     if (@blockers > 0) {
                   8061:                         $thisallowed = 'B';
                   8062:                     } else {
                   8063:                         $thisallowed.=$value;
                   8064:                     }
1.1162    raeburn  8065:                 }
1.671     raeburn  8066:             }
                   8067:         } else {
1.705     albertel 8068:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8069:             if ($refuri) {
                   8070:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8071:                     $thisallowed='F';
1.671     raeburn  8072:                 } else {
                   8073:                     $refuri=&declutter($refuri);
                   8074:                     my ($match) = &is_on_map($refuri);
                   8075:                     if ($match) {
1.1172.2.65  raeburn  8076:                         if ($noblockcheck) {
1.1162    raeburn  8077:                             $thisallowed='F';
1.1172.2.65  raeburn  8078:                         } else {
                   8079:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   8080:                             if (@blockers > 0) {
                   8081:                                 $thisallowed = 'B';
                   8082:                             } else {
                   8083:                                 $thisallowed='F';
                   8084:                             }
1.1162    raeburn  8085:                         }
1.671     raeburn  8086:                     }
1.669     raeburn  8087:                 }
1.671     raeburn  8088:             }
                   8089:         }
1.314     www      8090:     }
1.492     albertel 8091: 
1.766     albertel 8092:     if ($priv eq 'bre'
                   8093: 	&& $thisallowed ne 'F' 
                   8094: 	&& $thisallowed ne '2'
                   8095: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8096: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8097:     }
                   8098:     
1.52      www      8099: # Full access at system, domain or course-wide level? Exit.
1.29      www      8100:     if ($thisallowed=~/F/) {
                   8101: 	return 'F';
                   8102:     }
                   8103: 
1.52      www      8104: # If this is generating or modifying users, exit with special codes
1.29      www      8105: 
1.643     www      8106:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8107: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8108: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8109: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8110: 	    unless ($auname) { return $thisallowed; }
                   8111: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8112: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8113: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8114: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8115: 	}
1.52      www      8116: 	return $thisallowed;
                   8117:     }
                   8118: #
1.103     harris41 8119: # Gathered so far: system, domain and course wide privileges
1.52      www      8120: #
                   8121: # Course: See if uri or referer is an individual resource that is part of 
                   8122: # the course
                   8123: 
1.620     albertel 8124:     if ($env{'request.course.id'}) {
1.232     www      8125: 
1.1172.2.115  raeburn  8126: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8127: 
                   8128:         if ($priv eq 'mip') {
                   8129:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8130:                 return $thisallowed;
                   8131:             } else {
                   8132:                 return '';
                   8133:             }
                   8134:         }
                   8135: 
1.620     albertel 8136:        $courseprivid=$env{'request.course.id'};
                   8137:        if ($env{'request.course.sec'}) {
                   8138:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8139:        }
                   8140:        $courseprivid=~s/\_/\//;
                   8141:        my $checkreferer=1;
1.232     www      8142:        my ($match,$cond)=&is_on_map($uri);
                   8143:        if ($match) {
                   8144:            $statecond=$cond;
1.620     albertel 8145:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8146:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8147:                my $value = $1;
                   8148:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  8149:                    if ($noblockcheck) {
1.1162    raeburn  8150:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8151:                    } else {
                   8152:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   8153:                        if (@blockers > 0) {
                   8154:                            $thisallowed = 'B';
                   8155:                        } else {
                   8156:                            $thisallowed.=$value;
                   8157:                        }
1.1162    raeburn  8158:                    }
                   8159:                } else {
                   8160:                    $thisallowed.=$value;
                   8161:                }
1.52      www      8162:                $checkreferer=0;
                   8163:            }
1.29      www      8164:        }
1.83      www      8165:        
1.148     www      8166:        if ($checkreferer) {
1.620     albertel 8167: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8168:             unless ($refuri) {
1.800     albertel 8169:                 foreach my $key (keys(%env)) {
                   8170: 		    if ($key=~/^httpref\..*\*/) {
                   8171: 			my $pattern=$key;
1.156     www      8172:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8173:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8174:                         $pattern=~s/\//\\\//g;
1.152     www      8175:                         if ($orguri=~/$pattern/) {
1.800     albertel 8176: 			    $refuri=$env{$key};
1.148     www      8177:                         }
                   8178:                     }
1.191     harris41 8179:                 }
1.148     www      8180:             }
1.232     www      8181: 
1.148     www      8182:          if ($refuri) { 
1.152     www      8183: 	  $refuri=&declutter($refuri);
1.232     www      8184:           my ($match,$cond)=&is_on_map($refuri);
                   8185:             if ($match) {
                   8186:               my $refstatecond=$cond;
1.620     albertel 8187:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8188:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8189:                   my $value = $1;
                   8190:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  8191:                       if ($noblockcheck) {
1.1162    raeburn  8192:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8193:                       } else {
                   8194:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   8195:                           if (@blockers > 0) {
                   8196:                               $thisallowed = 'B';
                   8197:                           } else {
                   8198:                               $thisallowed.=$value;
                   8199:                           }
1.1162    raeburn  8200:                       }
                   8201:                   } else {
                   8202:                       $thisallowed.=$value;
                   8203:                   }
1.53      www      8204:                   $uri=$refuri;
                   8205:                   $statecond=$refstatecond;
1.52      www      8206:               }
                   8207:           }
1.148     www      8208:         }
1.29      www      8209:        }
1.52      www      8210:    }
1.29      www      8211: 
1.52      www      8212: #
1.103     harris41 8213: # Gathered now: all privileges that could apply, and condition number
1.52      www      8214: # 
                   8215: #
                   8216: # Full or no access?
                   8217: #
1.29      www      8218: 
1.52      www      8219:     if ($thisallowed=~/F/) {
                   8220: 	return 'F';
                   8221:     }
1.29      www      8222: 
1.52      www      8223:     unless ($thisallowed) {
                   8224:         return '';
                   8225:     }
1.29      www      8226: 
1.52      www      8227: # Restrictions exist, deal with them
                   8228: #
                   8229: #   C:according to course preferences
                   8230: #   R:according to resource settings
                   8231: #   L:unless locked
                   8232: #   X:according to user session state
                   8233: #
                   8234: 
                   8235: # Possibly locked functionality, check all courses
1.54      www      8236: # Locks might take effect only after 10 minutes cache expiration for other
                   8237: # courses, and 2 minutes for current course
1.52      www      8238: 
                   8239:     my $envkey;
                   8240:     if ($thisallowed=~/L/) {
1.1000    raeburn  8241:         foreach $envkey (keys(%env)) {
1.54      www      8242:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8243:                my $courseid=$2;
                   8244:                my $roleid=$1.'.'.$2;
1.92      www      8245:                $courseid=~s/^\///;
1.54      www      8246:                my $expiretime=600;
1.620     albertel 8247:                if ($env{'request.role'} eq $roleid) {
1.54      www      8248: 		  $expiretime=120;
                   8249:                }
                   8250: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8251:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8252:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8253: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8254:                }
1.620     albertel 8255:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8256:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8257: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8258:                        &log($env{'user.domain'},$env{'user.name'},
                   8259:                             $env{'user.home'},
1.57      www      8260:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8261:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8262:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8263: 		       return '';
                   8264:                    }
                   8265:                }
1.620     albertel 8266:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8267:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   8268: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   8269:                        &log($env{'user.domain'},$env{'user.name'},
                   8270:                             $env{'user.home'},
1.57      www      8271:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8272:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8273:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8274: 		       return '';
                   8275:                    }
                   8276:                }
                   8277: 	   }
1.29      www      8278:        }
1.52      www      8279:     }
                   8280:    
                   8281: #
                   8282: # Rest of the restrictions depend on selected course
                   8283: #
                   8284: 
1.620     albertel 8285:     unless ($env{'request.course.id'}) {
1.766     albertel 8286: 	if ($thisallowed eq 'A') {
                   8287: 	    return 'A';
1.814     raeburn  8288:         } elsif ($thisallowed eq 'B') {
                   8289:             return 'B';
1.766     albertel 8290: 	} else {
                   8291: 	    return '1';
                   8292: 	}
1.52      www      8293:     }
1.29      www      8294: 
1.52      www      8295: #
                   8296: # Now user is definitely in a course
                   8297: #
1.53      www      8298: 
                   8299: 
                   8300: # Course preferences
                   8301: 
                   8302:    if ($thisallowed=~/C/) {
1.620     albertel 8303:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8304:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8305:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8306: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8307: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8308: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8309: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8310: 			$env{'request.course.id'});
                   8311: 	   }
1.237     www      8312:            return '';
                   8313:        }
                   8314: 
1.620     albertel 8315:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8316: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8317: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8318: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8319: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8320: 			$env{'request.course.id'});
                   8321: 	   }
1.54      www      8322:            return '';
                   8323:        }
1.53      www      8324:    }
                   8325: 
                   8326: # Resource preferences
                   8327: 
                   8328:    if ($thisallowed=~/R/) {
1.620     albertel 8329:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8330:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8331: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8332: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8333: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8334: 	   }
                   8335: 	   return '';
1.54      www      8336:        }
1.53      www      8337:    }
1.30      www      8338: 
1.246     www      8339: # Restricted by state or randomout?
1.30      www      8340: 
1.52      www      8341:    if ($thisallowed=~/X/) {
1.620     albertel 8342:       if ($env{'acc.randomout'}) {
1.579     albertel 8343: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8344:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8345:             return ''; 
                   8346:          }
1.247     www      8347:       }
                   8348:       if (&condval($statecond)) {
1.52      www      8349: 	 return '2';
                   8350:       } else {
                   8351:          return '';
                   8352:       }
                   8353:    }
1.30      www      8354: 
1.766     albertel 8355:     if ($thisallowed eq 'A') {
                   8356: 	return 'A';
1.814     raeburn  8357:     } elsif ($thisallowed eq 'B') {
                   8358:         return 'B';
1.766     albertel 8359:     }
1.52      www      8360:    return 'F';
1.232     www      8361: }
1.1162    raeburn  8362: 
1.1172.2.13  raeburn  8363: # ------------------------------------------- Check construction space access
                   8364: 
                   8365: sub constructaccess {
                   8366:     my ($url,$setpriv)=@_;
                   8367: 
                   8368: # We do not allow editing of previous versions of files
                   8369:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8370: 
                   8371: # Get username and domain from URL
                   8372:     my ($ownername,$ownerdomain,$ownerhome);
                   8373: 
                   8374:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8375:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8376: 
                   8377: # The URL does not really point to any authorspace, forget it
                   8378:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8379: 
                   8380: # Now we need to see if the user has access to the authorspace of
                   8381: # $ownername at $ownerdomain
                   8382: 
                   8383:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8384: # Real author for this?
                   8385:        $ownerhome = $env{'user.home'};
                   8386:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8387:           return ($ownername,$ownerdomain,$ownerhome);
                   8388:        }
                   8389:     } else {
                   8390: # Co-author for this?
                   8391:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8392:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8393:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8394:             return ($ownername,$ownerdomain,$ownerhome);
                   8395:         }
                   8396:     }
                   8397: 
                   8398: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8399: # we might as well leave
                   8400:    unless ($setpriv) { return ''; }
                   8401: 
                   8402: # Backdoor access?
                   8403:     my $allowed=&allowed('eco',$ownerdomain);
                   8404: # Nope
                   8405:     unless ($allowed) { return ''; }
                   8406: # Looks like we may have access, but could be locked by the owner of the construction space
                   8407:     if ($allowed eq 'U') {
                   8408:         my %blocked=&get('environment',['domcoord.author'],
                   8409:                          $ownerdomain,$ownername);
                   8410: # Is blocked by owner
                   8411:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8412:     }
                   8413:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8414: # Grant temporary access
                   8415:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8416:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8417:         if (!$update) { $update = $then; }
                   8418:         my $refresh=$env{'user.refresh.time'};
                   8419:         if (!$refresh) { $refresh = $update; }
                   8420:         my $now = time;
                   8421:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8422:                            $now,'ca','constructaccess');
                   8423:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8424:         return($ownername,$ownerdomain,$ownerhome);
                   8425:     }
                   8426: # No business here
                   8427:     return '';
                   8428: }
                   8429: 
1.1172.2.66  raeburn  8430: # ----------------------------------------------------------- Content Blocking
                   8431: 
                   8432: {
                   8433: # Caches for faster Course Contents display where content blocking
                   8434: # is in operation (i.e., interval param set) for timed quiz.
                   8435: #
                   8436: # User for whom data are being temporarily cached.
                   8437: my $cacheduser='';
                   8438: # Cached blockers for this user (a hash of blocking items).
                   8439: my %cachedblockers=();
                   8440: # When the data were last cached.
                   8441: my $cachedlast='';
                   8442: 
                   8443: sub load_all_blockers {
                   8444:     my ($uname,$udom,$blocks)=@_;
                   8445:     if (($uname ne '') && ($udom ne '')) {
                   8446:         if (($cacheduser eq $uname.':'.$udom) &&
                   8447:             (abs($cachedlast-time)<5)) {
                   8448:             return;
                   8449:         }
                   8450:     }
                   8451:     $cachedlast=time;
                   8452:     $cacheduser=$uname.':'.$udom;
                   8453:     %cachedblockers = &get_commblock_resources($blocks);
                   8454: }
                   8455: 
1.1162    raeburn  8456: sub get_comm_blocks {
                   8457:     my ($cdom,$cnum) = @_;
                   8458:     if ($cdom eq '' || $cnum eq '') {
                   8459:         return unless ($env{'request.course.id'});
                   8460:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8461:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8462:     }
                   8463:     my %commblocks;
                   8464:     my $hashid=$cdom.'_'.$cnum;
                   8465:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8466:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8467:         %commblocks = %{$blocksref};
                   8468:     } else {
                   8469:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8470:         my $cachetime = 600;
                   8471:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8472:     }
                   8473:     return %commblocks;
                   8474: }
                   8475: 
1.1172.2.66  raeburn  8476: sub get_commblock_resources {
                   8477:     my ($blocks) = @_;
                   8478:     my %blockers = ();
                   8479:     return %blockers unless ($env{'request.course.id'});
                   8480:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8481:     my %commblocks;
                   8482:     if (ref($blocks) eq 'HASH') {
                   8483:         %commblocks = %{$blocks};
                   8484:     } else {
                   8485:         %commblocks = &get_comm_blocks();
                   8486:     }
1.1172.2.66  raeburn  8487:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8488:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8489:     return %blockers unless (ref($navmap));
                   8490:     my $now = time;
1.1162    raeburn  8491:     foreach my $block (keys(%commblocks)) {
                   8492:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8493:             my ($start,$end) = ($1,$2);
                   8494:             if ($start <= $now && $end >= $now) {
                   8495:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8496:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8497:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8498:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8499:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8500:                             }
                   8501:                         }
                   8502:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8503:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8504:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8505:                             }
                   8506:                         }
                   8507:                     }
                   8508:                 }
                   8509:             }
                   8510:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8511:             my $item = $1;
1.1163    raeburn  8512:             my @to_test;
1.1162    raeburn  8513:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8514:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  8515:                     my @interval;
                   8516:                     my $type = 'map';
                   8517:                     if ($item eq 'course') {
                   8518:                         $type = 'course';
                   8519:                         @interval=&EXT("resource.0.interval");
                   8520:                     } else {
                   8521:                         if ($item =~ /___\d+___/) {
                   8522:                             $type = 'resource';
                   8523:                             @interval=&EXT("resource.0.interval",$item);
                   8524:                             if (ref($navmap)) {
                   8525:                                 my $res = $navmap->getBySymb($item);
                   8526:                                 push(@to_test,$res);
                   8527:                             }
1.1162    raeburn  8528:                         } else {
1.1172.2.66  raeburn  8529:                             my $mapsymb = &symbread($item,1);
                   8530:                             if ($mapsymb) {
                   8531:                                 if (ref($navmap)) {
                   8532:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8533:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8534:                                     foreach my $res (@to_test) {
                   8535:                                         my $symb = $res->symb();
                   8536:                                         next if ($symb eq $mapsymb);
                   8537:                                         if ($symb ne '') {
                   8538:                                             @interval=&EXT("resource.0.interval",$symb);
                   8539:                                             if ($interval[1] eq 'map') {
                   8540:                                                 last;
1.1162    raeburn  8541:                                             }
                   8542:                                         }
                   8543:                                     }
                   8544:                                 }
                   8545:                             }
                   8546:                         }
1.1172.2.66  raeburn  8547:                     }
1.1172.2.118.  .1(raebu 8548:20):                     if ($interval[0] =~ /^(\d+)/) {
                   8549:20):                         my $timelimit = $1; 
1.1172.2.66  raeburn  8550:                         my $first_access;
                   8551:                         if ($type eq 'resource') {
                   8552:                             $first_access=&get_first_access($interval[1],$item);
                   8553:                         } elsif ($type eq 'map') {
                   8554:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8555:                         } else {
                   8556:                             $first_access=&get_first_access($interval[1]);
                   8557:                         }
                   8558:                         if ($first_access) {
1.1172.2.118.  .1(raebu 8559:20):                             my $timesup = $first_access+$timelimit;
1.1172.2.66  raeburn  8560:                             if ($timesup > $now) {
                   8561:                                 my $activeblock;
                   8562:                                 foreach my $res (@to_test) {
                   8563:                                     if ($res->answerable()) {
                   8564:                                         $activeblock = 1;
                   8565:                                         last;
                   8566:                                     }
                   8567:                                 }
                   8568:                                 if ($activeblock) {
                   8569:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8570:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8571:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8572:                                          }
                   8573:                                     }
                   8574:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8575:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8576:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8577:                                         }
1.1162    raeburn  8578:                                     }
                   8579:                                 }
                   8580:                             }
                   8581:                         }
                   8582:                     }
                   8583:                 }
                   8584:             }
                   8585:         }
                   8586:     }
1.1172.2.66  raeburn  8587:     return %blockers;
1.1162    raeburn  8588: }
                   8589: 
1.1172.2.66  raeburn  8590: sub has_comm_blocking {
                   8591:     my ($priv,$symb,$uri,$blocks) = @_;
                   8592:     my @blockers;
                   8593:     return unless ($env{'request.course.id'});
                   8594:     return unless ($priv eq 'bre');
                   8595:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8596:     return if ($env{'request.state'} eq 'construct');
                   8597:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8598:     return unless (keys(%cachedblockers) > 0);
                   8599:     my (%possibles,@symbs);
                   8600:     if (!$symb) {
                   8601:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8602:     }
1.1172.2.66  raeburn  8603:     if ($symb) {
                   8604:         @symbs = ($symb);
                   8605:     } elsif (keys(%possibles)) {
                   8606:         @symbs = keys(%possibles);
                   8607:     }
                   8608:     my $noblock;
                   8609:     foreach my $symb (@symbs) {
                   8610:         last if ($noblock);
                   8611:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8612:         foreach my $block (keys(%cachedblockers)) {
                   8613:             if ($block =~ /^firstaccess____(.+)$/) {
                   8614:                 my $item = $1;
                   8615:                 if (($item eq $map) || ($item eq $symb)) {
                   8616:                     $noblock = 1;
                   8617:                     last;
                   8618:                 }
1.1162    raeburn  8619:             }
1.1172.2.66  raeburn  8620:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8621:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8622:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8623:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8624:                             push(@blockers,$block);
                   8625:                         }
                   8626:                     }
                   8627:                 }
                   8628:             }
                   8629:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8630:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8631:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8632:                         push(@blockers,$block);
                   8633:                     }
                   8634:                 }
1.1162    raeburn  8635:             }
                   8636:         }
                   8637:     }
1.1172.2.66  raeburn  8638:     return if ($noblock);
                   8639:     return @blockers;
                   8640: }
1.1162    raeburn  8641: }
                   8642: 
1.1172.2.66  raeburn  8643: # -------------------------------- Deversion and split uri into path an filename
                   8644: 
1.1133    foxr     8645: #
1.1172.2.66  raeburn  8646: #   Removes the version from a URI and
1.1133    foxr     8647: #   splits it in to its filename and path to the filename.
                   8648: #   Seems like File::Basename could have done this more clearly.
                   8649: #   Parameters:
                   8650: #      $uri   - input URI
                   8651: #   Returns:
                   8652: #     Two element list consisting of 
                   8653: #     $pathname  - the URI up to and excluding the trailing /
                   8654: #     $filename  - The part of the URI following the last /
                   8655: #  NOTE:
                   8656: #    Another realization of this is simply:
                   8657: #    use File::Basename;
                   8658: #    ...
                   8659: #    $uri = shift;
                   8660: #    $filename = basename($uri);
                   8661: #    $path     = dirname($uri);
                   8662: #    return ($filename, $path);
                   8663: #
                   8664: #     The implementation below is probably faster however.
                   8665: #
1.710     albertel 8666: sub split_uri_for_cond {
                   8667:     my $uri=&deversion(&declutter(shift));
                   8668:     my @uriparts=split(/\//,$uri);
                   8669:     my $filename=pop(@uriparts);
                   8670:     my $pathname=join('/',@uriparts);
                   8671:     return ($pathname,$filename);
                   8672: }
1.232     www      8673: # --------------------------------------------------- Is a resource on the map?
                   8674: 
                   8675: sub is_on_map {
1.710     albertel 8676:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8677:     #Trying to find the conditional for the file
1.620     albertel 8678:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8679: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8680:     if ($match) {
1.289     bowersj2 8681: 	return (1,$1);
                   8682:     } else {
1.434     www      8683: 	return (0,0);
1.289     bowersj2 8684:     }
1.12      www      8685: }
                   8686: 
1.427     www      8687: # --------------------------------------------------------- Get symb from alias
                   8688: 
                   8689: sub get_symb_from_alias {
                   8690:     my $symb=shift;
                   8691:     my ($map,$resid,$url)=&decode_symb($symb);
                   8692: # Already is a symb
                   8693:     if ($url) { return $symb; }
                   8694: # Must be an alias
                   8695:     my $aliassymb='';
                   8696:     my %bighash;
1.620     albertel 8697:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8698:                             &GDBM_READER(),0640)) {
                   8699:         my $rid=$bighash{'mapalias_'.$symb};
                   8700: 	if ($rid) {
                   8701: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8702: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8703: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8704: 	}
                   8705:         untie %bighash;
                   8706:     }
                   8707:     return $aliassymb;
                   8708: }
                   8709: 
1.12      www      8710: # ----------------------------------------------------------------- Define Role
                   8711: 
                   8712: sub definerole {
                   8713:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8714:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8715:     foreach my $role (split(':',$sysrole)) {
                   8716: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8717:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8718:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8719: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8720:                return "refused:s:$crole&$cqual"; 
                   8721:             }
                   8722:         }
1.191     harris41 8723:     }
1.800     albertel 8724:     foreach my $role (split(':',$domrole)) {
                   8725: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8726:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8727:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8728: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8729:                return "refused:d:$crole&$cqual"; 
                   8730:             }
                   8731:         }
1.191     harris41 8732:     }
1.800     albertel 8733:     foreach my $role (split(':',$courole)) {
                   8734: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8735:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8736:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8737: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8738:                return "refused:c:$crole&$cqual"; 
                   8739:             }
                   8740:         }
1.191     harris41 8741:     }
1.1172.2.84  raeburn  8742:     my $uhome;
                   8743:     if (($uname ne '') && ($udom ne '')) {
                   8744:         $uhome = &homeserver($uname,$udom);
                   8745:         return $uhome if ($uhome eq 'no_host');
                   8746:     } else {
                   8747:         $uname = $env{'user.name'};
                   8748:         $udom = $env{'user.domain'};
                   8749:         $uhome = $env{'user.home'};
                   8750:     }
1.620     albertel 8751:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8752:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8753:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8754:     return reply($command,$uhome);
1.12      www      8755:   } else {
                   8756:     return 'refused';
                   8757:   }
1.105     harris41 8758: }
                   8759: 
                   8760: # ---------------- Make a metadata query against the network of library servers
                   8761: 
                   8762: sub metadata_query {
1.1172.2.33  raeburn  8763:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8764:     my %rhash;
1.845     albertel 8765:     my %libserv = &all_library();
1.244     matthew  8766:     my @server_list = (defined($server_array) ? @$server_array
                   8767:                                               : keys(%libserv) );
                   8768:     for my $server (@server_list) {
1.1172.2.33  raeburn  8769:         my $domains = '';
                   8770:         if (ref($domains_hash) eq 'HASH') {
                   8771:             $domains = $domains_hash->{$server};    
                   8772:         }
1.118     harris41 8773: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8774: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8775: 	    $rhash{$server}=$reply;
                   8776: 	}
                   8777: 	else {
                   8778: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8779: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8780: 			     $server);
                   8781: 	    $rhash{$server}=$reply;
                   8782: 	}
1.112     harris41 8783:     }
1.118     harris41 8784:     return \%rhash;
1.240     www      8785: }
                   8786: 
                   8787: # ----------------------------------------- Send log queries and wait for reply
                   8788: 
                   8789: sub log_query {
                   8790:     my ($uname,$udom,$query,%filters)=@_;
                   8791:     my $uhome=&homeserver($uname,$udom);
                   8792:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8793:     my $uhost=&hostname($uhome);
1.800     albertel 8794:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8795:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8796:                        $uhome);
1.479     albertel 8797:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8798:     return get_query_reply($queryid);
                   8799: }
                   8800: 
1.818     raeburn  8801: # -------------------------- Update MySQL table for portfolio file
                   8802: 
                   8803: sub update_portfolio_table {
1.821     raeburn  8804:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8805:     if ($group ne '') {
                   8806:         $file_name =~s /^\Q$group\E//;
                   8807:     }
1.818     raeburn  8808:     my $homeserver = &homeserver($uname,$udom);
                   8809:     my $queryid=
1.821     raeburn  8810:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8811:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8812:     my $reply = &get_query_reply($queryid);
                   8813:     return $reply;
                   8814: }
                   8815: 
1.899     raeburn  8816: # -------------------------- Update MySQL allusers table
                   8817: 
                   8818: sub update_allusers_table {
                   8819:     my ($uname,$udom,$names) = @_;
                   8820:     my $homeserver = &homeserver($uname,$udom);
                   8821:     my $queryid=
                   8822:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8823:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8824:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8825:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8826:                'generation='.&escape($names->{'generation'}).'%%'.
                   8827:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8828:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8829:     return;
1.899     raeburn  8830: }
                   8831: 
1.508     raeburn  8832: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8833: 
                   8834: sub fetch_enrollment_query {
1.511     raeburn  8835:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8836:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8837:     my $maxtries = 1;
1.508     raeburn  8838:     if ($context eq 'automated') {
                   8839:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8840:         $sleep = 2;
                   8841:         $loopmax = 100;
1.547     raeburn  8842:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8843:     } else {
                   8844:         $homeserver = &homeserver($cnum,$dom);
                   8845:     }
1.838     albertel 8846:     my $host=&hostname($homeserver);
1.506     raeburn  8847:     my $cmd = '';
1.1000    raeburn  8848:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8849:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8850:     }
                   8851:     $cmd =~ s/%%$//;
                   8852:     $cmd = &escape($cmd);
                   8853:     my $query = 'fetchenrollment';
1.620     albertel 8854:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8855:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8856:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8857:         return 'error: '.$queryid;
                   8858:     }
1.1172.2.93  raeburn  8859:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8860:     my $tries = 1;
                   8861:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8862:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8863:         $tries ++;
                   8864:     }
1.526     raeburn  8865:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8866:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8867:     } else {
1.901     albertel 8868:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8869:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8870:             foreach my $line (@responses) {
                   8871:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8872:                 $$replyref{$key} = $value;
                   8873:             }
                   8874:         } else {
1.1117    foxr     8875:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8876:             foreach my $line (@responses) {
                   8877:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8878:                 $$replyref{$key} = $value;
                   8879:                 if ($value > 0) {
1.800     albertel 8880:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8881:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8882:                         my $destname = $pathname.'/'.$filename;
                   8883:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8884:                         if ($xml_classlist =~ /^error/) {
                   8885:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8886:                         } else {
1.1172.2.96  raeburn  8887:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8888:                                 print FILE &unescape($xml_classlist);
                   8889:                                 close(FILE);
1.526     raeburn  8890:                             } else {
                   8891:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8892:                             }
                   8893:                         }
                   8894:                     }
                   8895:                 }
                   8896:             }
                   8897:         }
                   8898:         return 'ok';
                   8899:     }
                   8900:     return 'error';
                   8901: }
                   8902: 
1.242     www      8903: sub get_query_reply {
1.1172.2.79  raeburn  8904:     my ($queryid,$sleep,$loopmax) = @_;
                   8905:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8906:         $sleep = 0.2;
                   8907:     }
                   8908:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8909:         $loopmax = 100;
                   8910:     }
1.1117    foxr     8911:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8912:     my $reply='';
1.1172.2.79  raeburn  8913:     for (1..$loopmax) {
                   8914: 	sleep($sleep);
1.240     www      8915:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  8916: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8917: 		$reply = join('',<$fh>);
                   8918: 		close($fh);
1.240     www      8919: 	   } else { return 'error: reply_file_error'; }
1.242     www      8920:            return &unescape($reply);
                   8921: 	}
1.240     www      8922:     }
1.242     www      8923:     return 'timeout:'.$queryid;
1.240     www      8924: }
                   8925: 
                   8926: sub courselog_query {
1.241     www      8927: #
                   8928: # possible filters:
                   8929: # url: url or symb
                   8930: # username
                   8931: # domain
                   8932: # action: view, submit, grade
                   8933: # start: timestamp
                   8934: # end: timestamp
                   8935: #
1.240     www      8936:     my (%filters)=@_;
1.620     albertel 8937:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8938:     if ($filters{'url'}) {
                   8939: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8940:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8941:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8942:     }
1.620     albertel 8943:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8944:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8945:     return &log_query($cname,$cdom,'courselog',%filters);
                   8946: }
                   8947: 
                   8948: sub userlog_query {
1.858     raeburn  8949: #
                   8950: # possible filters:
                   8951: # action: log check role
                   8952: # start: timestamp
                   8953: # end: timestamp
                   8954: #
1.240     www      8955:     my ($uname,$udom,%filters)=@_;
                   8956:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8957: }
                   8958: 
1.506     raeburn  8959: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8960: 
                   8961: sub auto_run {
1.508     raeburn  8962:     my ($cnum,$cdom) = @_;
1.876     raeburn  8963:     my $response = 0;
                   8964:     my $settings;
                   8965:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8966:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8967:         $settings = $domconfig{'autoenroll'};
                   8968:         if ($settings->{'run'} eq '1') {
                   8969:             $response = 1;
                   8970:         }
                   8971:     } else {
1.934     raeburn  8972:         my $homeserver;
                   8973:         if (&is_course($cdom,$cnum)) {
                   8974:             $homeserver = &homeserver($cnum,$cdom);
                   8975:         } else {
                   8976:             $homeserver = &domain($cdom,'primary');
                   8977:         }
                   8978:         if ($homeserver ne 'no_host') {
                   8979:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8980:         }
1.876     raeburn  8981:     }
1.506     raeburn  8982:     return $response;
                   8983: }
1.776     albertel 8984: 
1.506     raeburn  8985: sub auto_get_sections {
1.508     raeburn  8986:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8987:     my $homeserver;
                   8988:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8989:         $homeserver = &homeserver($cnum,$cdom);
                   8990:     }
                   8991:     if (!defined($homeserver)) { 
                   8992:         if ($cdom =~ /^$match_domain$/) {
                   8993:             $homeserver = &domain($cdom,'primary');
                   8994:         }
                   8995:     }
                   8996:     my @secs;
                   8997:     if (defined($homeserver)) {
                   8998:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8999:         unless ($response eq 'refused') {
                   9000:             @secs = split(/:/,$response);
                   9001:         }
1.506     raeburn  9002:     }
                   9003:     return @secs;
                   9004: }
1.776     albertel 9005: 
1.506     raeburn  9006: sub auto_new_course {
1.1099    raeburn  9007:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9008:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9009:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9010:     return $response;
                   9011: }
1.776     albertel 9012: 
1.506     raeburn  9013: sub auto_validate_courseID {
1.508     raeburn  9014:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9015:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9016:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9017:     return $response;
                   9018: }
1.776     albertel 9019: 
1.1007    raeburn  9020: sub auto_validate_instcode {
1.1020    raeburn  9021:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9022:     my ($homeserver,$response);
                   9023:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9024:         $homeserver = &homeserver($cnum,$cdom);
                   9025:     }
                   9026:     if (!defined($homeserver)) {
                   9027:         if ($cdom =~ /^$match_domain$/) {
                   9028:             $homeserver = &domain($cdom,'primary');
                   9029:         }
                   9030:     }
1.1065    raeburn  9031:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9032:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  9033:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9034:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9035: }
                   9036: 
1.506     raeburn  9037: sub auto_create_password {
1.873     raeburn  9038:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9039:     my ($homeserver,$response);
1.506     raeburn  9040:     my $create_passwd = 0;
                   9041:     my $authchk = '';
1.873     raeburn  9042:     if ($udom =~ /^$match_domain$/) {
                   9043:         $homeserver = &domain($udom,'primary');
                   9044:     }
                   9045:     if ($homeserver eq '') {
                   9046:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9047:             $homeserver = &homeserver($cnum,$cdom);
                   9048:         }
                   9049:     }
                   9050:     if ($homeserver eq '') {
                   9051:         $authchk = 'nodomain';
1.506     raeburn  9052:     } else {
1.873     raeburn  9053:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9054:         if ($response eq 'refused') {
                   9055:             $authchk = 'refused';
                   9056:         } else {
1.901     albertel 9057:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9058:         }
1.506     raeburn  9059:     }
                   9060:     return ($authparam,$create_passwd,$authchk);
                   9061: }
                   9062: 
1.706     raeburn  9063: sub auto_photo_permission {
                   9064:     my ($cnum,$cdom,$students) = @_;
                   9065:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9066:     my ($outcome,$perm_reqd,$conditions) = 
                   9067: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9068:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9069: 	return (undef,undef);
                   9070:     }
1.706     raeburn  9071:     return ($outcome,$perm_reqd,$conditions);
                   9072: }
                   9073: 
                   9074: sub auto_checkphotos {
                   9075:     my ($uname,$udom,$pid) = @_;
                   9076:     my $homeserver = &homeserver($uname,$udom);
                   9077:     my ($result,$resulttype);
                   9078:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9079: 				   &escape($uname).':'.&escape($pid),
                   9080: 				   $homeserver));
1.709     albertel 9081:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9082: 	return (undef,undef);
                   9083:     }
1.706     raeburn  9084:     if ($outcome) {
                   9085:         ($result,$resulttype) = split(/:/,$outcome);
                   9086:     } 
                   9087:     return ($result,$resulttype);
                   9088: }
                   9089: 
                   9090: sub auto_photochoice {
                   9091:     my ($cnum,$cdom) = @_;
                   9092:     my $homeserver = &homeserver($cnum,$cdom);
                   9093:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9094: 						       &escape($cdom),
                   9095: 						       $homeserver)));
1.709     albertel 9096:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9097: 	return (undef,undef);
                   9098:     }
1.706     raeburn  9099:     return ($update,$comment);
                   9100: }
                   9101: 
                   9102: sub auto_photoupdate {
                   9103:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9104:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9105:     my $host=&hostname($homeserver);
1.706     raeburn  9106:     my $cmd = '';
                   9107:     my $maxtries = 1;
1.800     albertel 9108:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9109:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9110:     }
                   9111:     $cmd =~ s/%%$//;
                   9112:     $cmd = &escape($cmd);
                   9113:     my $query = 'institutionalphotos';
                   9114:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9115:     unless ($queryid=~/^\Q$host\E\_/) {
                   9116:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9117:         return 'error: '.$queryid;
                   9118:     }
                   9119:     my $reply = &get_query_reply($queryid);
                   9120:     my $tries = 1;
                   9121:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9122:         $reply = &get_query_reply($queryid);
                   9123:         $tries ++;
                   9124:     }
                   9125:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9126:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9127:     } else {
                   9128:         my @responses = split(/:/,$reply);
                   9129:         my $outcome = shift(@responses); 
                   9130:         foreach my $item (@responses) {
                   9131:             my ($key,$value) = split(/=/,$item);
                   9132:             $$photo{$key} = $value;
                   9133:         }
                   9134:         return $outcome;
                   9135:     }
                   9136:     return 'error';
                   9137: }
                   9138: 
1.521     raeburn  9139: sub auto_instcode_format {
1.793     albertel 9140:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9141: 	$cat_order) = @_;
1.521     raeburn  9142:     my $courses = '';
1.772     raeburn  9143:     my @homeservers;
1.521     raeburn  9144:     if ($caller eq 'global') {
1.841     albertel 9145: 	my %servers = &get_servers($codedom,'library');
                   9146: 	foreach my $tryserver (keys(%servers)) {
                   9147: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9148: 		push(@homeservers,$tryserver);
                   9149: 	    }
1.584     raeburn  9150:         }
1.1022    raeburn  9151:     } elsif ($caller eq 'requests') {
                   9152:         if ($codedom =~ /^$match_domain$/) {
                   9153:             my $chome = &domain($codedom,'primary');
                   9154:             unless ($chome eq 'no_host') {
                   9155:                 push(@homeservers,$chome);
                   9156:             }
                   9157:         }
1.521     raeburn  9158:     } else {
1.772     raeburn  9159:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9160:     }
1.793     albertel 9161:     foreach my $code (keys(%{$instcodes})) {
                   9162:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9163:     }
                   9164:     chop($courses);
1.772     raeburn  9165:     my $ok_response = 0;
                   9166:     my $response;
                   9167:     while (@homeservers > 0 && $ok_response == 0) {
                   9168:         my $server = shift(@homeservers); 
                   9169:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9170:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9171:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9172: 		split(/:/,$response);
1.772     raeburn  9173:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9174:             push(@{$codetitles},&str2array($codetitles_str));
                   9175:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9176:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9177:             $ok_response = 1;
                   9178:         }
                   9179:     }
                   9180:     if ($ok_response) {
1.521     raeburn  9181:         return 'ok';
1.772     raeburn  9182:     } else {
                   9183:         return $response;
1.521     raeburn  9184:     }
                   9185: }
                   9186: 
1.792     raeburn  9187: sub auto_instcode_defaults {
                   9188:     my ($domain,$returnhash,$code_order) = @_;
                   9189:     my @homeservers;
1.841     albertel 9190: 
                   9191:     my %servers = &get_servers($domain,'library');
                   9192:     foreach my $tryserver (keys(%servers)) {
                   9193: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9194: 	    push(@homeservers,$tryserver);
                   9195: 	}
1.792     raeburn  9196:     }
1.841     albertel 9197: 
1.792     raeburn  9198:     my $response;
1.841     albertel 9199:     foreach my $server (@homeservers) {
1.792     raeburn  9200:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9201:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9202: 	
                   9203: 	foreach my $pair (split(/\&/,$response)) {
                   9204: 	    my ($name,$value)=split(/\=/,$pair);
                   9205: 	    if ($name eq 'code_order') {
                   9206: 		@{$code_order} = split(/\&/,&unescape($value));
                   9207: 	    } else {
                   9208: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9209: 	    }
                   9210: 	}
                   9211: 	return 'ok';
1.792     raeburn  9212:     }
1.841     albertel 9213: 
                   9214:     return $response;
1.1003    raeburn  9215: }
                   9216: 
                   9217: sub auto_possible_instcodes {
1.1007    raeburn  9218:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9219:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9220:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9221:         return;
                   9222:     }
1.1003    raeburn  9223:     my (@homeservers,$uhome);
                   9224:     if (defined(&domain($domain,'primary'))) {
                   9225:         $uhome=&domain($domain,'primary');
                   9226:         push(@homeservers,&domain($domain,'primary'));
                   9227:     } else {
                   9228:         my %servers = &get_servers($domain,'library');
                   9229:         foreach my $tryserver (keys(%servers)) {
                   9230:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9231:                 push(@homeservers,$tryserver);
                   9232:             }
                   9233:         }
                   9234:     }
                   9235:     my $response;
                   9236:     foreach my $server (@homeservers) {
                   9237:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9238:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9239:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9240:             split(':',$response);
                   9241:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9242:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9243:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9244:             my ($name,$value)=split('=',$item);
                   9245:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9246:         }
                   9247:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9248:             my ($name,$value)=split('=',$item);
                   9249:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9250:         }
                   9251:         return 'ok';
                   9252:     }
                   9253:     return $response;
                   9254: }
1.792     raeburn  9255: 
1.1010    raeburn  9256: sub auto_courserequest_checks {
                   9257:     my ($dom) = @_;
1.1020    raeburn  9258:     my ($homeserver,%validations);
                   9259:     if ($dom =~ /^$match_domain$/) {
                   9260:         $homeserver = &domain($dom,'primary');
                   9261:     }
                   9262:     unless ($homeserver eq 'no_host') {
                   9263:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9264:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9265:             my @items = split(/&/,$response);
                   9266:             foreach my $item (@items) {
                   9267:                 my ($key,$value) = split('=',$item);
                   9268:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9269:             }
                   9270:         }
                   9271:     }
1.1010    raeburn  9272:     return %validations; 
                   9273: }
                   9274: 
1.1020    raeburn  9275: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9276:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9277:     my ($homeserver,$response);
                   9278:     if ($dom =~ /^$match_domain$/) {
                   9279:         $homeserver = &domain($dom,'primary');
                   9280:     }
1.1172.2.43  raeburn  9281:     unless ($homeserver eq 'no_host') {
                   9282:         my $customdata;
                   9283:         if (ref($custominfo) eq 'HASH') {
                   9284:             $customdata = &freeze_escape($custominfo);
                   9285:         }
1.1020    raeburn  9286:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9287:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9288:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9289:                                     $customdata,$homeserver));
1.1020    raeburn  9290:     }
                   9291:     return $response;
                   9292: }
                   9293: 
1.777     albertel 9294: sub auto_validate_class_sec {
1.918     raeburn  9295:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9296:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9297:     my $ownerlist;
                   9298:     if (ref($owners) eq 'ARRAY') {
                   9299:         $ownerlist = join(',',@{$owners});
                   9300:     } else {
                   9301:         $ownerlist = $owners;
                   9302:     }
1.773     raeburn  9303:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9304:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9305:     return $response;
                   9306: }
                   9307: 
1.1172.2.94  raeburn  9308: sub auto_validate_instclasses {
                   9309:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9310:     my ($homeserver,%validations);
                   9311:     $homeserver = &homeserver($cnum,$cdom);
                   9312:     unless ($homeserver eq 'no_host') {
                   9313:         my $ownerlist;
                   9314:         if (ref($owners) eq 'ARRAY') {
                   9315:             $ownerlist = join(',',@{$owners});
                   9316:         } else {
                   9317:             $ownerlist = $owners;
                   9318:         }
                   9319:         if (ref($classesref) eq 'HASH') {
                   9320:             my $classes = &freeze_escape($classesref);
                   9321:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9322:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9323:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9324:                 my @items = split(/&/,$response);
                   9325:                 foreach my $item (@items) {
                   9326:                     my ($key,$value) = split('=',$item);
                   9327:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9328:                 }
                   9329:             }
                   9330:         }
                   9331:     }
                   9332:     return %validations;
                   9333: }
                   9334: 
1.1172.2.38  raeburn  9335: sub auto_crsreq_update {
                   9336:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9337:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9338:     my ($homeserver,%crsreqresponse);
                   9339:     if ($cdom =~ /^$match_domain$/) {
                   9340:         $homeserver = &domain($cdom,'primary');
                   9341:     }
                   9342:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9343:         my $info;
                   9344:         if (ref($inbound) eq 'HASH') {
                   9345:             $info = &freeze_escape($inbound);
                   9346:         }
                   9347:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9348:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9349:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9350:                             &escape($title).':'.&escape($code).':'.
                   9351:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9352:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9353:             my @items = split(/&/,$response);
                   9354:             foreach my $item (@items) {
                   9355:                 my ($key,$value) = split('=',$item);
                   9356:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9357:             }
                   9358:         }
                   9359:     }
                   9360:     return \%crsreqresponse;
                   9361: }
                   9362: 
1.1172.2.78  raeburn  9363: sub auto_export_grades {
                   9364:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9365:     my ($homeserver,%exportresponse);
                   9366:     if ($cdom =~ /^$match_domain$/) {
                   9367:         $homeserver = &domain($cdom,'primary');
                   9368:     }
                   9369:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9370:         my $info;
                   9371:         if (ref($inforef) eq 'HASH') {
                   9372:             $info = &freeze_escape($inforef);
                   9373:         }
                   9374:         if (ref($gradesref) eq 'HASH') {
                   9375:             my $grades = &freeze_escape($gradesref);
                   9376:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9377:                                 $info.':'.$grades,$homeserver);
                   9378:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9379:                 my @items = split(/&/,$response);
                   9380:                 foreach my $item (@items) {
                   9381:                     my ($key,$value) = split('=',$item);
                   9382:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9383:                 }
                   9384:             }
                   9385:         }
                   9386:     }
                   9387:     return \%exportresponse;
                   9388: }
                   9389: 
1.1172.2.68  raeburn  9390: sub check_instcode_cloning {
                   9391:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9392:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9393:         return;
                   9394:     }
                   9395:     my $canclone;
                   9396:     if (@{$code_order} > 0) {
                   9397:         my $instcoderegexp ='^';
                   9398:         my @clonecodes = split(/\&/,$cloner);
                   9399:         foreach my $item (@{$code_order}) {
                   9400:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9401:                 foreach my $pair (@clonecodes) {
                   9402:                     my ($key,$val) = split(/\=/,$pair,2);
                   9403:                     $val = &unescape($val);
                   9404:                     if ($key eq $item) {
                   9405:                         $instcoderegexp .= '('.$val.')';
                   9406:                         last;
                   9407:                     }
                   9408:                 }
                   9409:             } else {
                   9410:                 $instcoderegexp .= $codedefaults->{$item};
                   9411:             }
                   9412:         }
                   9413:         $instcoderegexp .= '$';
                   9414:         my (@from,@to);
                   9415:         eval {
                   9416:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9417:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9418:         };
                   9419:         if ((@from > 0) && (@to > 0)) {
                   9420:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9421:             if (!@diffs) {
                   9422:                 $canclone = 1;
                   9423:             }
                   9424:         }
                   9425:     }
                   9426:     return $canclone;
                   9427: }
                   9428: 
                   9429: sub default_instcode_cloning {
                   9430:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9431:     my (%codedefaults,@code_order,$canclone);
                   9432:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9433:         %codedefaults = %{$codedefaultsref};
                   9434:         @code_order = @{$codeorderref};
                   9435:     } elsif ($clonedom) {
                   9436:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9437:     }
                   9438:     if (($domdefclone) && (@code_order)) {
                   9439:         my @clonecodes = split(/\+/,$domdefclone);
                   9440:         my $instcoderegexp ='^';
                   9441:         foreach my $item (@code_order) {
                   9442:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9443:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9444:             } else {
                   9445:                 $instcoderegexp .= $codedefaults{$item};
                   9446:             }
                   9447:         }
                   9448:         $instcoderegexp .= '$';
                   9449:         my (@from,@to);
                   9450:         eval {
                   9451:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9452:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9453:         };
                   9454:         if ((@from > 0) && (@to > 0)) {
                   9455:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9456:             if (!@diffs) {
                   9457:                 $canclone = 1;
                   9458:             }
                   9459:         }
                   9460:     }
                   9461:     return $canclone;
                   9462: }
                   9463: 
1.679     raeburn  9464: # ------------------------------------------------------- Course Group routines
                   9465: 
                   9466: sub get_coursegroups {
1.809     raeburn  9467:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9468:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9469: }
                   9470: 
1.679     raeburn  9471: sub modify_coursegroup {
                   9472:     my ($cdom,$cnum,$groupsettings) = @_;
                   9473:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9474: }
                   9475: 
1.809     raeburn  9476: sub toggle_coursegroup_status {
                   9477:     my ($cdom,$cnum,$group,$action) = @_;
                   9478:     my ($from_namespace,$to_namespace);
                   9479:     if ($action eq 'delete') {
                   9480:         $from_namespace = 'coursegroups';
                   9481:         $to_namespace = 'deleted_groups';
                   9482:     } else {
                   9483:         $from_namespace = 'deleted_groups';
                   9484:         $to_namespace = 'coursegroups';
                   9485:     }
                   9486:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9487:     if (my $tmp = &error(%curr_group)) {
                   9488:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9489:         return ('read error',$tmp);
                   9490:     } else {
                   9491:         my %savedsettings = %curr_group; 
1.809     raeburn  9492:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9493:         my $deloutcome;
                   9494:         if ($result eq 'ok') {
1.809     raeburn  9495:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9496:         } else {
                   9497:             return ('write error',$result);
                   9498:         }
                   9499:         if ($deloutcome eq 'ok') {
                   9500:             return 'ok';
                   9501:         } else {
                   9502:             return ('delete error',$deloutcome);
                   9503:         }
                   9504:     }
                   9505: }
                   9506: 
1.679     raeburn  9507: sub modify_group_roles {
1.957     raeburn  9508:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9509:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9510:     my $role = 'gr/'.&escape($userprivs);
                   9511:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9512:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9513:     if ($result eq 'ok') {
                   9514:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9515:     }
1.679     raeburn  9516:     return $result;
                   9517: }
                   9518: 
                   9519: sub modify_coursegroup_membership {
                   9520:     my ($cdom,$cnum,$membership) = @_;
                   9521:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9522:     return $result;
                   9523: }
                   9524: 
1.682     raeburn  9525: sub get_active_groups {
                   9526:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9527:     my $now = time;
                   9528:     my %groups = ();
                   9529:     foreach my $key (keys(%env)) {
1.811     albertel 9530:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9531:             my ($start,$end) = split(/\./,$env{$key});
                   9532:             if (($end!=0) && ($end<$now)) { next; }
                   9533:             if (($start!=0) && ($start>$now)) { next; }
                   9534:             if ($1 eq $cdom && $2 eq $cnum) {
                   9535:                 $groups{$3} = $env{$key} ;
                   9536:             }
                   9537:         }
                   9538:     }
                   9539:     return %groups;
                   9540: }
                   9541: 
1.683     raeburn  9542: sub get_group_membership {
                   9543:     my ($cdom,$cnum,$group) = @_;
                   9544:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9545: }
                   9546: 
                   9547: sub get_users_groups {
                   9548:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9549:     my @usersgroups;
1.683     raeburn  9550:     my $cachetime=1800;
                   9551: 
                   9552:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9553:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9554:     if (defined($cached)) {
1.734     albertel 9555:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9556:     } else {  
                   9557:         $grouplist = '';
1.816     raeburn  9558:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9559:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9560:         my $access_end = $env{'course.'.$courseid.
                   9561:                               '.default_enrollment_end_date'};
                   9562:         my $now = time;
                   9563:         foreach my $key (keys(%roleshash)) {
                   9564:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9565:                 my $group = $1;
                   9566:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9567:                     my $start = $2;
                   9568:                     my $end = $1;
                   9569:                     if ($start == -1) { next; } # deleted from group
                   9570:                     if (($start!=0) && ($start>$now)) { next; }
                   9571:                     if (($end!=0) && ($end<$now)) {
                   9572:                         if ($access_end && $access_end < $now) {
                   9573:                             if ($access_end - $end < 86400) {
                   9574:                                 push(@usersgroups,$group);
1.733     raeburn  9575:                             }
                   9576:                         }
1.817     raeburn  9577:                         next;
1.733     raeburn  9578:                     }
1.817     raeburn  9579:                     push(@usersgroups,$group);
1.683     raeburn  9580:                 }
                   9581:             }
                   9582:         }
1.817     raeburn  9583:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9584:         $grouplist = join(':',@usersgroups);
                   9585:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9586:     }
1.733     raeburn  9587:     return @usersgroups;
1.683     raeburn  9588: }
                   9589: 
                   9590: sub devalidate_getgroups_cache {
                   9591:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9592:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9593: 
1.683     raeburn  9594:     my $hashid="$udom:$uname:$courseid";
                   9595:     &devalidate_cache_new('getgroups',$hashid);
                   9596: }
                   9597: 
1.12      www      9598: # ------------------------------------------------------------------ Plain Text
                   9599: 
                   9600: sub plaintext {
1.988     raeburn  9601:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9602:     if ($short =~ m{^cr/}) {
1.758     albertel 9603: 	return (split('/',$short))[-1];
                   9604:     }
1.742     raeburn  9605:     if (!defined($cid)) {
                   9606:         $cid = $env{'request.course.id'};
                   9607:     }
                   9608:     my %rolenames = (
1.1008    raeburn  9609:                       Course    => 'std',
                   9610:                       Community => 'alt1',
1.742     raeburn  9611:                     );
1.1037    raeburn  9612:     if ($cid ne '') {
                   9613:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9614:             unless ($forcedefault) {
                   9615:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9616:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9617:                 return &Apache::lonlocal::mt($roletext);
                   9618:             }
                   9619:         }
                   9620:     }
                   9621:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9622:         (defined($rolenames{$type})) && 
                   9623:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9624:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9625:     } elsif ($cid ne '') {
                   9626:         my $crstype = $env{'course.'.$cid.'.type'};
                   9627:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9628:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9629:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9630:         }
1.742     raeburn  9631:     }
1.1037    raeburn  9632:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9633: }
                   9634: 
                   9635: # ----------------------------------------------------------------- Assign Role
                   9636: 
                   9637: sub assignrole {
1.957     raeburn  9638:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9639:         $context)=@_;
1.21      www      9640:     my $mrole;
                   9641:     if ($role =~ /^cr\//) {
1.393     www      9642:         my $cwosec=$url;
1.811     albertel 9643:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9644: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9645:            my $refused = 1;
                   9646:            if ($context eq 'requestcourses') {
                   9647:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9648:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9649:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9650:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9651:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9652:                            if ($crsenv{'internal.courseowner'} eq
                   9653:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9654:                                $refused = '';
                   9655:                            }
                   9656:                        }
                   9657:                    }
                   9658:                }
                   9659:            }
                   9660:            if ($refused) {
                   9661:                &logthis('Refused custom assignrole: '.
                   9662:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9663:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9664:                return 'refused';
                   9665:            }
1.104     www      9666:         }
1.21      www      9667:         $mrole='cr';
1.678     raeburn  9668:     } elsif ($role =~ /^gr\//) {
                   9669:         my $cwogrp=$url;
1.811     albertel 9670:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9671:         unless (&allowed('mdg',$cwogrp)) {
                   9672:             &logthis('Refused group assignrole: '.
                   9673:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9674:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9675:             return 'refused';
                   9676:         }
                   9677:         $mrole='gr';
1.21      www      9678:     } else {
1.82      www      9679:         my $cwosec=$url;
1.811     albertel 9680:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9681:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9682:             my $refused;
                   9683:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9684:                 if (!(&allowed('c'.$role,$url))) {
                   9685:                     $refused = 1;
                   9686:                 }
                   9687:             } else {
                   9688:                 $refused = 1;
                   9689:             }
1.947     raeburn  9690:             if ($refused) {
1.1045    raeburn  9691:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9692:                 if (!$selfenroll && $context eq 'course') {
                   9693:                     my %crsenv;
                   9694:                     if ($role eq 'cc' || $role eq 'co') {
                   9695:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9696:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9697:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9698:                                 if ($crsenv{'internal.courseowner'} eq 
                   9699:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9700:                                     $refused = '';
                   9701:                                 }
                   9702:                             }
                   9703:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9704:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9705:                                 if ($crsenv{'internal.courseowner'} eq 
                   9706:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9707:                                     $refused = '';
                   9708:                                 }
                   9709:                             }
                   9710:                         }
                   9711:                     }
                   9712:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9713:                     $refused = '';
1.1017    raeburn  9714:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9715:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9716:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9717:                         my $wrongcc;
                   9718:                         if ($cnum =~ /^$match_community$/) {
                   9719:                             $wrongcc = 1 if ($role eq 'cc');
                   9720:                         } else {
                   9721:                             $wrongcc = 1 if ($role eq 'co');
                   9722:                         }
                   9723:                         unless ($wrongcc) {
                   9724:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9725:                             if ($crsenv{'internal.courseowner'} eq 
                   9726:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9727:                                 $refused = '';
                   9728:                             }
1.1017    raeburn  9729:                         }
                   9730:                     }
1.1172.2.9  raeburn  9731:                 } elsif ($context eq 'requestauthor') {
                   9732:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9733:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9734:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9735:                             $refused = '';
                   9736:                         } else {
                   9737:                             my %domdefaults = &get_domain_defaults($udom);
                   9738:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9739:                                 my $checkbystatus;
                   9740:                                 if ($env{'user.adv'}) {
                   9741:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9742:                                     if ($disposition eq 'automatic') {
                   9743:                                         $refused = '';
                   9744:                                     } elsif ($disposition eq '') {
                   9745:                                         $checkbystatus = 1;
                   9746:                                     }
                   9747:                                 } else {
                   9748:                                     $checkbystatus = 1;
                   9749:                                 }
                   9750:                                 if ($checkbystatus) {
                   9751:                                     if ($env{'environment.inststatus'}) {
                   9752:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9753:                                         foreach my $type (@inststatuses) {
                   9754:                                             if (($type ne '') &&
                   9755:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9756:                                                 $refused = '';
                   9757:                                             }
                   9758:                                         }
                   9759:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9760:                                         $refused = '';
                   9761:                                     }
                   9762:                                 }
                   9763:                             }
                   9764:                         }
                   9765:                     }
1.1017    raeburn  9766:                 }
                   9767:                 if ($refused) {
1.947     raeburn  9768:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9769:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9770: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9771:                     return 'refused';
                   9772:                 }
1.932     raeburn  9773:             }
1.1131    raeburn  9774:         } elsif ($role eq 'au') {
                   9775:             if ($url ne '/'.$udom.'/') {
                   9776:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9777:                          ' to assign author role for '.$uname.':'.$udom.
                   9778:                          ' in domain: '.$url.' refused (wrong domain).');
                   9779:                 return 'refused';
                   9780:             }
1.104     www      9781:         }
1.21      www      9782:         $mrole=$role;
                   9783:     }
1.620     albertel 9784:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9785:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9786:     if ($end) { $command.='_'.$end; }
1.21      www      9787:     if ($start) {
                   9788: 	if ($end) { 
1.81      www      9789:            $command.='_'.$start; 
1.21      www      9790:         } else {
1.81      www      9791:            $command.='_0_'.$start;
1.21      www      9792:         }
                   9793:     }
1.739     raeburn  9794:     my $origstart = $start;
                   9795:     my $origend = $end;
1.957     raeburn  9796:     my $delflag;
1.357     www      9797: # actually delete
                   9798:     if ($deleteflag) {
1.373     www      9799: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9800: # modify command to delete the role
1.620     albertel 9801:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9802:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9803: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9804: # set start and finish to negative values for userrolelog
                   9805:            $start=-1;
                   9806:            $end=-1;
1.957     raeburn  9807:            $delflag = 1;
1.357     www      9808:         }
                   9809:     }
                   9810: # send command
1.349     www      9811:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9812: # log new user role if status is ok
1.349     www      9813:     if ($answer eq 'ok') {
1.663     raeburn  9814: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9815:         if (($role eq 'cc') || ($role eq 'in') ||
                   9816:             ($role eq 'ep') || ($role eq 'ad') ||
                   9817:             ($role eq 'ta') || ($role eq 'st') ||
                   9818:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9819:             ($role eq 'co')) {
1.1172.2.13  raeburn  9820: # for course roles, perform group memberships changes triggered by role change.
                   9821:             unless ($role =~ /^gr/) {
                   9822:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9823:                                                  $origstart,$selfenroll,$context);
                   9824:             }
1.1172.2.9  raeburn  9825:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9826:                            $selfenroll,$context);
                   9827:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9828:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9829:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9830:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9831:                            $context);
                   9832:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9833:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9834:                              $context);
                   9835:         }
1.1053    raeburn  9836:         if ($role eq 'cc') {
                   9837:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9838:         }
1.349     www      9839:     }
                   9840:     return $answer;
1.169     harris41 9841: }
                   9842: 
1.1053    raeburn  9843: sub autoupdate_coowners {
                   9844:     my ($url,$end,$start,$uname,$udom) = @_;
                   9845:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9846:     if (($cdom ne '') && ($cnum ne '')) {
                   9847:         my $now = time;
                   9848:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9849:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9850:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9851:             my $instcode = $coursehash{'internal.coursecode'};
                   9852:             if ($instcode ne '') {
1.1056    raeburn  9853:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9854:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9855:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9856:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9857:                         if ($result eq 'valid') {
                   9858:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9859:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9860:                                     push(@newcoowners,$coowner);
                   9861:                                 }
                   9862:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9863:                                     push(@newcoowners,$uname.':'.$udom);
                   9864:                                 }
                   9865:                                 @newcoowners = sort(@newcoowners);
                   9866:                             } else {
                   9867:                                 push(@newcoowners,$uname.':'.$udom);
                   9868:                             }
                   9869:                         } else {
                   9870:                             if ($coursehash{'internal.co-owners'}) {
                   9871:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9872:                                     unless ($coowner eq $uname.':'.$udom) {
                   9873:                                         push(@newcoowners,$coowner);
                   9874:                                     }
                   9875:                                 }
                   9876:                                 unless (@newcoowners > 0) {
                   9877:                                     $delcoowners = 1;
                   9878:                                     $coowners = '';
                   9879:                                 }
                   9880:                             }
                   9881:                         }
                   9882:                         if (@newcoowners || $delcoowners) {
                   9883:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9884:                                             $delcoowners,@newcoowners);
                   9885:                         }
                   9886:                     }
                   9887:                 }
                   9888:             }
                   9889:         }
                   9890:     }
                   9891: }
                   9892: 
                   9893: sub store_coowners {
                   9894:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9895:     my $cid = $cdom.'_'.$cnum;
                   9896:     my ($coowners,$delresult,$putresult);
                   9897:     if (@newcoowners) {
                   9898:         $coowners = join(',',@newcoowners);
                   9899:         my %coownershash = (
                   9900:                             'internal.co-owners' => $coowners,
                   9901:                            );
                   9902:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9903:         if ($putresult eq 'ok') {
                   9904:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9905:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9906:             }
                   9907:         }
                   9908:     }
                   9909:     if ($delcoowners) {
                   9910:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9911:         if ($delresult eq 'ok') {
                   9912:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9913:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9914:             }
                   9915:         }
                   9916:     }
                   9917:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9918:         my %crsinfo =
                   9919:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9920:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9921:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9922:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9923:         }
                   9924:     }
                   9925: }
                   9926: 
1.169     harris41 9927: # -------------------------------------------------- Modify user authentication
1.197     www      9928: # Overrides without validation
                   9929: 
1.169     harris41 9930: sub modifyuserauth {
                   9931:     my ($udom,$uname,$umode,$upass)=@_;
                   9932:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  9933:     my $allowed;
                   9934:     if (&allowed('mau',$udom)) {
                   9935:         $allowed = 1;
                   9936:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   9937:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   9938:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   9939:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9940:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9941:         if (($cdom ne '') && ($cnum ne '')) {
                   9942:             my $is_owner = &is_course_owner($cdom,$cnum);
                   9943:             if ($is_owner) {
                   9944:                 $allowed = 1;
                   9945:             }
                   9946:         }
                   9947:     }
                   9948:     unless ($allowed) { return 'refused'; }
1.197     www      9949:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9950:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9951:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9952:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9953: 		     &escape($upass),$uhome);
1.620     albertel 9954:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9955:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9956:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9957:     &log($udom,,$uname,$uhome,
1.620     albertel 9958:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9959:                                      $env{'user.name'}.', '.$umode.
1.197     www      9960:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9961:     unless ($reply eq 'ok') {
1.197     www      9962:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9963: 	return 'error: '.$reply;
                   9964:     }   
1.170     harris41 9965:     return 'ok';
1.80      www      9966: }
                   9967: 
1.81      www      9968: # --------------------------------------------------------------- Modify a user
1.80      www      9969: 
1.81      www      9970: sub modifyuser {
1.206     matthew  9971:     my ($udom,    $uname, $uid,
                   9972:         $umode,   $upass, $first,
                   9973:         $middle,  $last,  $gene,
1.1058    raeburn  9974:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9975:     $udom= &LONCAPA::clean_domain($udom);
                   9976:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9977:     my $showcandelete = 'none';
                   9978:     if (ref($candelete) eq 'ARRAY') {
                   9979:         if (@{$candelete} > 0) {
                   9980:             $showcandelete = join(', ',@{$candelete});
                   9981:         }
                   9982:     }
1.81      www      9983:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9984:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9985: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9986:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9987:                                      ' desiredhome not specified'). 
1.620     albertel 9988:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9989:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9990:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9991:     my $newuser;
                   9992:     if ($uhome eq 'no_host') {
                   9993:         $newuser = 1;
                   9994:     }
1.80      www      9995: # ----------------------------------------------------------------- Create User
1.406     albertel 9996:     if (($uhome eq 'no_host') && 
                   9997: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9998:         my $unhome='';
1.844     albertel 9999:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10000:             $unhome = $desiredhome;
1.620     albertel 10001: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10002: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10003:         } else { # load balancing routine for determining $unhome
1.81      www      10004:             my $loadm=10000000;
1.841     albertel 10005: 	    my %servers = &get_servers($udom,'library');
                   10006: 	    foreach my $tryserver (keys(%servers)) {
                   10007: 		my $answer=reply('load',$tryserver);
                   10008: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10009: 		    $loadm=$answer;
                   10010: 		    $unhome=$tryserver;
                   10011: 		}
1.80      www      10012: 	    }
                   10013:         }
                   10014:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10015: 	    return 'error: unable to find a home server for '.$uname.
                   10016:                    ' in domain '.$udom;
1.80      www      10017:         }
                   10018:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10019:                          &escape($upass),$unhome);
                   10020: 	unless ($reply eq 'ok') {
                   10021:             return 'error: '.$reply;
                   10022:         }   
1.230     stredwic 10023:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10024:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10025: 	    return 'error: unable verify users home machine.';
1.80      www      10026:         }
1.209     matthew  10027:     }   # End of creation of new user
1.80      www      10028: # ---------------------------------------------------------------------- Add ID
                   10029:     if ($uid) {
                   10030:        $uid=~tr/A-Z/a-z/;
                   10031:        my %uidhash=&idrget($udom,$uname);
1.196     www      10032:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10033:          && (!$forceid)) {
1.80      www      10034: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10035: 	      return 'error: user id "'.$uid.'" does not match '.
                   10036:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10037:           }
                   10038:        } else {
                   10039: 	  &idput($udom,($uname => $uid));
                   10040:        }
                   10041:     }
                   10042: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10043:     my @tmp=&get('environment',
1.899     raeburn  10044: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10045:                     'permanentemail','inststatus'],
1.134     albertel 10046: 		   $udom,$uname);
1.1075    raeburn  10047:     my (%names,%oldnames);
1.313     matthew  10048:     if ($tmp[0] =~ m/^error:.*/) { 
                   10049:         %names=(); 
                   10050:     } else {
                   10051:         %names = @tmp;
1.1075    raeburn  10052:         %oldnames = %names;
1.313     matthew  10053:     }
1.388     www      10054: #
1.1058    raeburn  10055: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10056: # of users did not contain them), do not overwrite existing values
                   10057: # unless field is in $candelete array ref.  
                   10058: #
                   10059: 
                   10060:     my @fields = ('firstname','middlename','lastname','generation',
                   10061:                   'permanentemail','id');
                   10062:     my %newvalues;
                   10063:     if (ref($candelete) eq 'ARRAY') {
                   10064:         foreach my $field (@fields) {
                   10065:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10066:                 if ($field eq 'firstname') {
                   10067:                     $names{$field} = $first;
                   10068:                 } elsif ($field eq 'middlename') {
                   10069:                     $names{$field} = $middle;
                   10070:                 } elsif ($field eq 'lastname') {
                   10071:                     $names{$field} = $last;
                   10072:                 } elsif ($field eq 'generation') { 
                   10073:                     $names{$field} = $gene;
                   10074:                 } elsif ($field eq 'permanentemail') {
                   10075:                     $names{$field} = $email;
                   10076:                 } elsif ($field eq 'id') {
                   10077:                     $names{$field}  = $uid;
                   10078:                 }
                   10079:             }
                   10080:         }
                   10081:     }
1.388     www      10082:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10083:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10084:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10085:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10086:     if ($email) {
                   10087:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10088:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10089:     }
1.899     raeburn  10090:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10091:     if (defined($inststatus)) {
                   10092:         $names{'inststatus'} = '';
                   10093:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10094:         if (ref($usertypes) eq 'HASH') {
                   10095:             my @okstatuses; 
                   10096:             foreach my $item (split(/:/,$inststatus)) {
                   10097:                 if (defined($usertypes->{$item})) {
                   10098:                     push(@okstatuses,$item);  
                   10099:                 }
                   10100:             }
                   10101:             if (@okstatuses) {
                   10102:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10103:             }
                   10104:         }
                   10105:     }
1.1075    raeburn  10106:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10107:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10108:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10109:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10110:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10111:     } else {
                   10112:         $logmsg .= ' during self creation';
                   10113:     }
1.1075    raeburn  10114:     my $changed;
                   10115:     if ($newuser) {
                   10116:         $changed = 1;
                   10117:     } else {
                   10118:         foreach my $field (@fields) {
                   10119:             if ($names{$field} ne $oldnames{$field}) {
                   10120:                 $changed = 1;
                   10121:                 last;
                   10122:             }
                   10123:         }
                   10124:     }
                   10125:     unless ($changed) {
                   10126:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10127:         &logthis($logmsg);
                   10128:         return 'ok';
                   10129:     }
                   10130:     my $reply = &put('environment', \%names, $udom,$uname);
                   10131:     if ($reply ne 'ok') { 
                   10132:         return 'error: '.$reply;
                   10133:     }
1.1087    raeburn  10134:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10135:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10136:     }
1.1075    raeburn  10137:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10138:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10139:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10140:     &logthis($logmsg);
1.134     albertel 10141:     return 'ok';
1.80      www      10142: }
                   10143: 
1.81      www      10144: # -------------------------------------------------------------- Modify student
1.80      www      10145: 
1.81      www      10146: sub modifystudent {
                   10147:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10148:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10149:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10150:     if (!$cid) {
1.620     albertel 10151: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10152: 	    return 'not_in_class';
                   10153: 	}
1.80      www      10154:     }
                   10155: # --------------------------------------------------------------- Make the user
1.81      www      10156:     my $reply=&modifyuser
1.209     matthew  10157: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10158:          $desiredhome,$email,$inststatus);
1.80      www      10159:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10160:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10161:     # student's environment
1.297     matthew  10162:     $uid = undef if (!$forceid);
1.455     albertel 10163:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10164: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10165:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10166:     return $reply;
                   10167: }
                   10168: 
                   10169: sub modify_student_enrollment {
1.1172.2.23  raeburn  10170:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10171:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10172:     my ($cdom,$cnum,$chome);
                   10173:     if (!$cid) {
1.620     albertel 10174: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10175: 	    return 'not_in_class';
                   10176: 	}
1.620     albertel 10177: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10178: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10179:     } else {
                   10180: 	($cdom,$cnum)=split(/_/,$cid);
                   10181:     }
1.620     albertel 10182:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10183:     if (!$chome) {
1.457     raeburn  10184: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10185:     }
1.455     albertel 10186:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10187:     # Make sure the user exists
1.81      www      10188:     my $uhome=&homeserver($uname,$udom);
                   10189:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10190: 	return 'error: no such user';
                   10191:     }
1.297     matthew  10192:     # Get student data if we were not given enough information
                   10193:     if (!defined($first)  || $first  eq '' || 
                   10194:         !defined($last)   || $last   eq '' || 
                   10195:         !defined($uid)    || $uid    eq '' || 
                   10196:         !defined($middle) || $middle eq '' || 
                   10197:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10198:         # They did not supply us with enough data to enroll the student, so
                   10199:         # we need to pick up more information.
1.297     matthew  10200:         my %tmp = &get('environment',
1.294     matthew  10201:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10202:                        ,$udom,$uname);
                   10203: 
1.800     albertel 10204:         #foreach my $key (keys(%tmp)) {
                   10205:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10206:         #}
1.294     matthew  10207:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10208:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10209:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10210:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10211:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10212:     }
1.556     albertel 10213:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10214:     my $user = "$uname:$udom";
                   10215:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10216:     my $reply=cput('classlist',
1.1148    raeburn  10217: 		   {$user => 
1.1172.2.76  raeburn  10218: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10219: 		   $cdom,$cnum);
1.1148    raeburn  10220:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10221:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10222:     } else { 
1.81      www      10223: 	return 'error: '.$reply;
                   10224:     }
1.297     matthew  10225:     # Add student role to user
1.83      www      10226:     my $uurl='/'.$cid;
1.81      www      10227:     $uurl=~s/\_/\//g;
                   10228:     if ($usec) {
                   10229: 	$uurl.='/'.$usec;
                   10230:     }
1.1148    raeburn  10231:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10232:                              $selfenroll,$context);
                   10233:     if ($result ne 'ok') {
                   10234:         if ($old_entry{$user} ne '') {
                   10235:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10236:         } else {
                   10237:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10238:         }
                   10239:     }
                   10240:     return $result; 
1.21      www      10241: }
                   10242: 
1.556     albertel 10243: sub format_name {
                   10244:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10245:     my $name;
                   10246:     if ($first ne 'lastname') {
                   10247: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10248:     } else {
                   10249: 	if ($lastname=~/\S/) {
                   10250: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10251: 	    $name=~s/\s+,/,/;
                   10252: 	} else {
                   10253: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10254: 	}
                   10255:     }
                   10256:     $name=~s/^\s+//;
                   10257:     $name=~s/\s+$//;
                   10258:     $name=~s/\s+/ /g;
                   10259:     return $name;
                   10260: }
                   10261: 
1.84      www      10262: # ------------------------------------------------- Write to course preferences
                   10263: 
                   10264: sub writecoursepref {
                   10265:     my ($courseid,%prefs)=@_;
                   10266:     $courseid=~s/^\///;
                   10267:     $courseid=~s/\_/\//g;
                   10268:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10269:     my $chome=homeserver($cnum,$cdomain);
                   10270:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10271: 	return 'error: no such course';
                   10272:     }
                   10273:     my $cstring='';
1.800     albertel 10274:     foreach my $pref (keys(%prefs)) {
                   10275: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10276:     }
1.84      www      10277:     $cstring=~s/\&$//;
                   10278:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10279: }
                   10280: 
                   10281: # ---------------------------------------------------------- Make/modify course
                   10282: 
                   10283: sub createcourse {
1.741     raeburn  10284:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1172.2.118.  .6(raebu 10285:20):         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      10286:     $url=&declutter($url);
                   10287:     my $cid='';
1.1028    raeburn  10288:     if ($context eq 'requestcourses') {
                   10289:         my $can_create = 0;
                   10290:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10291:         if ($udom eq $ownerdom) {
1.1172.2.118.  .6(raebu 10292:20):             my $reload;
                   10293:20):             if (($callercontext eq 'auto') &&
                   10294:20):                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   10295:20):                 $reload = 'reload';
                   10296:20):             }
                   10297:20):             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  10298:                                   $context)) {
                   10299:                 $can_create = 1;
                   10300:             }
                   10301:         } else {
                   10302:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10303:                                            $category);
                   10304:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10305:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10306:                 if (@curr > 0) {
                   10307:                     my @options = qw(approval validate autolimit);
                   10308:                     my $optregex = join('|',@options);
                   10309:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10310:                         $can_create = 1;
                   10311:                     }
                   10312:                 }
                   10313:             }
                   10314:         }
                   10315:         if ($can_create) {
                   10316:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10317:                 unless (&allowed('ccc',$udom)) {
                   10318:                     return 'refused'; 
                   10319:                 }
1.1017    raeburn  10320:             }
                   10321:         } else {
                   10322:             return 'refused';
                   10323:         }
1.1028    raeburn  10324:     } elsif (!&allowed('ccc',$udom)) {
                   10325:         return 'refused';
1.84      www      10326:     }
1.1011    raeburn  10327: # --------------------------------------------------------------- Get Unique ID
                   10328:     my $uname;
                   10329:     if ($cnum =~ /^$match_courseid$/) {
                   10330:         my $chome=&homeserver($cnum,$udom,'true');
                   10331:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10332:             $uname = $cnum;
                   10333:         } else {
1.1038    raeburn  10334:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10335:         }
                   10336:     } else {
1.1038    raeburn  10337:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10338:     }
                   10339:     return $uname if ($uname =~ /^error/);
                   10340: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10341:     if (!defined($course_server)) {
                   10342:         if (defined(&domain($udom,'primary'))) {
                   10343:             $course_server = &domain($udom,'primary');
                   10344:         } else {
                   10345:             $course_server = $env{'user.home'}; 
                   10346:         }
                   10347:     }
                   10348:     my %host_servers =
                   10349:         &Apache::lonnet::get_servers($udom,'library');
                   10350:     unless ($host_servers{$course_server}) {
                   10351:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10352:     }
1.84      www      10353: # ------------------------------------------------------------- Make the course
                   10354:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10355:                       $course_server);
1.84      www      10356:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10357:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10358:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10359: 	return 'error: no such course';
                   10360:     }
1.271     www      10361: # ----------------------------------------------------------------- Course made
1.516     raeburn  10362: # log existence
1.1029    raeburn  10363:     my $now = time;
1.918     raeburn  10364:     my $newcourse = {
                   10365:                     $udom.'_'.$uname => {
1.921     raeburn  10366:                                      description => $description,
                   10367:                                      inst_code   => $inst_code,
                   10368:                                      owner       => $course_owner,
                   10369:                                      type        => $crstype,
1.1029    raeburn  10370:                                      creator     => $env{'user.name'}.':'.
                   10371:                                                     $env{'user.domain'},
                   10372:                                      created     => $now,
                   10373:                                      context     => $context,
1.918     raeburn  10374:                                                 },
                   10375:                     };
1.921     raeburn  10376:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10377: # set toplevel url
1.271     www      10378:     my $topurl=$url;
                   10379:     unless ($nonstandard) {
                   10380: # ------------------------------------------ For standard courses, make top url
                   10381:         my $mapurl=&clutter($url);
1.278     www      10382:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10383:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10384: <map>
                   10385: <resource id="1" type="start"></resource>
                   10386: <resource id="2" src="$mapurl"></resource>
                   10387: <resource id="3" type="finish"></resource>
                   10388: <link index="1" from="1" to="2"></link>
                   10389: <link index="2" from="2" to="3"></link>
                   10390: </map>
                   10391: ENDINITMAP
                   10392:         $topurl=&declutter(
1.638     albertel 10393:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10394:                           );
                   10395:     }
                   10396: # ----------------------------------------------------------- Write preferences
1.84      www      10397:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10398:                      ('description'              => $description,
                   10399:                       'url'                      => $topurl,
                   10400:                       'internal.creator'         => $env{'user.name'}.':'.
                   10401:                                                     $env{'user.domain'},
                   10402:                       'internal.created'         => $now,
                   10403:                       'internal.creationcontext' => $context)
                   10404:                     );
1.84      www      10405:     return '/'.$udom.'/'.$uname;
                   10406: }
                   10407: 
1.1011    raeburn  10408: # ------------------------------------------------------------------- Create ID
                   10409: sub generate_coursenum {
1.1038    raeburn  10410:     my ($udom,$crstype) = @_;
1.1011    raeburn  10411:     my $domdesc = &domain($udom);
                   10412:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10413:     my $first;
                   10414:     if ($crstype eq 'Community') {
                   10415:         $first = '0';
                   10416:     } else {
                   10417:         $first = int(1+rand(9)); 
                   10418:     } 
                   10419:     my $uname=$first.
1.1011    raeburn  10420:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10421:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10422:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10423: # ----------------------------------------------- Make sure that does not exist
                   10424:     my $uhome=&homeserver($uname,$udom,'true');
                   10425:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10426:         if ($crstype eq 'Community') {
                   10427:             $first = '0';
                   10428:         } else {
                   10429:             $first = int(1+rand(9));
                   10430:         }
                   10431:         $uname=$first.
1.1011    raeburn  10432:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10433:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10434:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10435:         $uhome=&homeserver($uname,$udom,'true');
                   10436:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10437:             return 'error: unable to generate unique course-ID';
                   10438:         }
                   10439:     }
                   10440:     return $uname;
                   10441: }
                   10442: 
1.813     albertel 10443: sub is_course {
1.1167    droeschl 10444:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10445:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10446:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10447:     my $uhome=&homeserver($cnum,$cdom);
                   10448:     my $iscourse;
                   10449:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10450:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10451:     } else {
                   10452:         my $hashid = $cdom.':'.$cnum;
                   10453:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10454:         unless (defined($cached)) {
                   10455:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10456:                                         $cnum,undef,undef,'.');
                   10457:             $iscourse = 0;
                   10458:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10459:                 $iscourse = 1;
                   10460:             }
                   10461:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10462:         }
                   10463:     }
                   10464:     return unless($iscourse);
1.1167    droeschl 10465:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10466: }
                   10467: 
1.1015    raeburn  10468: sub store_userdata {
                   10469:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10470:     my $result;
1.1016    raeburn  10471:     if ($datakey ne '') {
1.1013    raeburn  10472:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10473:             if ($udom eq '' || $uname eq '') {
                   10474:                 $udom = $env{'user.domain'};
                   10475:                 $uname = $env{'user.name'};
                   10476:             }
                   10477:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10478:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10479:                 $result = 'error: no_host';
                   10480:             } else {
                   10481:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10482:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10483: 
                   10484:                 my $namevalue='';
                   10485:                 foreach my $key (keys(%{$storehash})) {
                   10486:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10487:                 }
                   10488:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10489:                 unless ($namespace eq 'courserequests') {
                   10490:                     $datakey = &escape($datakey);
                   10491:                 }
1.1105    raeburn  10492:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10493:                                   $namevalue,$uhome);
1.1013    raeburn  10494:             }
                   10495:         } else {
                   10496:             $result = 'error: data to store was not a hash reference'; 
                   10497:         }
                   10498:     } else {
                   10499:         $result= 'error: invalid requestkey'; 
                   10500:     }
                   10501:     return $result;
                   10502: }
                   10503: 
1.21      www      10504: # ---------------------------------------------------------- Assign Custom Role
                   10505: 
                   10506: sub assigncustomrole {
1.957     raeburn  10507:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10508:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10509:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10510: }
                   10511: 
                   10512: # ----------------------------------------------------------------- Revoke Role
                   10513: 
                   10514: sub revokerole {
1.957     raeburn  10515:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10516:     my $now=time;
1.965     raeburn  10517:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10518: }
                   10519: 
                   10520: # ---------------------------------------------------------- Revoke Custom Role
                   10521: 
                   10522: sub revokecustomrole {
1.957     raeburn  10523:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10524:     my $now=time;
1.357     www      10525:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10526:            $deleteflag,$selfenroll,$context);
1.17      www      10527: }
                   10528: 
1.533     banghart 10529: # ------------------------------------------------------------ Disk usage
1.535     albertel 10530: sub diskusage {
1.955     raeburn  10531:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10532:     $directorypath =~ s/\/$//;
                   10533:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10534:                        .&escape($getpropath).':'.&escape($uname).':'
                   10535:                        .&escape($udom),homeserver($uname,$udom));
                   10536:     if ($listing eq 'unknown_cmd') {
                   10537:         if ($getpropath) {
                   10538:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10539:         }
                   10540:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10541:     }
1.514     albertel 10542:     return $listing;
1.512     banghart 10543: }
                   10544: 
1.566     banghart 10545: sub is_locked {
1.1096    raeburn  10546:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10547:     my @check;
                   10548:     my $is_locked;
1.1093    raeburn  10549:     push (@check,$file_name);
1.613     albertel 10550:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10551: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10552:     my ($tmp)=keys(%locked);
                   10553:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10554:     
1.566     banghart 10555:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10556:         $is_locked = 'false';
                   10557:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10558:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10559:                $is_locked = 'true';
1.1096    raeburn  10560:                if (ref($which) eq 'ARRAY') {
                   10561:                    push(@{$which},$entry);
                   10562:                } else {
                   10563:                    last;
                   10564:                }
1.745     raeburn  10565:            }
                   10566:        }
1.566     banghart 10567:     } else {
                   10568:         $is_locked = 'false';
                   10569:     }
1.1093    raeburn  10570:     return $is_locked;
1.566     banghart 10571: }
                   10572: 
1.759     albertel 10573: sub declutter_portfile {
                   10574:     my ($file) = @_;
1.833     albertel 10575:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10576:     return $file;
                   10577: }
                   10578: 
1.559     banghart 10579: # ------------------------------------------------------------- Mark as Read Only
                   10580: 
                   10581: sub mark_as_readonly {
                   10582:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10583:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10584:     my ($tmp)=keys(%current_permissions);
                   10585:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10586:     foreach my $file (@{$files}) {
1.759     albertel 10587: 	$file = &declutter_portfile($file);
1.561     banghart 10588:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10589:     }
1.613     albertel 10590:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10591:     return;
                   10592: }
                   10593: 
1.572     banghart 10594: # ------------------------------------------------------------Save Selected Files
                   10595: 
                   10596: sub save_selected_files {
                   10597:     my ($user, $path, @files) = @_;
                   10598:     my $filename = $user."savedfiles";
1.573     banghart 10599:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  10600:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10601:     foreach my $file (@files) {
1.620     albertel 10602:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10603:     }
                   10604:     foreach my $file (@other_files) {
1.574     banghart 10605:         print (OUT $file."\n");
1.572     banghart 10606:     }
1.574     banghart 10607:     close (OUT);
1.572     banghart 10608:     return 'ok';
                   10609: }
                   10610: 
1.574     banghart 10611: sub clear_selected_files {
                   10612:     my ($user) = @_;
                   10613:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  10614:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10615:     print (OUT undef);
                   10616:     close (OUT);
                   10617:     return ("ok");    
                   10618: }
                   10619: 
1.572     banghart 10620: sub files_in_path {
                   10621:     my ($user, $path) = @_;
                   10622:     my $filename = $user."savedfiles";
                   10623:     my %return_files;
1.1172.2.96  raeburn  10624:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10625:     while (my $line_in = <IN>) {
1.574     banghart 10626:         chomp ($line_in);
                   10627:         my @paths_and_file = split (m!/!, $line_in);
                   10628:         my $file_part = pop (@paths_and_file);
                   10629:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10630:         $path_part.='/';
                   10631:         my $path_and_file = $path_part.$file_part;
                   10632:         if ($path_part eq $path) {
                   10633:             $return_files{$file_part}= 'selected';
                   10634:         }
                   10635:     }
1.574     banghart 10636:     close (IN);
                   10637:     return (\%return_files);
1.572     banghart 10638: }
                   10639: 
                   10640: # called in portfolio select mode, to show files selected NOT in current directory
                   10641: sub files_not_in_path {
                   10642:     my ($user, $path) = @_;
                   10643:     my $filename = $user."savedfiles";
                   10644:     my @return_files;
                   10645:     my $path_part;
1.1172.2.96  raeburn  10646:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10647:     while (my $line = <IN>) {
1.572     banghart 10648:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10649:         my @paths_and_file = split(m|/|, $line);
                   10650:         my $file_part = pop(@paths_and_file);
                   10651:         chomp($file_part);
                   10652:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10653:         $path_part .= '/';
                   10654:         my $path_and_file = $path_part.$file_part;
                   10655:         if ($path_part ne $path) {
1.800     albertel 10656:             push(@return_files, ($path_and_file));
1.572     banghart 10657:         }
                   10658:     }
1.800     albertel 10659:     close(OUT);
1.574     banghart 10660:     return (@return_files);
1.572     banghart 10661: }
                   10662: 
1.745     raeburn  10663: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10664: 
1.745     raeburn  10665: sub get_portfile_permissions {
                   10666:     my ($domain,$user) = @_;
1.613     albertel 10667:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10668:     my ($tmp)=keys(%current_permissions);
                   10669:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10670:     return \%current_permissions;
                   10671: }
                   10672: 
                   10673: #---------------------------------------------Get portfolio file access controls
                   10674: 
1.749     raeburn  10675: sub get_access_controls {
1.745     raeburn  10676:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10677:     my %access;
                   10678:     my $real_file = $file;
                   10679:     $file =~ s/\.meta$//;
1.745     raeburn  10680:     if (defined($file)) {
1.749     raeburn  10681:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10682:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10683:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10684:             }
                   10685:         }
1.745     raeburn  10686:     } else {
1.749     raeburn  10687:         foreach my $key (keys(%{$current_permissions})) {
                   10688:             if ($key =~ /\0accesscontrol$/) {
                   10689:                 if (defined($group)) {
                   10690:                     if ($key !~ m-^\Q$group\E/-) {
                   10691:                         next;
                   10692:                     }
                   10693:                 }
                   10694:                 my ($fullpath) = split(/\0/,$key);
                   10695:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10696:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10697:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10698:                     }
                   10699:                 }
                   10700:             }
                   10701:         }
                   10702:     }
                   10703:     return %access;
                   10704: }
                   10705: 
                   10706: sub modify_access_controls {
                   10707:     my ($file_name,$changes,$domain,$user)=@_;
                   10708:     my ($outcome,$deloutcome);
                   10709:     my %store_permissions;
                   10710:     my %new_values;
                   10711:     my %new_control;
                   10712:     my %translation;
                   10713:     my @deletions = ();
                   10714:     my $now = time;
                   10715:     if (exists($$changes{'activate'})) {
                   10716:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10717:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10718:             my $numnew = scalar(@newitems);
                   10719:             for (my $i=0; $i<$numnew; $i++) {
                   10720:                 my $newkey = $newitems[$i];
                   10721:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10722:                 if ($newkey =~ /^\d+:/) { 
                   10723:                     $newkey =~ s/^(\d+)/$newid/;
                   10724:                     $translation{$1} = $newid;
                   10725:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10726:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10727:                     $translation{$1} = $newid;
                   10728:                 }
1.749     raeburn  10729:                 $new_values{$file_name."\0".$newkey} = 
                   10730:                                           $$changes{'activate'}{$newitems[$i]};
                   10731:                 $new_control{$newkey} = $now;
                   10732:             }
                   10733:         }
                   10734:     }
                   10735:     my %todelete;
                   10736:     my %changed_items;
                   10737:     foreach my $action ('delete','update') {
                   10738:         if (exists($$changes{$action})) {
                   10739:             if (ref($$changes{$action}) eq 'HASH') {
                   10740:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10741:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10742:                     if ($action eq 'delete') { 
                   10743:                         $todelete{$itemnum} = 1;
                   10744:                     } else {
                   10745:                         $changed_items{$itemnum} = $key;
                   10746:                     }
                   10747:                 }
1.745     raeburn  10748:             }
                   10749:         }
1.749     raeburn  10750:     }
                   10751:     # get lock on access controls for file.
                   10752:     my $lockhash = {
                   10753:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10754:                                                        ':'.$env{'user.domain'},
                   10755:                    }; 
                   10756:     my $tries = 0;
                   10757:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10758:    
1.1172.2.79  raeburn  10759:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10760:         $tries ++;
1.1172.2.79  raeburn  10761:         sleep(0.1);
1.749     raeburn  10762:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10763:     }
                   10764:     if ($gotlock eq 'ok') {
                   10765:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10766:         my ($tmp)=keys(%curr_permissions);
                   10767:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10768:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10769:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10770:             if (ref($curr_controls) eq 'HASH') {
                   10771:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10772:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10773:                     if (defined($todelete{$itemnum})) {
                   10774:                         push(@deletions,$file_name."\0".$control_item);
                   10775:                     } else {
                   10776:                         if (defined($changed_items{$itemnum})) {
                   10777:                             $new_control{$changed_items{$itemnum}} = $now;
                   10778:                             push(@deletions,$file_name."\0".$control_item);
                   10779:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10780:                         } else {
                   10781:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10782:                         }
                   10783:                     }
1.745     raeburn  10784:                 }
                   10785:             }
                   10786:         }
1.970     raeburn  10787:         my ($group);
                   10788:         if (&is_course($domain,$user)) {
                   10789:             ($group,my $file) = split(/\//,$file_name,2);
                   10790:         }
1.749     raeburn  10791:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10792:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10793:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10794:         #  remove lock
                   10795:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10796:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10797:         my $sqlresult =
1.970     raeburn  10798:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10799:                                     $group);
1.749     raeburn  10800:     } else {
                   10801:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10802:     }
1.749     raeburn  10803:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10804: }
                   10805: 
1.827     raeburn  10806: sub make_public_indefinitely {
                   10807:     my ($requrl) = @_;
                   10808:     my $now = time;
                   10809:     my $action = 'activate';
                   10810:     my $aclnum = 0;
                   10811:     if (&is_portfolio_url($requrl)) {
                   10812:         my (undef,$udom,$unum,$file_name,$group) =
                   10813:             &parse_portfolio_url($requrl);
                   10814:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10815:         my %access_controls = &get_access_controls($current_perms,
                   10816:                                                    $group,$file_name);
                   10817:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10818:             my ($num,$scope,$end,$start) = 
                   10819:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10820:             if ($scope eq 'public') {
                   10821:                 if ($start <= $now && $end == 0) {
                   10822:                     $action = 'none';
                   10823:                 } else {
                   10824:                     $action = 'update';
                   10825:                     $aclnum = $num;
                   10826:                 }
                   10827:                 last;
                   10828:             }
                   10829:         }
                   10830:         if ($action eq 'none') {
                   10831:              return 'ok';
                   10832:         } else {
                   10833:             my %changes;
                   10834:             my $newend = 0;
                   10835:             my $newstart = $now;
                   10836:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10837:             $changes{$action}{$newkey} = {
                   10838:                 type => 'public',
                   10839:                 time => {
                   10840:                     start => $newstart,
                   10841:                     end   => $newend,
                   10842:                 },
                   10843:             };
                   10844:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10845:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10846:             return $outcome;
                   10847:         }
                   10848:     } else {
                   10849:         return 'invalid';
                   10850:     }
                   10851: }
                   10852: 
1.745     raeburn  10853: #------------------------------------------------------Get Marked as Read Only
                   10854: 
                   10855: sub get_marked_as_readonly {
                   10856:     my ($domain,$user,$what,$group) = @_;
                   10857:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10858:     my @readonly_files;
1.629     banghart 10859:     my $cmp1=$what;
                   10860:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10861:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10862:         if (defined($group)) {
                   10863:             if ($file_name !~ m-^\Q$group\E/-) {
                   10864:                 next;
                   10865:             }
                   10866:         }
1.561     banghart 10867:         if (ref($value) eq "ARRAY"){
                   10868:             foreach my $stored_what (@{$value}) {
1.629     banghart 10869:                 my $cmp2=$stored_what;
1.759     albertel 10870:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10871:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10872:                 }
1.629     banghart 10873:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10874:                     push(@readonly_files, $file_name);
1.745     raeburn  10875:                     last;
1.563     banghart 10876:                 } elsif (!defined($what)) {
                   10877:                     push(@readonly_files, $file_name);
1.745     raeburn  10878:                     last;
1.561     banghart 10879:                 }
                   10880:             }
1.745     raeburn  10881:         }
1.561     banghart 10882:     }
                   10883:     return @readonly_files;
                   10884: }
1.577     banghart 10885: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10886: 
1.577     banghart 10887: sub get_marked_as_readonly_hash {
1.745     raeburn  10888:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10889:     my %readonly_files;
1.745     raeburn  10890:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10891:         if (defined($group)) {
                   10892:             if ($file_name !~ m-^\Q$group\E/-) {
                   10893:                 next;
                   10894:             }
                   10895:         }
1.577     banghart 10896:         if (ref($value) eq "ARRAY"){
                   10897:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10898:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10899:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10900:                         if ($lock_descriptor eq 'graded') {
                   10901:                             $readonly_files{$file_name} = 'graded';
                   10902:                         } elsif ($lock_descriptor eq 'handback') {
                   10903:                             $readonly_files{$file_name} = 'handback';
                   10904:                         } else {
                   10905:                             if (!exists($readonly_files{$file_name})) {
                   10906:                                 $readonly_files{$file_name} = 'locked';
                   10907:                             }
                   10908:                         }
1.745     raeburn  10909:                     }
1.750     banghart 10910:                 } 
1.577     banghart 10911:             }
                   10912:         } 
                   10913:     }
                   10914:     return %readonly_files;
                   10915: }
1.559     banghart 10916: # ------------------------------------------------------------ Unmark as Read Only
                   10917: 
                   10918: sub unmark_as_readonly {
1.629     banghart 10919:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10920:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10921:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10922:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10923:     my $symb_crs = $what;
                   10924:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10925:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10926:     my ($tmp)=keys(%current_permissions);
                   10927:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10928:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10929:     foreach my $file (@readonly_files) {
1.759     albertel 10930: 	my $clean_file = &declutter_portfile($file);
                   10931: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10932: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10933:         my @new_locks;
                   10934:         my @del_keys;
                   10935:         if (ref($current_locks) eq "ARRAY"){
                   10936:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10937:                 my $compare=$locker;
1.749     raeburn  10938:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10939:                     $compare=join('',@{$locker});
1.746     raeburn  10940:                     if ($compare ne $symb_crs) {
                   10941:                         push(@new_locks, $locker);
                   10942:                     }
1.563     banghart 10943:                 }
                   10944:             }
1.650     albertel 10945:             if (scalar(@new_locks) > 0) {
1.563     banghart 10946:                 $current_permissions{$file} = \@new_locks;
                   10947:             } else {
                   10948:                 push(@del_keys, $file);
1.613     albertel 10949:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10950:                 delete($current_permissions{$file});
1.563     banghart 10951:             }
                   10952:         }
1.561     banghart 10953:     }
1.613     albertel 10954:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10955:     return;
                   10956: }
1.512     banghart 10957: 
1.17      www      10958: # ------------------------------------------------------------ Directory lister
                   10959: 
                   10960: sub dirlist {
1.955     raeburn  10961:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10962:     $uri=~s/^\///;
                   10963:     $uri=~s/\/$//;
1.253     stredwic 10964:     my ($udom, $uname);
1.955     raeburn  10965:     if ($getuserdir) {
1.253     stredwic 10966:         $udom = $userdomain;
                   10967:         $uname = $username;
1.955     raeburn  10968:     } else {
                   10969:         (undef,$udom,$uname)=split(/\//,$uri);
                   10970:         if(defined($userdomain)) {
                   10971:             $udom = $userdomain;
                   10972:         }
                   10973:         if(defined($username)) {
                   10974:             $uname = $username;
                   10975:         }
1.253     stredwic 10976:     }
1.955     raeburn  10977:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10978: 
1.955     raeburn  10979:     $dirRoot = $perlvar{'lonDocRoot'};
                   10980:     if (defined($getpropath)) {
                   10981:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10982:         $dirRoot =~ s/\/$//;
1.955     raeburn  10983:     } elsif (defined($getuserdir)) {
                   10984:         my $subdir=$uname.'__';
                   10985:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10986:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10987:                    ."/$udom/$subdir/$uname";
                   10988:     } elsif (defined($alternateRoot)) {
                   10989:         $dirRoot = $alternateRoot;
1.751     banghart 10990:     }
1.253     stredwic 10991: 
                   10992:     if($udom) {
                   10993:         if($uname) {
1.1135    raeburn  10994:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10995:             if ($uhome eq 'no_host') {
                   10996:                 return ([],'no_host');
                   10997:             }
1.955     raeburn  10998:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10999:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11000:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11001:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11002:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11003:             } else {
                   11004:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11005:             }
1.605     matthew  11006:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11007:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11008:                 @listing_results = split(/:/,$listing);
                   11009:             } else {
                   11010:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11011:             }
1.1135    raeburn  11012:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11013:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11014:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11015:                 return ([],$listing);
                   11016:             } else {
                   11017:                 return (\@listing_results);
1.1135    raeburn  11018:             }
1.955     raeburn  11019:         } elsif(!$alternateRoot) {
1.1136    raeburn  11020:             my (%allusers,%listerror);
1.841     albertel 11021: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11022:  	    foreach my $tryserver (keys(%servers)) {
                   11023:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11024:                                   &escape($udom),$tryserver);
                   11025:                 if ($listing eq 'unknown_cmd') {
                   11026: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11027: 				      $udom, $tryserver);
                   11028:                 } else {
                   11029:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11030:                 }
1.841     albertel 11031: 		if ($listing eq 'unknown_cmd') {
                   11032: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11033: 				      $udom, $tryserver);
                   11034: 		    @listing_results = split(/:/,$listing);
                   11035: 		} else {
                   11036: 		    @listing_results =
                   11037: 			map { &unescape($_); } split(/:/,$listing);
                   11038: 		}
1.1136    raeburn  11039:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11040:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11041:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11042:                     $listerror{$tryserver} = $listing;
                   11043:                 } else {
1.841     albertel 11044: 		    foreach my $line (@listing_results) {
                   11045: 			my ($entry) = split(/&/,$line,2);
                   11046: 			$allusers{$entry} = 1;
                   11047: 		    }
                   11048: 		}
1.253     stredwic 11049:             }
1.1136    raeburn  11050:             my @alluserslist=();
1.800     albertel 11051:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11052:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11053:             }
1.1172.2.80  raeburn  11054:             if (!%listerror) {
                   11055:                 # no errors
                   11056:                 return (\@alluserslist);
                   11057:             } elsif (scalar(keys(%servers)) == 1) {
                   11058:                 # one library server, one error
                   11059:                 my ($key) = keys(%listerror);
                   11060:                 return (\@alluserslist, $listerror{$key});
                   11061:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11062:                 # con_lost indicates that we might miss data from at least one
                   11063:                 # library server
                   11064:                 return (\@alluserslist, 'con_lost');
                   11065:             } else {
                   11066:                 # multiple library servers and no con_lost -> data should be
                   11067:                 # complete.
                   11068:                 return (\@alluserslist);
                   11069:             }
                   11070: 
1.253     stredwic 11071:         } else {
1.1136    raeburn  11072:             return ([],'missing username');
1.253     stredwic 11073:         }
1.955     raeburn  11074:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11075:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11076:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11077:         return (\@all_domains);
1.955     raeburn  11078:     } else {
1.1136    raeburn  11079:         return ([],'missing domain');
1.275     stredwic 11080:     }
                   11081: }
                   11082: 
                   11083: # --------------------------------------------- GetFileTimestamp
                   11084: # This function utilizes dirlist and returns the date stamp for
                   11085: # when it was last modified.  It will also return an error of -1
                   11086: # if an error occurs
                   11087: 
                   11088: sub GetFileTimestamp {
1.955     raeburn  11089:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11090:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11091:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11092:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11093:                                     undef,$getuserdir);
                   11094:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11095:         return -1;
                   11096:     }
                   11097:     if (ref($fileref) eq 'ARRAY') {
                   11098:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11099:         # @stats contains first the filename, then the stat output
                   11100:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11101:     } else {
                   11102:         return -1;
1.253     stredwic 11103:     }
1.26      www      11104: }
                   11105: 
1.712     albertel 11106: sub stat_file {
                   11107:     my ($uri) = @_;
1.787     albertel 11108:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11109: 
1.955     raeburn  11110:     my ($udom,$uname,$file);
1.712     albertel 11111:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11112: 	($udom,$uname,$file) =
1.811     albertel 11113: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11114: 	$file = 'userfiles/'.$file;
                   11115:     }
                   11116:     if ($uri =~ m-^/res/-) {
                   11117: 	($udom,$uname) = 
1.807     albertel 11118: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11119: 	$file = $uri;
                   11120:     }
                   11121: 
                   11122:     if (!$udom || !$uname || !$file) {
                   11123: 	# unable to handle the uri
                   11124: 	return ();
                   11125:     }
1.956     raeburn  11126:     my $getpropath;
                   11127:     if ($file =~ /^userfiles\//) {
                   11128:         $getpropath = 1;
                   11129:     }
1.1136    raeburn  11130:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11131:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11132:         return ();
                   11133:     } else {
                   11134:         if (ref($listref) eq 'ARRAY') {
                   11135:             my @stats = split('&',$listref->[0]);
                   11136: 	    shift(@stats); #filename is first
                   11137: 	    return @stats;
                   11138:         }
1.712     albertel 11139:     }
                   11140:     return ();
                   11141: }
                   11142: 
1.26      www      11143: # -------------------------------------------------------- Value of a Condition
                   11144: 
1.713     albertel 11145: # gets the value of a specific preevaluated condition
                   11146: #    stored in the string  $env{user.state.<cid>}
                   11147: # or looks up a condition reference in the bighash and if if hasn't
                   11148: # already been evaluated recurses into docondval to get the value of
                   11149: # the condition, then memoizing it to 
                   11150: #   $env{user.state.<cid>.<condition>}
1.40      www      11151: sub directcondval {
                   11152:     my $number=shift;
1.620     albertel 11153:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11154: 	&Apache::lonuserstate::evalstate();
                   11155:     }
1.713     albertel 11156:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11157: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11158:     } elsif ($number =~ /^_/) {
                   11159: 	my $sub_condition;
                   11160: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11161: 		&GDBM_READER(),0640)) {
                   11162: 	    $sub_condition=$bighash{'conditions'.$number};
                   11163: 	    untie(%bighash);
                   11164: 	}
                   11165: 	my $value = &docondval($sub_condition);
1.949     raeburn  11166: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11167: 	return $value;
                   11168:     }
1.620     albertel 11169:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11170:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11171:     } else {
                   11172:        return 2;
                   11173:     }
                   11174: }
                   11175: 
1.713     albertel 11176: # get the collection of conditions for this resource
1.26      www      11177: sub condval {
                   11178:     my $condidx=shift;
1.54      www      11179:     my $allpathcond='';
1.713     albertel 11180:     foreach my $cond (split(/\|/,$condidx)) {
                   11181: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11182: 	    $allpathcond.=
                   11183: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11184: 	}
1.191     harris41 11185:     }
1.54      www      11186:     $allpathcond=~s/\|$//;
1.713     albertel 11187:     return &docondval($allpathcond);
                   11188: }
                   11189: 
                   11190: #evaluates an expression of conditions
                   11191: sub docondval {
                   11192:     my ($allpathcond) = @_;
                   11193:     my $result=0;
                   11194:     if ($env{'request.course.id'}
                   11195: 	&& defined($allpathcond)) {
                   11196: 	my $operand='|';
                   11197: 	my @stack;
                   11198: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11199: 	    if ($chunk eq '(') {
                   11200: 		push @stack,($operand,$result);
                   11201: 	    } elsif ($chunk eq ')') {
                   11202: 		my $before=pop @stack;
                   11203: 		if (pop @stack eq '&') {
                   11204: 		    $result=$result>$before?$before:$result;
                   11205: 		} else {
                   11206: 		    $result=$result>$before?$result:$before;
                   11207: 		}
                   11208: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11209: 		$operand=$chunk;
                   11210: 	    } else {
                   11211: 		my $new=directcondval($chunk);
                   11212: 		if ($operand eq '&') {
                   11213: 		    $result=$result>$new?$new:$result;
                   11214: 		} else {
                   11215: 		    $result=$result>$new?$result:$new;
                   11216: 		}
                   11217: 	    }
                   11218: 	}
1.26      www      11219:     }
                   11220:     return $result;
1.421     albertel 11221: }
                   11222: 
                   11223: # ---------------------------------------------------- Devalidate courseresdata
                   11224: 
                   11225: sub devalidatecourseresdata {
                   11226:     my ($coursenum,$coursedomain)=@_;
                   11227:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11228:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11229: }
                   11230: 
1.763     www      11231: 
1.200     www      11232: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11233: #
                   11234: #  Parameters:
                   11235: #      $coursenum    - Number of the course.
                   11236: #      $coursedomain - Domain at which the course was created.
                   11237: #  Returns:
                   11238: #     A hash of the course parameters along (I think) with timestamps
                   11239: #     and version info.
1.877     foxr     11240: 
1.624     albertel 11241: sub get_courseresdata {
                   11242:     my ($coursenum,$coursedomain)=@_;
1.200     www      11243:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11244:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11245:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11246:     my %dumpreply;
1.417     albertel 11247:     unless (defined($cached)) {
1.624     albertel 11248: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11249: 	$result=\%dumpreply;
1.251     albertel 11250: 	my ($tmp) = keys(%dumpreply);
                   11251: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11252: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11253: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11254: 	    return $tmp;
1.416     albertel 11255: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11256: 	    $result=undef;
1.599     albertel 11257: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11258: 	}
                   11259:     }
1.624     albertel 11260:     return $result;
                   11261: }
                   11262: 
1.633     albertel 11263: sub devalidateuserresdata {
                   11264:     my ($uname,$udom)=@_;
                   11265:     my $hashid="$udom:$uname";
                   11266:     &devalidate_cache_new('userres',$hashid);
                   11267: }
                   11268: 
1.624     albertel 11269: sub get_userresdata {
                   11270:     my ($uname,$udom)=@_;
                   11271:     #most student don\'t have any data set, check if there is some data
                   11272:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11273: 
                   11274:     my $hashid="$udom:$uname";
                   11275:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11276:     if (!defined($cached)) {
                   11277: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11278: 	$result=\%resourcedata;
                   11279: 	&do_cache_new('userres',$hashid,$result,600);
                   11280:     }
                   11281:     my ($tmp)=keys(%$result);
                   11282:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11283: 	return $result;
                   11284:     }
                   11285:     #error 2 occurs when the .db doesn't exist
                   11286:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11287:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11288: 	    &logthis("<font color=\"blue\">WARNING:".
                   11289: 		     " Trying to get resource data for ".
                   11290: 		     $uname." at ".$udom.": ".
                   11291: 		     $tmp."</font>");
                   11292:         }
1.624     albertel 11293:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11294: 	#&EXT_cache_set($udom,$uname);
                   11295: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11296: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11297:     }
                   11298:     return $tmp;
                   11299: }
1.879     foxr     11300: #----------------------------------------------- resdata - return resource data
                   11301: #  Purpose:
                   11302: #    Return resource data for either users or for a course.
                   11303: #  Parameters:
                   11304: #     $name      - Course/user name.
                   11305: #     $domain    - Name of the domain the user/course is registered on.
1.1172.2.118.  .1(raebu 11306:20): #     $type      - Type of thing $name is (must be 'course' or 'user')
1.879     foxr     11307: #     @which     - Array of names of resources desired.
                   11308: #  Returns:
                   11309: #     The value of the first reasource in @which that is found in the
                   11310: #     resource hash.
                   11311: #  Exceptional Conditions:
                   11312: #     If the $type passed in is not valid (not the string 'course' or 
                   11313: #     'user', an undefined  reference is returned.
                   11314: #     If none of the resources are found, an undef is returned
1.624     albertel 11315: sub resdata {
                   11316:     my ($name,$domain,$type,@which)=@_;
                   11317:     my $result;
                   11318:     if ($type eq 'course') {
                   11319: 	$result=&get_courseresdata($name,$domain);
                   11320:     } elsif ($type eq 'user') {
                   11321: 	$result=&get_userresdata($name,$domain);
                   11322:     }
                   11323:     if (!ref($result)) { return $result; }    
1.251     albertel 11324:     foreach my $item (@which) {
1.1172.2.118.  .1(raebu 11325:20):         if (ref($item) eq 'ARRAY') {
                   11326:20): 	    if (defined($result->{$item->[0]})) {
                   11327:20): 	        return [$result->{$item->[0]},$item->[1]];
                   11328:20): 	    }
                   11329:20):         }
1.250     albertel 11330:     }
1.291     albertel 11331:     return undef;
1.200     www      11332: }
                   11333: 
1.1172.2.118.  .1(raebu 11334:20): sub get_domain_ltitools {
                   11335:20):     my ($cdom) = @_;
                   11336:20):     my %ltitools;
                   11337:20):     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
                   11338:20):     if (defined($cached)) {
                   11339:20):         if (ref($result) eq 'HASH') {
                   11340:20):             %ltitools = %{$result};
                   11341:20):         }
                   11342:20):     } else {
                   11343:20):         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
                   11344:20):         if (ref($domconfig{'ltitools'}) eq 'HASH') {
                   11345:20):             %ltitools = %{$domconfig{'ltitools'}};
                   11346:20):             my %encdomconfig = &get_dom('encconfig',['ltitools'],$cdom);
                   11347:20):             if (ref($encdomconfig{'ltitools'}) eq 'HASH') {
                   11348:20):                 foreach my $id (keys(%ltitools)) {
                   11349:20):                     if (ref($encdomconfig{'ltitools'}{$id}) eq 'HASH') {
                   11350:20):                         foreach my $item ('key','secret') {
                   11351:20):                             $ltitools{$id}{$item} = $encdomconfig{'ltitools'}{$id}{$item};
                   11352:20):                         }
                   11353:20):                     }
                   11354:20):                 }
                   11355:20):             }
                   11356:20):         }
                   11357:20):         my $cachetime = 24*60*60;
                   11358:20):         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
                   11359:20):     }
                   11360:20):     return %ltitools;
                   11361:20): }
                   11362:20): 
1.1172.2.31  raeburn  11363: sub get_numsuppfiles {
                   11364:     my ($cnum,$cdom,$ignorecache)=@_;
                   11365:     my $hashid=$cnum.':'.$cdom;
                   11366:     my ($suppcount,$cached);
                   11367:     unless ($ignorecache) {
                   11368:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11369:     }
                   11370:     unless (defined($cached)) {
                   11371:         my $chome=&homeserver($cnum,$cdom);
                   11372:         unless ($chome eq 'no_host') {
                   11373:             ($suppcount,my $errors) = (0,0);
                   11374:             my $suppmap = 'supplemental.sequence';
                   11375:             ($suppcount,$errors) =
                   11376:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11377:         }
                   11378:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11379:     }
                   11380:     return $suppcount;
                   11381: }
                   11382: 
1.379     matthew  11383: #
                   11384: # EXT resource caching routines
                   11385: #
                   11386: 
                   11387: sub clear_EXT_cache_status {
1.383     albertel 11388:     &delenv('cache.EXT.');
1.379     matthew  11389: }
                   11390: 
                   11391: sub EXT_cache_status {
                   11392:     my ($target_domain,$target_user) = @_;
1.383     albertel 11393:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11394:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11395:         # We know already the user has no data
                   11396:         return 1;
                   11397:     } else {
                   11398:         return 0;
                   11399:     }
                   11400: }
                   11401: 
                   11402: sub EXT_cache_set {
                   11403:     my ($target_domain,$target_user) = @_;
1.383     albertel 11404:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11405:     #&appenv({$cachename => time});
1.379     matthew  11406: }
                   11407: 
1.28      www      11408: # --------------------------------------------------------- Value of a Variable
1.58      www      11409: sub EXT {
1.715     albertel 11410: 
1.1172.2.28  raeburn  11411:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11412:     unless ($varname) { return ''; }
1.218     albertel 11413:     #get real user name/domain, courseid and symb
                   11414:     my $courseid;
1.359     albertel 11415:     my $publicuser;
1.427     www      11416:     if ($symbparm) {
                   11417: 	$symbparm=&get_symb_from_alias($symbparm);
                   11418:     }
1.218     albertel 11419:     if (!($uname && $udom)) {
1.790     albertel 11420:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11421:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11422:     } else {
1.620     albertel 11423: 	$courseid=$env{'request.course.id'};
1.218     albertel 11424:     }
1.48      www      11425:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11426:     my $rest;
1.320     albertel 11427:     if (defined($therest[0])) {
1.48      www      11428:        $rest=join('.',@therest);
                   11429:     } else {
                   11430:        $rest='';
                   11431:     }
1.320     albertel 11432: 
1.57      www      11433:     my $qualifierrest=$qualifier;
                   11434:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11435:     my $spacequalifierrest=$space;
                   11436:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11437:     if ($realm eq 'user') {
1.48      www      11438: # --------------------------------------------------------------- user.resource
                   11439: 	if ($space eq 'resource') {
1.651     albertel 11440: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11441: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11442: 		 &&
1.744     albertel 11443: 		 ($symbparm eq &symbread()) ) {	
                   11444: 		# if we are in the middle of processing the resource the
                   11445: 		# get the value we are planning on committing
                   11446:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11447:                     return $Apache::lonhomework::results{$qualifierrest};
                   11448:                 } else {
                   11449:                     return $Apache::lonhomework::history{$qualifierrest};
                   11450:                 }
1.335     albertel 11451: 	    } else {
1.359     albertel 11452: 		my %restored;
1.620     albertel 11453: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11454: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11455: 		} else {
                   11456: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11457: 		}
1.335     albertel 11458: 		return $restored{$qualifierrest};
                   11459: 	    }
1.48      www      11460: # ----------------------------------------------------------------- user.access
                   11461:         } elsif ($space eq 'access') {
1.218     albertel 11462: 	    # FIXME - not supporting calls for a specific user
1.48      www      11463:             return &allowed($qualifier,$rest);
                   11464: # ------------------------------------------ user.preferences, user.environment
                   11465:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11466: 	    if (($uname eq $env{'user.name'}) &&
                   11467: 		($udom eq $env{'user.domain'})) {
                   11468: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11469: 	    } else {
1.359     albertel 11470: 		my %returnhash;
                   11471: 		if (!$publicuser) {
                   11472: 		    %returnhash=&userenvironment($udom,$uname,
                   11473: 						 $qualifierrest);
                   11474: 		}
1.218     albertel 11475: 		return $returnhash{$qualifierrest};
                   11476: 	    }
1.48      www      11477: # ----------------------------------------------------------------- user.course
                   11478:         } elsif ($space eq 'course') {
1.218     albertel 11479: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11480:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11481: # ------------------------------------------------------------------- user.role
                   11482:         } elsif ($space eq 'role') {
1.218     albertel 11483: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11484:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11485:             if ($qualifier eq 'value') {
                   11486: 		return $role;
                   11487:             } elsif ($qualifier eq 'extent') {
                   11488:                 return $where;
                   11489:             }
                   11490: # ----------------------------------------------------------------- user.domain
                   11491:         } elsif ($space eq 'domain') {
1.218     albertel 11492:             return $udom;
1.48      www      11493: # ------------------------------------------------------------------- user.name
                   11494:         } elsif ($space eq 'name') {
1.218     albertel 11495:             return $uname;
1.48      www      11496: # ---------------------------------------------------- Any other user namespace
1.29      www      11497:         } else {
1.359     albertel 11498: 	    my %reply;
                   11499: 	    if (!$publicuser) {
                   11500: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11501: 	    }
                   11502: 	    return $reply{$qualifierrest};
1.48      www      11503:         }
1.236     www      11504:     } elsif ($realm eq 'query') {
                   11505: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11506:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11507: 						[$spacequalifierrest]);
1.620     albertel 11508: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11509:    } elsif ($realm eq 'request') {
1.48      www      11510: # ------------------------------------------------------------- request.browser
                   11511:         if ($space eq 'browser') {
1.1145    bisitz   11512:             return $env{'browser.'.$qualifier};
1.57      www      11513: # ------------------------------------------------------------ request.filename
                   11514:         } else {
1.620     albertel 11515:             return $env{'request.'.$spacequalifierrest};
1.29      www      11516:         }
1.28      www      11517:     } elsif ($realm eq 'course') {
1.48      www      11518: # ---------------------------------------------------------- course.description
1.620     albertel 11519:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11520:     } elsif ($realm eq 'resource') {
1.165     www      11521: 
1.620     albertel 11522: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11523: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11524: 	}
1.693     albertel 11525: 
1.1172.2.30  raeburn  11526:         if ($qualifier eq '') {
                   11527: 	    if ($space eq 'title') {
                   11528: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11529: 	        return &gettitle($symbparm);
                   11530: 	    }
1.693     albertel 11531: 	
1.1172.2.30  raeburn  11532: 	    if ($space eq 'map') {
                   11533: 	        my ($map) = &decode_symb($symbparm);
                   11534: 	        return &symbread($map);
                   11535: 	    }
                   11536:             if ($space eq 'maptitle') {
                   11537:                 my ($map) = &decode_symb($symbparm);
                   11538:                 return &gettitle($map);
                   11539:             }
                   11540: 	    if ($space eq 'filename') {
                   11541: 	        if ($symbparm) {
                   11542: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11543: 	        }
                   11544: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11545: 	    }
1.1172.2.30  raeburn  11546: 
                   11547:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11548:                 if ($space eq 'visibleparts') {
                   11549:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11550:                     my $item;
                   11551:                     if (ref($navmap)) {
                   11552:                         my $res = $navmap->getBySymb($symbparm);
                   11553:                         my $parts = $res->parts();
                   11554:                         if (ref($parts) eq 'ARRAY') {
                   11555:                             $item = join(',',@{$parts});
                   11556:                         }
                   11557:                         undef($navmap);
                   11558:                     }
                   11559:                     return $item;
                   11560:                 }
                   11561:             }
                   11562:         }
1.693     albertel 11563: 
                   11564: 	my ($section, $group, @groups);
1.593     albertel 11565: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  11566:         if (($courseid eq '') && ($cid)) {
                   11567:             $courseid = $cid;
                   11568:         }
                   11569: 	if (($symbparm && $courseid) && 
                   11570: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      11571: 
1.218     albertel 11572: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11573: 
1.60      www      11574: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11575: 	    my $symbp=$symbparm;
1.735     albertel 11576: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11577: 
                   11578: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   11579: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   11580: 
1.620     albertel 11581: 	    if (($env{'user.name'} eq $uname) &&
                   11582: 		($env{'user.domain'} eq $udom)) {
                   11583: 		$section=$env{'request.course.sec'};
1.733     raeburn  11584:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11585:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11586: 	    } else {
1.539     albertel 11587: 		if (! defined($usection)) {
1.551     albertel 11588: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11589: 		} else {
                   11590: 		    $section = $usection;
                   11591: 		}
1.733     raeburn  11592:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11593: 	    }
                   11594: 
                   11595: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11596: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   11597: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11598: 
1.593     albertel 11599: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11600: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 11601: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11602: 
1.60      www      11603: # ----------------------------------------------------------- first, check user
1.624     albertel 11604: 
                   11605: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 11606: 				       ([$courselevelr,'resource'],
                   11607: 					[$courselevelm,'map'     ],
                   11608: 					[$courselevel, 'course'  ]));
1.931     albertel 11609: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11610: 
1.594     albertel 11611: # ------------------------------------------------ second, check some of course
1.684     raeburn  11612:             my $coursereply;
1.691     raeburn  11613:             if (@groups > 0) {
                   11614:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   11615:                                        $mapparm,$spacequalifierrest);
1.927     albertel 11616:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  11617:             }
1.96      www      11618: 
1.684     raeburn  11619: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11620: 				  $env{'course.'.$courseid.'.domain'},
                   11621: 				  'course',
                   11622: 				  ([$seclevelr,   'resource'],
                   11623: 				   [$seclevelm,   'map'     ],
                   11624: 				   [$seclevel,    'course'  ],
                   11625: 				   [$courselevelr,'resource']));
                   11626: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11627: 
1.60      www      11628: # ------------------------------------------------------ third, check map parms
1.218     albertel 11629: 	    my %parmhash=();
                   11630: 	    my $thisparm='';
                   11631: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11632: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11633: 		    &GDBM_READER(),0640)) {
1.218     albertel 11634: 		$thisparm=$parmhash{$symbparm};
                   11635: 		untie(%parmhash);
                   11636: 	    }
1.927     albertel 11637: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11638: 	}
1.594     albertel 11639: # ------------------------------------------ fourth, look in resource metadata
1.71      www      11640: 
1.218     albertel 11641: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 11642: 	my $filename;
                   11643: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11644: 	if ($symbparm) {
1.409     www      11645: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11646: 	} else {
1.620     albertel 11647: 	    $filename=$env{'request.filename'};
1.282     albertel 11648: 	}
                   11649: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 11650: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 11651: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 11652: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11653: 
1.927     albertel 11654: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 11655: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11656: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11657: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11658: 				     $env{'course.'.$courseid.'.domain'},
                   11659: 				     'course',
1.927     albertel 11660: 				     ([$courselevelm,'map'   ],
                   11661: 				      [$courselevel, 'course']));
                   11662: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11663: 	}
1.145     www      11664: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11665: 	unless ($space eq '0') {
1.336     albertel 11666: 	    my @parts=split(/_/,$space);
                   11667: 	    my $id=pop(@parts);
                   11668: 	    my $part=join('_',@parts);
                   11669: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11670: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11671: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11672: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11673: 	}
1.395     albertel 11674: 	if ($recurse) { return undef; }
                   11675: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11676: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11677: # ---------------------------------------------------- Any other user namespace
                   11678:     } elsif ($realm eq 'environment') {
                   11679: # ----------------------------------------------------------------- environment
1.620     albertel 11680: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11681: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11682: 	} else {
1.770     albertel 11683: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11684: 		return '';
                   11685: 	    }
1.219     albertel 11686: 	    my %returnhash=&userenvironment($udom,$uname,
                   11687: 					    $spacequalifierrest);
                   11688: 	    return $returnhash{$spacequalifierrest};
                   11689: 	}
1.28      www      11690:     } elsif ($realm eq 'system') {
1.48      www      11691: # ----------------------------------------------------------------- system.time
                   11692: 	if ($space eq 'time') {
                   11693: 	    return time;
                   11694:         }
1.696     albertel 11695:     } elsif ($realm eq 'server') {
                   11696: # ----------------------------------------------------------------- system.time
                   11697: 	if ($space eq 'name') {
                   11698: 	    return $ENV{'SERVER_NAME'};
                   11699:         }
1.28      www      11700:     }
1.48      www      11701:     return '';
1.61      www      11702: }
                   11703: 
1.927     albertel 11704: sub get_reply {
                   11705:     my ($reply_value) = @_;
1.940     raeburn  11706:     if (ref($reply_value) eq 'ARRAY') {
                   11707:         if (wantarray) {
                   11708: 	    return @$reply_value;
                   11709:         }
                   11710:         return $reply_value->[0];
                   11711:     } else {
                   11712:         return $reply_value;
1.927     albertel 11713:     }
                   11714: }
                   11715: 
1.691     raeburn  11716: sub check_group_parms {
                   11717:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11718:     my @groupitems = ();
                   11719:     my $resultitem;
1.927     albertel 11720:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11721:     foreach my $group (@{$groups}) {
                   11722:         foreach my $level (@levels) {
1.927     albertel 11723:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11724:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11725:         }
                   11726:     }
                   11727:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11728:                             $env{'course.'.$courseid.'.domain'},
                   11729:                                      'course',@groupitems);
                   11730:     return $coursereply;
                   11731: }
                   11732: 
                   11733: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11734:     my ($courseid,@groups) = @_;
                   11735:     @groups = sort(@groups);
1.691     raeburn  11736:     return @groups;
                   11737: }
                   11738: 
1.395     albertel 11739: sub packages_tab_default {
                   11740:     my ($uri,$varname)=@_;
                   11741:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11742: 
                   11743:     my (@extension,@specifics,$do_default);
                   11744:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11745: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11746: 	if ($pack_type eq 'default') {
                   11747: 	    $do_default=1;
                   11748: 	} elsif ($pack_type eq 'extension') {
                   11749: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11750: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11751: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11752: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11753: 	}
                   11754:     }
                   11755:     # first look for a package that matches the requested part id
                   11756:     foreach my $package (@specifics) {
                   11757: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11758: 	next if ($pack_part ne $part);
                   11759: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11760: 	    return $packagetab{"$pack_type&$name&default"};
                   11761: 	}
                   11762:     }
                   11763:     # look for any possible matching non extension_ package
                   11764:     foreach my $package (@specifics) {
                   11765: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11766: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11767: 	    return $packagetab{"$pack_type&$name&default"};
                   11768: 	}
1.585     albertel 11769: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11770: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11771: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11772: 	}
                   11773:     }
1.738     albertel 11774:     # look for any posible extension_ match
                   11775:     foreach my $package (@extension) {
                   11776: 	my ($package,$pack_type)=@{$package};
                   11777: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11778: 	    return $packagetab{"$pack_type&$name&default"};
                   11779: 	}
                   11780: 	if (defined($packagetab{$package."&$name&default"})) {
                   11781: 	    return $packagetab{$package."&$name&default"};
                   11782: 	}
                   11783:     }
                   11784:     # look for a global default setting
                   11785:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11786: 	return $packagetab{"default&$name&default"};
                   11787:     }
1.395     albertel 11788:     return undef;
                   11789: }
                   11790: 
1.334     albertel 11791: sub add_prefix_and_part {
                   11792:     my ($prefix,$part)=@_;
                   11793:     my $keyroot;
                   11794:     if (defined($prefix) && $prefix !~ /^__/) {
                   11795: 	# prefix that has a part already
                   11796: 	$keyroot=$prefix;
                   11797:     } elsif (defined($prefix)) {
                   11798: 	# prefix that is missing a part
                   11799: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11800:     } else {
                   11801: 	# no prefix at all
                   11802: 	if (defined($part)) { $keyroot='_'.$part; }
                   11803:     }
                   11804:     return $keyroot;
                   11805: }
                   11806: 
1.71      www      11807: # ---------------------------------------------------------------- Get metadata
                   11808: 
1.599     albertel 11809: my %metaentry;
1.1070    www      11810: my %importedpartids;
1.1172.2.99  raeburn  11811: my %importedrespids;
1.71      www      11812: sub metadata {
1.176     www      11813:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11814:     $uri=&declutter($uri);
1.288     albertel 11815:     # if it is a non metadata possible uri return quickly
1.529     albertel 11816:     if (($uri eq '') || 
                   11817: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.118.  .1(raebu 11818:20): 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  11819:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11820: 	return undef;
                   11821:     }
1.1172.2.49  raeburn  11822:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11823: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11824: 	return undef;
1.288     albertel 11825:     }
1.73      www      11826:     my $filename=$uri;
                   11827:     $uri=~s/\.meta$//;
1.172     www      11828: #
                   11829: # Is the metadata already cached?
1.177     www      11830: # Look at timestamp of caching
1.172     www      11831: # Everything is cached by the main uri, libraries are never directly cached
                   11832: #
1.428     albertel 11833:     if (!defined($liburi)) {
1.599     albertel 11834: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11835: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11836:     }
                   11837:     {
1.1069    www      11838: # Imported parts would go here
1.1172.2.99  raeburn  11839:         my @origfiletagids=();
1.1069    www      11840:         my $importedparts=0;
1.1172.2.99  raeburn  11841: 
                   11842: # Imported responseids would go here
                   11843:         my $importedresponses=0;
1.172     www      11844: #
                   11845: # Is this a recursive call for a library?
                   11846: #
1.599     albertel 11847: #	if (! exists($metacache{$uri})) {
                   11848: #	    $metacache{$uri}={};
                   11849: #	}
1.924     albertel 11850: 	my $cachetime = 60*60;
1.171     www      11851:         if ($liburi) {
                   11852: 	    $liburi=&declutter($liburi);
                   11853:             $filename=$liburi;
1.401     bowersj2 11854:         } else {
1.599     albertel 11855: 	    &devalidate_cache_new('meta',$uri);
                   11856: 	    undef(%metaentry);
1.401     bowersj2 11857: 	}
1.140     www      11858:         my %metathesekeys=();
1.73      www      11859:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11860: 	my $metastring;
1.1140    www      11861: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11862: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11863: 	    $metastring = 
1.929     albertel 11864: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11865: 					  ('grade_target' => 'meta'));
                   11866: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11867: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11868:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11869: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11870: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11871: 	    $metastring=&getfile($file);
1.489     albertel 11872: 	}
1.208     albertel 11873:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11874:         my $token;
1.140     www      11875:         undef %metathesekeys;
1.71      www      11876:         while ($token=$parser->get_token) {
1.339     albertel 11877: 	    if ($token->[0] eq 'S') {
                   11878: 		if (defined($token->[2]->{'package'})) {
1.172     www      11879: #
                   11880: # This is a package - get package info
                   11881: #
1.339     albertel 11882: 		    my $package=$token->[2]->{'package'};
                   11883: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11884: 		    if (defined($token->[2]->{'id'})) { 
                   11885: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11886: 		    }
1.599     albertel 11887: 		    if ($metaentry{':packages'}) {
                   11888: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11889: 		    } else {
1.599     albertel 11890: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11891: 		    }
1.736     albertel 11892: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11893: 			my $part=$keyroot;
                   11894: 			$part=~s/^\_//;
1.736     albertel 11895: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11896: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11897: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11898: 			    # ignore package.tab specified default values
                   11899:                             # here &package_tab_default() will fetch those
                   11900: 			    if ($subp eq 'default') { next; }
1.736     albertel 11901: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11902: 			    my $unikey;
                   11903: 			    if ($pack =~ /_0$/) {
                   11904: 				$unikey='parameter_0_'.$name;
                   11905: 				$part=0;
                   11906: 			    } else {
                   11907: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11908: 			    }
1.339     albertel 11909: 			    if ($subp eq 'display') {
                   11910: 				$value.=' [Part: '.$part.']';
                   11911: 			    }
1.599     albertel 11912: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11913: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11914: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11915: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11916: 			    }
1.599     albertel 11917: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11918: 				$metaentry{':'.$unikey}=
                   11919: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11920: 			    }
1.339     albertel 11921: 			}
                   11922: 		    }
                   11923: 		} else {
1.172     www      11924: #
                   11925: # This is not a package - some other kind of start tag
1.339     albertel 11926: #
                   11927: 		    my $entry=$token->[1];
1.1068    www      11928: 		    my $unikey='';
1.175     www      11929: 
1.339     albertel 11930: 		    if ($entry eq 'import') {
1.175     www      11931: #
                   11932: # Importing a library here
1.339     albertel 11933: #
1.1067    www      11934:                         my $location=$parser->get_text('/import');
                   11935:                         my $dir=$filename;
                   11936:                         $dir=~s|[^/]*$||;
                   11937:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  11938: 
                   11939:                         my $importid=$token->[2]->{'id'};
1.1068    www      11940:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  11941: #
                   11942: # Check metadata for imported file to
                   11943: # see if it contained response items
                   11944: #
                   11945:                         my %currmetaentry = %metaentry;
                   11946:                         my $libresponseorder = &metadata($location,'responseorder');
                   11947:                         my $origfile;
                   11948:                         if ($libresponseorder ne '') {
                   11949:                             if ($#origfiletagids<0) {
                   11950:                                 undef(%importedrespids);
                   11951:                                 undef(%importedpartids);
                   11952:                             }
                   11953:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   11954:                             if (@{$importedrespids{$importid}} > 0) {
                   11955:                                 $importedresponses = 1;
                   11956: # We need to get the original file and the imported file to get the response order correct
                   11957: # Load and inspect original file
                   11958:                                 if ($#origfiletagids<0) {
                   11959:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11960:                                     $origfile=&getfile($origfilelocation);
                   11961:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11962:                                 }
                   11963:                             }
                   11964:                         }
                   11965: # Do not overwrite contents of %metaentry hash for resource itself with 
                   11966: # hash populated for imported library file
                   11967:                         %metaentry = %currmetaentry;
                   11968:                         undef(%currmetaentry);
1.1068    www      11969:                         if ($importmode eq 'problem') {
1.1069    www      11970: # Import as problem/response
1.1068    www      11971:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11972:                         } elsif ($importmode eq 'part') {
                   11973: # Import as part(s)
1.1069    www      11974:                            $importedparts=1;
                   11975: # We need to get the original file and the imported file to get the part order correct
                   11976: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  11977: # Load and inspect original file if we didn't do that already
                   11978:                            if ($#origfiletagids<0) {
                   11979:                                undef(%importedrespids);
                   11980:                                undef(%importedpartids);
                   11981:                                if ($origfile eq '') {
                   11982:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11983:                                    $origfile=&getfile($origfilelocation);
                   11984:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11985:                                }
1.1070    www      11986:                            }
                   11987: 
1.1069    www      11988: # Load and inspect imported file
                   11989:                            my $impfile=&getfile($location);
                   11990:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11991:                            if ($#impfilepartids>=0) {
                   11992: # This problem had parts
1.1070    www      11993:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11994:                            } else {
                   11995: # Importing by turning a single problem into a problem part
                   11996: # It gets the import-tags ID as part-ID
                   11997:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11998:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11999:                            }
1.1068    www      12000:                         } else {
                   12001: # Normal import
                   12002:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12003:                            if (defined($token->[2]->{'id'})) {
                   12004:                               $unikey.='_'.$token->[2]->{'id'};
                   12005:                            }
1.1067    www      12006:                         }
                   12007: 
1.339     albertel 12008: 			if ($depthcount<20) {
1.736     albertel 12009: 			    my $metadata = 
                   12010: 				&metadata($uri,'keys', $location,$unikey,
                   12011: 					  $depthcount+1);
                   12012: 			    foreach my $meta (split(',',$metadata)) {
                   12013: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12014: 				$metathesekeys{$meta}=1;
1.339     albertel 12015: 			    }
1.1068    www      12016: 			
                   12017:                         }
1.1067    www      12018: 		    } else {
                   12019: #
                   12020: # Not importing, some other kind of non-package, non-library start tag
                   12021: # 
                   12022:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12023:                         if (defined($token->[2]->{'id'})) {
                   12024:                             $unikey.='_'.$token->[2]->{'id'};
                   12025:                         }
1.339     albertel 12026: 			if (defined($token->[2]->{'name'})) { 
                   12027: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12028: 			}
                   12029: 			$metathesekeys{$unikey}=1;
1.736     albertel 12030: 			foreach my $param (@{$token->[3]}) {
                   12031: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12032: 				$token->[2]->{$param};
1.339     albertel 12033: 			}
                   12034: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12035: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12036: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12037: 		 # only ws inside the tag, and not in default, so use default
                   12038: 		 # as value
1.599     albertel 12039: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12040: 			} elsif ( $internaltext =~ /\S/ ) {
                   12041: 		  # something interesting inside the tag
                   12042: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12043: 			} else {
1.908     albertel 12044: 		  # no interesting values, don't set a default
1.339     albertel 12045: 			}
1.172     www      12046: # end of not-a-package not-a-library import
1.339     albertel 12047: 		    }
1.172     www      12048: # end of not-a-package start tag
1.339     albertel 12049: 		}
1.172     www      12050: # the next is the end of "start tag"
1.339     albertel 12051: 	    }
                   12052: 	}
1.483     albertel 12053: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12054: 	$extension = lc($extension);
                   12055: 	if ($extension eq 'htm') { $extension='html'; }
                   12056: 
1.737     albertel 12057: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12058: 	    #no specific packages #how's our extension
                   12059: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12060: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12061: 					 \%metathesekeys);
                   12062: 	}
1.883     albertel 12063: 
                   12064: 	if (!exists($metaentry{':packages'})
                   12065: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12066: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12067: 		#no specific packages well let's get default then
                   12068: 		if ($key!~/^default&/) { next; }
1.488     albertel 12069: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12070: 					     \%metathesekeys);
                   12071: 	    }
                   12072: 	}
1.338     www      12073: # are there custom rights to evaluate
1.599     albertel 12074: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12075: 
1.338     www      12076:     #
                   12077:     # Importing a rights file here
1.339     albertel 12078:     #
                   12079: 	    unless ($depthcount) {
1.599     albertel 12080: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12081: 		my $dir=$filename;
                   12082: 		$dir=~s|[^/]*$||;
                   12083: 		$location=&filelocation($dir,$location);
1.736     albertel 12084: 		my $rights_metadata =
                   12085: 		    &metadata($uri,'keys',$location,'_rights',
                   12086: 			      $depthcount+1);
                   12087: 		foreach my $rights (split(',',$rights_metadata)) {
                   12088: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12089: 		    $metathesekeys{$rights}=1;
1.339     albertel 12090: 		}
                   12091: 	    }
                   12092: 	}
1.737     albertel 12093: 	# uniqifiy package listing
                   12094: 	my %seen;
                   12095: 	my @uniq_packages =
                   12096: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12097: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12098: 
1.1172.2.99  raeburn  12099:         if (($importedresponses) || ($importedparts)) {
                   12100:             if ($importedparts) {
1.1070    www      12101: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  12102:                 $metaentry{':partorder'}='';
                   12103:                 $metathesekeys{'partorder'}=1;
                   12104:             }
                   12105:             if ($importedresponses) {
                   12106: # We had imported responses and need to rebuild responseorder
                   12107:                 $metaentry{':responseorder'}='';
                   12108:                 $metathesekeys{'responseorder'}=1;
                   12109:             }
                   12110:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12111:                 my $origid = $origfiletagids[$index+1];
                   12112:                 if ($origfiletagids[$index] eq 'part') {
                   12113: # Original part, part of the problem
                   12114:                     if ($importedparts) {
                   12115:                         $metaentry{':partorder'}.=','.$origid;
                   12116:                     }
                   12117:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12118:                     if ($importedparts) {
                   12119: # We have imported parts at this position
                   12120:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12121:                     }
                   12122:                     if ($importedresponses) {
                   12123: # We have imported responses at this position
                   12124:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   12125:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   12126:                         }
                   12127:                     }
                   12128:                 } else {
                   12129: # Original response item, part of the problem
                   12130:                     if ($importedresponses) {
                   12131:                         $metaentry{':responseorder'}.=','.$origid;
                   12132:                     }
                   12133:                 }
                   12134:             }
                   12135:             if ($importedparts) {
                   12136:                 $metaentry{':partorder'}=~s/^\,//;
                   12137:             }
                   12138:             if ($importedresponses) {
                   12139:                 $metaentry{':responseorder'}=~s/^\,//;
                   12140:             }
1.1070    www      12141:         }
                   12142: 
1.737     albertel 12143: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12144: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  12145: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 12146: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      12147: # this is the end of "was not already recently cached
1.71      www      12148:     }
1.599     albertel 12149:     return $metaentry{':'.$what};
1.261     albertel 12150: }
                   12151: 
1.488     albertel 12152: sub metadata_create_package_def {
1.483     albertel 12153:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12154:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12155:     if ($subp eq 'default') { next; }
                   12156:     
1.599     albertel 12157:     if (defined($metaentry{':packages'})) {
                   12158: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12159:     } else {
1.599     albertel 12160: 	$metaentry{':packages'}=$package;
1.483     albertel 12161:     }
                   12162:     my $value=$packagetab{$key};
                   12163:     my $unikey;
                   12164:     $unikey='parameter_0_'.$name;
1.599     albertel 12165:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12166:     $$metathesekeys{$unikey}=1;
1.599     albertel 12167:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12168: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12169:     }
1.599     albertel 12170:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12171: 	$metaentry{':'.$unikey}=
                   12172: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12173:     }
                   12174: }
                   12175: 
1.261     albertel 12176: sub metadata_generate_part0 {
                   12177:     my ($metadata,$metacache,$uri) = @_;
                   12178:     my %allnames;
1.737     albertel 12179:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12180: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12181: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12182: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12183: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12184: 	    $allnames{$name}=$part;
                   12185: 	  }
                   12186: 	}
                   12187:     }
                   12188:     foreach my $name (keys(%allnames)) {
                   12189:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12190:       my $key=":parameter_0_$name";
1.261     albertel 12191:       $$metacache{"$key.part"}='0';
                   12192:       $$metacache{"$key.name"}=$name;
1.428     albertel 12193:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12194: 					   $allnames{$name}.'_'.$name.
                   12195: 					   '.type'};
1.428     albertel 12196:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12197: 			     '.display'};
1.644     www      12198:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12199:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12200:       $$metacache{"$key.display"}=$olddis;
                   12201:     }
1.71      www      12202: }
                   12203: 
1.764     albertel 12204: # ------------------------------------------------------ Devalidate title cache
                   12205: 
                   12206: sub devalidate_title_cache {
                   12207:     my ($url)=@_;
                   12208:     if (!$env{'request.course.id'}) { return; }
                   12209:     my $symb=&symbread($url);
                   12210:     if (!$symb) { return; }
                   12211:     my $key=$env{'request.course.id'}."\0".$symb;
                   12212:     &devalidate_cache_new('title',$key);
                   12213: }
                   12214: 
1.1014    droeschl 12215: # ------------------------------------------------- Get the title of a course
                   12216: 
                   12217: sub current_course_title {
                   12218:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12219: }
1.301     www      12220: # ------------------------------------------------- Get the title of a resource
                   12221: 
                   12222: sub gettitle {
                   12223:     my $urlsymb=shift;
                   12224:     my $symb=&symbread($urlsymb);
1.534     albertel 12225:     if ($symb) {
1.620     albertel 12226: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12227: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12228: 	if (defined($cached)) { 
                   12229: 	    return $result;
                   12230: 	}
1.534     albertel 12231: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12232: 	my $title='';
1.907     albertel 12233: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12234: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12235: 	} else {
                   12236: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12237: 		    &GDBM_READER(),0640)) {
                   12238: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12239: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12240: 		untie(%bighash);
                   12241: 	    }
1.534     albertel 12242: 	}
                   12243: 	$title=~s/\&colon\;/\:/gs;
                   12244: 	if ($title) {
1.1159    www      12245: # Remember both $symb and $title for dynamic metadata
                   12246:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12247:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12248: # Cache this title and then return it
1.599     albertel 12249: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12250: 	}
                   12251: 	$urlsymb=$url;
                   12252:     }
                   12253:     my $title=&metadata($urlsymb,'title');
                   12254:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12255:     return $title;
1.301     www      12256: }
1.613     albertel 12257: 
1.614     albertel 12258: sub get_slot {
                   12259:     my ($which,$cnum,$cdom)=@_;
                   12260:     if (!$cnum || !$cdom) {
1.790     albertel 12261: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12262: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12263: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12264:     }
1.703     albertel 12265:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12266:     my %slotinfo;
                   12267:     if (exists($remembered{$key})) {
                   12268: 	$slotinfo{$which} = $remembered{$key};
                   12269:     } else {
                   12270: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12271: 	&Apache::lonhomework::showhash(%slotinfo);
                   12272: 	my ($tmp)=keys(%slotinfo);
                   12273: 	if ($tmp=~/^error:/) { return (); }
                   12274: 	$remembered{$key} = $slotinfo{$which};
                   12275:     }
1.616     albertel 12276:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12277: 	return %{$slotinfo{$which}};
                   12278:     }
                   12279:     return $slotinfo{$which};
1.614     albertel 12280: }
1.1150    raeburn  12281: 
                   12282: sub get_reservable_slots {
                   12283:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12284:     my $now = time;
                   12285:     my $reservable_info;
                   12286:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12287:     if (exists($remembered{$key})) {
                   12288:         $reservable_info = $remembered{$key};
                   12289:     } else {
                   12290:         my %resv;
                   12291:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12292:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12293:         $reservable_info = \%resv;
                   12294:         $remembered{$key} = $reservable_info;
                   12295:     }
                   12296:     return $reservable_info;
                   12297: }
                   12298: 
                   12299: sub get_course_slots {
                   12300:     my ($cnum,$cdom) = @_;
                   12301:     my $hashid=$cnum.':'.$cdom;
                   12302:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12303:     if (defined($cached)) {
                   12304:         if (ref($result) eq 'HASH') {
                   12305:             return %{$result};
                   12306:         }
                   12307:     } else {
                   12308:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12309:         my ($tmp) = keys(%slots);
                   12310:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12311:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12312:             return %slots;
                   12313:         }
                   12314:     }
                   12315:     return;
                   12316: }
                   12317: 
                   12318: sub devalidate_slots_cache {
                   12319:     my ($cnum,$cdom)=@_;
                   12320:     my $hashid=$cnum.':'.$cdom;
                   12321:     &devalidate_cache_new('allslots',$hashid);
                   12322: }
                   12323: 
1.1172.2.8  raeburn  12324: sub get_coursechange {
                   12325:     my ($cdom,$cnum) = @_;
                   12326:     if ($cdom eq '' || $cnum eq '') {
                   12327:         return unless ($env{'request.course.id'});
                   12328:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12329:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12330:     }
                   12331:     my $hashid=$cdom.'_'.$cnum;
                   12332:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12333:     if ((defined($cached)) && ($change ne '')) {
                   12334:         return $change;
                   12335:     } else {
                   12336:         my %crshash;
                   12337:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12338:         if ($crshash{'internal.contentchange'} eq '') {
                   12339:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12340:             if ($change eq '') {
                   12341:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12342:                 $change = $crshash{'internal.created'};
                   12343:             }
                   12344:         } else {
                   12345:             $change = $crshash{'internal.contentchange'};
                   12346:         }
                   12347:         my $cachetime = 600;
                   12348:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12349:     }
                   12350:     return $change;
                   12351: }
                   12352: 
                   12353: sub devalidate_coursechange_cache {
                   12354:     my ($cnum,$cdom)=@_;
                   12355:     my $hashid=$cnum.':'.$cdom;
                   12356:     &devalidate_cache_new('crschange',$hashid);
                   12357: }
                   12358: 
1.31      www      12359: # ------------------------------------------------- Update symbolic store links
                   12360: 
                   12361: sub symblist {
                   12362:     my ($mapname,%newhash)=@_;
1.438     www      12363:     $mapname=&deversion(&declutter($mapname));
1.31      www      12364:     my %hash;
1.620     albertel 12365:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12366:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12367:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12368: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12369: 		next if ($url eq 'last_known'
                   12370: 			 && $env{'form.no_update_last_known'});
                   12371: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12372: 						    $newhash{$url}->[1],
                   12373: 						    $newhash{$url}->[0]);
1.191     harris41 12374:             }
1.31      www      12375:             if (untie(%hash)) {
                   12376: 		return 'ok';
                   12377:             }
                   12378:         }
                   12379:     }
                   12380:     return 'error';
1.212     www      12381: }
                   12382: 
                   12383: # --------------------------------------------------------------- Verify a symb
                   12384: 
                   12385: sub symbverify {
1.1172.2.11  raeburn  12386:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12387:     my $thisfn=$thisurl;
1.439     www      12388:     $thisfn=&declutter($thisfn);
1.215     www      12389: # direct jump to resource in page or to a sequence - will construct own symbs
                   12390:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12391: # check URL part
1.409     www      12392:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12393: 
1.431     www      12394:     unless ($url eq $thisfn) { return 0; }
1.213     www      12395: 
1.216     www      12396:     $symb=&symbclean($symb);
1.510     www      12397:     $thisurl=&deversion($thisurl);
1.439     www      12398:     $thisfn=&deversion($thisfn);
1.213     www      12399: 
                   12400:     my %bighash;
                   12401:     my $okay=0;
1.431     www      12402: 
1.620     albertel 12403:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12404:                             &GDBM_READER(),0640)) {
1.1032    raeburn  12405:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12406:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  12407:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12408:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12409:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12410:             }
                   12411:         }
                   12412:         my $ids;
1.1172.2.118.  .5(raebu 12413:20):         if ($map =~ m{^uploaded/.+\.page$}) {
                   12414:20):             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13  raeburn  12415:         } else {
                   12416:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12417:         }
1.1102    raeburn  12418:         unless ($ids) {
1.1172.2.13  raeburn  12419:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  12420:             $ids=$bighash{$idkey};
1.216     www      12421:         }
                   12422:         if ($ids) {
                   12423: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  12424:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   12425:                 $symb =~ s/\?.+$//;
                   12426:             }
1.800     albertel 12427: 	    foreach my $id (split(/\,/,$ids)) {
                   12428: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12429:                if (
                   12430:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  12431:    eq $symb) {
1.1172.2.11  raeburn  12432:                    if (ref($encstate)) {
                   12433:                        $$encstate = $bighash{'encrypted_'.$id};
                   12434:                    }
1.1172.2.13  raeburn  12435:                    if (($env{'request.role.adv'}) ||
                   12436:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  12437:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  12438:                        $okay=1;
                   12439:                        last;
                   12440:                    }
                   12441:                }
                   12442:            }
1.216     www      12443:         }
1.213     www      12444: 	untie(%bighash);
                   12445:     }
                   12446:     return $okay;
1.31      www      12447: }
                   12448: 
1.210     www      12449: # --------------------------------------------------------------- Clean-up symb
                   12450: 
                   12451: sub symbclean {
                   12452:     my $symb=shift;
1.568     albertel 12453:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12454: # remove version from map
                   12455:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12456: 
1.210     www      12457: # remove version from URL
                   12458:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12459: 
1.507     www      12460: # remove wrapper
                   12461: 
1.510     www      12462:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12463:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12464:     return $symb;
1.409     www      12465: }
                   12466: 
                   12467: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12468: 
                   12469: sub encode_symb {
                   12470:     my ($map,$resid,$url)=@_;
                   12471:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12472: }
1.409     www      12473: 
                   12474: sub decode_symb {
1.568     albertel 12475:     my $symb=shift;
                   12476:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12477:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12478:     return (&fixversion($map),$resid,&fixversion($url));
                   12479: }
                   12480: 
                   12481: sub fixversion {
                   12482:     my $fn=shift;
1.609     banghart 12483:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12484:     my %bighash;
                   12485:     my $uri=&clutter($fn);
1.620     albertel 12486:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12487: # is this cached?
1.599     albertel 12488:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12489:     if (defined($cached)) { return $result; }
                   12490: # unfortunately not cached, or expired
1.620     albertel 12491:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12492: 	    &GDBM_READER(),0640)) {
                   12493:  	if ($bighash{'version_'.$uri}) {
                   12494:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12495:  	    unless (($version eq 'mostrecent') || 
                   12496: 		    ($version==&getversion($uri))) {
1.440     www      12497:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12498:  	    }
                   12499:  	}
                   12500:  	untie %bighash;
1.413     www      12501:     }
1.599     albertel 12502:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12503: }
                   12504: 
                   12505: sub deversion {
                   12506:     my $url=shift;
                   12507:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12508:     return $url;
1.210     www      12509: }
                   12510: 
1.31      www      12511: # ------------------------------------------------------ Return symb list entry
                   12512: 
                   12513: sub symbread {
1.1172.2.66  raeburn  12514:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1172.2.54  raeburn  12515:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.66  raeburn  12516:     if (defined($env{$cache_str})) {
                   12517:         if ($ignorecachednull) {
                   12518:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12519:         } else {
                   12520:             return $env{$cache_str};
                   12521:         }
                   12522:     }
1.242     www      12523: # no filename provided? try from environment
1.1172.2.54  raeburn  12524:     unless ($thisfn) {
1.620     albertel 12525:         if ($env{'request.symb'}) {
1.1172.2.13  raeburn  12526:             return $env{$cache_str}=&symbclean($env{'request.symb'});
                   12527:         }
                   12528:         $thisfn=$env{'request.filename'};
1.44      www      12529:     }
1.569     albertel 12530:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12531: # is that filename actually a symb? Verify, clean, and return
                   12532:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12533: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12534: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12535: 	}
1.242     www      12536:     }
1.44      www      12537:     $thisfn=declutter($thisfn);
1.31      www      12538:     my %hash;
1.37      www      12539:     my %bighash;
                   12540:     my $syval='';
1.620     albertel 12541:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12542:         my $targetfn = $thisfn;
1.609     banghart 12543:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12544:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12545:         }
1.687     albertel 12546: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12547: 	    $targetfn=$1;
                   12548: 	}
1.620     albertel 12549:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12550:                       &GDBM_READER(),0640)) {
1.481     raeburn  12551: 	    $syval=$hash{$targetfn};
1.37      www      12552:             untie(%hash);
                   12553:         }
                   12554: # ---------------------------------------------------------- There was an entry
                   12555:         if ($syval) {
1.601     albertel 12556: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12557: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12558: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12559: 		    #return $env{$cache_str}='';
1.601     albertel 12560: 		#}    
                   12561: 		#$syval.=$1;
                   12562: 	    #}
1.37      www      12563:         } else {
                   12564: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12565:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12566:                             &GDBM_READER(),0640)) {
1.37      www      12567: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12568:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12569:               unless ($ids) { 
                   12570:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12571:               }
                   12572:               unless ($ids) {
                   12573: # alias?
                   12574: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12575:               }
1.37      www      12576:               if ($ids) {
                   12577: # ------------------------------------------------------------------- Has ID(s)
                   12578:                  my @possibilities=split(/\,/,$ids);
1.39      www      12579:                  if ($#possibilities==0) {
                   12580: # ----------------------------------------------- There is only one possibility
1.37      www      12581: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12582: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12583: 						    $resid,$thisfn);
1.1172.2.66  raeburn  12584:                      if (ref($possibles) eq 'HASH') {
                   12585:                          $possibles->{$syval} = 1;
                   12586:                      }
                   12587:                      if ($checkforblock) {
                   12588:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12589:                          if (@blockers) {
                   12590:                              $syval = '';
                   12591:                              return;
                   12592:                          }
                   12593:                      }
                   12594:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      12595: # ------------------------------------------ There is more than one possibility
                   12596:                      my $realpossible=0;
1.800     albertel 12597:                      foreach my $id (@possibilities) {
                   12598: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  12599:                          my $canaccess;
                   12600:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12601:                              $canaccess = 1;
                   12602:                          } else {
                   12603:                              $canaccess = &allowed('bre',$file);
                   12604:                          }
                   12605:                          if ($canaccess) {
                   12606:          		     my ($mapid,$resid)=split(/\./,$id);
                   12607:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12608:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12609:                                                              $resid,$thisfn);
                   12610:                                  if (ref($possibles) eq 'HASH') {
                   12611:                                      $possibles->{$syval} = 1;
                   12612:                                  }
                   12613:                                  if ($checkforblock) {
                   12614:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12615:                                      unless (@blockers > 0) {
                   12616:                                          $syval = $poss_syval;
                   12617:                                          $realpossible++;
                   12618:                                      }
                   12619:                                  } else {
                   12620:                                      $syval = $poss_syval;
                   12621:                                      $realpossible++;
                   12622:                                  }
                   12623:                              }
1.39      www      12624: 			 }
1.191     harris41 12625:                      }
1.39      www      12626: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12627:                  } else {
                   12628:                      $syval='';
1.37      www      12629:                  }
                   12630: 	      }
1.1172.2.66  raeburn  12631:               untie(%bighash);
1.481     raeburn  12632:            }
1.31      www      12633:         }
1.62      www      12634:         if ($syval) {
1.620     albertel 12635: 	    return $env{$cache_str}=$syval;
1.62      www      12636:         }
1.31      www      12637:     }
1.949     raeburn  12638:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12639:     return $env{$cache_str}='';
1.31      www      12640: }
                   12641: 
                   12642: # ---------------------------------------------------------- Return random seed
                   12643: 
1.32      www      12644: sub numval {
                   12645:     my $txt=shift;
                   12646:     $txt=~tr/A-J/0-9/;
                   12647:     $txt=~tr/a-j/0-9/;
                   12648:     $txt=~tr/K-T/0-9/;
                   12649:     $txt=~tr/k-t/0-9/;
                   12650:     $txt=~tr/U-Z/0-5/;
                   12651:     $txt=~tr/u-z/0-5/;
                   12652:     $txt=~s/\D//g;
1.564     albertel 12653:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12654:     return int($txt);
1.368     albertel 12655: }
                   12656: 
1.484     albertel 12657: sub numval2 {
                   12658:     my $txt=shift;
                   12659:     $txt=~tr/A-J/0-9/;
                   12660:     $txt=~tr/a-j/0-9/;
                   12661:     $txt=~tr/K-T/0-9/;
                   12662:     $txt=~tr/k-t/0-9/;
                   12663:     $txt=~tr/U-Z/0-5/;
                   12664:     $txt=~tr/u-z/0-5/;
                   12665:     $txt=~s/\D//g;
                   12666:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12667:     my $total;
                   12668:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12669:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12670:     return int($total);
                   12671: }
                   12672: 
1.575     albertel 12673: sub numval3 {
                   12674:     use integer;
                   12675:     my $txt=shift;
                   12676:     $txt=~tr/A-J/0-9/;
                   12677:     $txt=~tr/a-j/0-9/;
                   12678:     $txt=~tr/K-T/0-9/;
                   12679:     $txt=~tr/k-t/0-9/;
                   12680:     $txt=~tr/U-Z/0-5/;
                   12681:     $txt=~tr/u-z/0-5/;
                   12682:     $txt=~s/\D//g;
                   12683:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12684:     my $total;
                   12685:     foreach my $val (@txts) { $total+=$val; }
                   12686:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12687:     return $total;
                   12688: }
                   12689: 
1.675     albertel 12690: sub digest {
                   12691:     my ($data)=@_;
                   12692:     my $digest=&Digest::MD5::md5($data);
                   12693:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12694:     my ($e,$f);
                   12695:     {
                   12696:         use integer;
                   12697:         $e=($a+$b);
                   12698:         $f=($c+$d);
                   12699:         if ($_64bit) {
                   12700:             $e=(($e<<32)>>32);
                   12701:             $f=(($f<<32)>>32);
                   12702:         }
                   12703:     }
                   12704:     if (wantarray) {
                   12705: 	return ($e,$f);
                   12706:     } else {
                   12707: 	my $g;
                   12708: 	{
                   12709: 	    use integer;
                   12710: 	    $g=($e+$f);
                   12711: 	    if ($_64bit) {
                   12712: 		$g=(($g<<32)>>32);
                   12713: 	    }
                   12714: 	}
                   12715: 	return $g;
                   12716:     }
                   12717: }
                   12718: 
1.368     albertel 12719: sub latest_rnd_algorithm_id {
1.675     albertel 12720:     return '64bit5';
1.366     albertel 12721: }
1.32      www      12722: 
1.503     albertel 12723: sub get_rand_alg {
                   12724:     my ($courseid)=@_;
1.790     albertel 12725:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12726:     if ($courseid) {
1.620     albertel 12727: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12728:     }
                   12729:     return &latest_rnd_algorithm_id();
                   12730: }
                   12731: 
1.562     albertel 12732: sub validCODE {
                   12733:     my ($CODE)=@_;
                   12734:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12735:     return 0;
                   12736: }
                   12737: 
1.491     albertel 12738: sub getCODE {
1.620     albertel 12739:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12740:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12741: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12742: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12743: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12744:     }
                   12745:     return undef;
                   12746: }
1.1133    foxr     12747: #
                   12748: #  Determines the random seed for a specific context:
                   12749: #
                   12750: # parameters:
                   12751: #   symb      - in course context the symb for the seed.
                   12752: #   course_id - The course id of the form domain_coursenum.
                   12753: #   domain    - Domain for the user.
                   12754: #   course    - Course for the user.
                   12755: #   cenv      - environment of the course.
                   12756: #
                   12757: # NOTE:
                   12758: #   All parameters are picked out of the environment if missing
                   12759: #   or not defined.
                   12760: #   If a symb cannot be determined the current time is used instead.
                   12761: #
                   12762: #  For a given well defined symb, courside, domain, username,
                   12763: #  and course environment, the seed is reproducible.
                   12764: #
1.31      www      12765: sub rndseed {
1.1133    foxr     12766:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12767:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12768:     if (!defined($symb)) {
1.366     albertel 12769: 	unless ($symb=$wsymb) { return time; }
                   12770:     }
1.1146    foxr     12771:     if (!defined $courseid) { 
                   12772: 	$courseid=$wcourseid; 
                   12773:     }
                   12774:     if (!defined $domain) { $domain=$wdomain; }
                   12775:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12776: 
                   12777:     my $which;
                   12778:     if (defined($cenv->{'rndseed'})) {
                   12779: 	$which = $cenv->{'rndseed'};
                   12780:     } else {
                   12781: 	$which =&get_rand_alg($courseid);
                   12782:     }
1.491     albertel 12783:     if (defined(&getCODE())) {
1.675     albertel 12784: 	if ($which eq '64bit5') {
                   12785: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12786: 	} elsif ($which eq '64bit4') {
1.575     albertel 12787: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12788: 	} else {
                   12789: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12790: 	}
1.675     albertel 12791:     } elsif ($which eq '64bit5') {
                   12792: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12793:     } elsif ($which eq '64bit4') {
                   12794: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12795:     } elsif ($which eq '64bit3') {
                   12796: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12797:     } elsif ($which eq '64bit2') {
                   12798: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12799:     } elsif ($which eq '64bit') {
                   12800: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12801:     }
                   12802:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12803: }
                   12804: 
                   12805: sub rndseed_32bit {
                   12806:     my ($symb,$courseid,$domain,$username)=@_;
                   12807:     {
                   12808: 	use integer;
                   12809: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12810: 	my $symbseed=numval($symb) << 22;
                   12811: 	my $namechck=unpack("%32C*",$username) << 17;
                   12812: 	my $nameseed=numval($username) << 12;
                   12813: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12814: 	my $courseseed=unpack("%32C*",$courseid);
                   12815: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12816: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12817: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12818: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12819: 	return $num;
                   12820:     }
                   12821: }
                   12822: 
                   12823: sub rndseed_64bit {
                   12824:     my ($symb,$courseid,$domain,$username)=@_;
                   12825:     {
                   12826: 	use integer;
                   12827: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12828: 	my $symbseed=numval($symb) << 10;
                   12829: 	my $namechck=unpack("%32S*",$username);
                   12830: 	
                   12831: 	my $nameseed=numval($username) << 21;
                   12832: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12833: 	my $courseseed=unpack("%32S*",$courseid);
                   12834: 	
                   12835: 	my $num1=$symbchck+$symbseed+$namechck;
                   12836: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12837: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12838: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12839: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12840: 	return "$num1,$num2";
1.155     albertel 12841:     }
1.366     albertel 12842: }
                   12843: 
1.443     albertel 12844: sub rndseed_64bit2 {
                   12845:     my ($symb,$courseid,$domain,$username)=@_;
                   12846:     {
                   12847: 	use integer;
                   12848: 	# strings need to be an even # of cahracters long, it it is odd the
                   12849:         # last characters gets thrown away
                   12850: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12851: 	my $symbseed=numval($symb) << 10;
                   12852: 	my $namechck=unpack("%32S*",$username.' ');
                   12853: 	
                   12854: 	my $nameseed=numval($username) << 21;
1.501     albertel 12855: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12856: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12857: 	
                   12858: 	my $num1=$symbchck+$symbseed+$namechck;
                   12859: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12860: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12861: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12862: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12863: 	return "$num1,$num2";
                   12864:     }
                   12865: }
                   12866: 
                   12867: sub rndseed_64bit3 {
                   12868:     my ($symb,$courseid,$domain,$username)=@_;
                   12869:     {
                   12870: 	use integer;
                   12871: 	# strings need to be an even # of cahracters long, it it is odd the
                   12872:         # last characters gets thrown away
                   12873: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12874: 	my $symbseed=numval2($symb) << 10;
                   12875: 	my $namechck=unpack("%32S*",$username.' ');
                   12876: 	
                   12877: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12878: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12879: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12880: 	
                   12881: 	my $num1=$symbchck+$symbseed+$namechck;
                   12882: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12883: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12884: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12885: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12886: 	
1.503     albertel 12887: 	return "$num1:$num2";
1.443     albertel 12888:     }
                   12889: }
                   12890: 
1.575     albertel 12891: sub rndseed_64bit4 {
                   12892:     my ($symb,$courseid,$domain,$username)=@_;
                   12893:     {
                   12894: 	use integer;
                   12895: 	# strings need to be an even # of cahracters long, it it is odd the
                   12896:         # last characters gets thrown away
                   12897: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12898: 	my $symbseed=numval3($symb) << 10;
                   12899: 	my $namechck=unpack("%32S*",$username.' ');
                   12900: 	
                   12901: 	my $nameseed=numval3($username) << 21;
                   12902: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12903: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12904: 	
                   12905: 	my $num1=$symbchck+$symbseed+$namechck;
                   12906: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12907: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12908: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12909: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12910: 	
1.575     albertel 12911: 	return "$num1:$num2";
                   12912:     }
                   12913: }
                   12914: 
1.675     albertel 12915: sub rndseed_64bit5 {
                   12916:     my ($symb,$courseid,$domain,$username)=@_;
                   12917:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12918:     return "$num1:$num2";
                   12919: }
                   12920: 
1.366     albertel 12921: sub rndseed_CODE_64bit {
                   12922:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12923:     {
1.366     albertel 12924: 	use integer;
1.443     albertel 12925: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12926: 	my $symbseed=numval2($symb);
1.491     albertel 12927: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12928: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12929: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12930: 	my $num1=$symbseed+$CODEchck;
                   12931: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12932: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12933: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12934: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12935: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12936: 	return "$num1:$num2";
1.366     albertel 12937:     }
                   12938: }
                   12939: 
1.575     albertel 12940: sub rndseed_CODE_64bit4 {
                   12941:     my ($symb,$courseid,$domain,$username)=@_;
                   12942:     {
                   12943: 	use integer;
                   12944: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12945: 	my $symbseed=numval3($symb);
                   12946: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12947: 	my $CODEseed=numval3(&getCODE());
                   12948: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12949: 	my $num1=$symbseed+$CODEchck;
                   12950: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12951: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12952: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12953: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12954: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12955: 	return "$num1:$num2";
                   12956:     }
                   12957: }
                   12958: 
1.675     albertel 12959: sub rndseed_CODE_64bit5 {
                   12960:     my ($symb,$courseid,$domain,$username)=@_;
                   12961:     my $code = &getCODE();
                   12962:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12963:     return "$num1:$num2";
                   12964: }
                   12965: 
1.366     albertel 12966: sub setup_random_from_rndseed {
                   12967:     my ($rndseed)=@_;
1.503     albertel 12968:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  12969: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12970:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12971:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12972:         } else {
                   12973:             &Math::Random::random_set_seed($num1,$num2);
                   12974:         }
1.366     albertel 12975:     } else {
                   12976: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12977:     }
1.36      albertel 12978: }
                   12979: 
1.474     albertel 12980: sub latest_receipt_algorithm_id {
1.835     albertel 12981:     return 'receipt3';
1.474     albertel 12982: }
                   12983: 
1.480     www      12984: sub recunique {
                   12985:     my $fucourseid=shift;
                   12986:     my $unique;
1.835     albertel 12987:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12988: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12989: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12990:     } else {
                   12991: 	$unique=$perlvar{'lonReceipt'};
                   12992:     }
                   12993:     return unpack("%32C*",$unique);
                   12994: }
                   12995: 
                   12996: sub recprefix {
                   12997:     my $fucourseid=shift;
                   12998:     my $prefix;
1.835     albertel 12999:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13000: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13001: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13002:     } else {
                   13003: 	$prefix=$perlvar{'lonHostID'};
                   13004:     }
                   13005:     return unpack("%32C*",$prefix);
                   13006: }
                   13007: 
1.76      www      13008: sub ireceipt {
1.474     albertel 13009:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13010: 
                   13011:     my $return =&recprefix($fucourseid).'-';
                   13012: 
                   13013:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13014: 	$env{'request.state'} eq 'construct') {
                   13015: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13016: 	return $return;
                   13017:     }
                   13018: 
1.76      www      13019:     my $cuname=unpack("%32C*",$funame);
                   13020:     my $cudom=unpack("%32C*",$fudom);
                   13021:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13022:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13023:     my $cunique=&recunique($fucourseid);
1.474     albertel 13024:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13025:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13026: 
1.790     albertel 13027: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13028: 			       
                   13029: 	$return.= ($cunique%$cuname+
                   13030: 		   $cunique%$cudom+
                   13031: 		   $cusymb%$cuname+
                   13032: 		   $cusymb%$cudom+
                   13033: 		   $cucourseid%$cuname+
                   13034: 		   $cucourseid%$cudom+
                   13035: 		   $cpart%$cuname+
                   13036: 		   $cpart%$cudom);
                   13037:     } else {
                   13038: 	$return.= ($cunique%$cuname+
                   13039: 		   $cunique%$cudom+
                   13040: 		   $cusymb%$cuname+
                   13041: 		   $cusymb%$cudom+
                   13042: 		   $cucourseid%$cuname+
                   13043: 		   $cucourseid%$cudom);
                   13044:     }
                   13045:     return $return;
1.76      www      13046: }
                   13047: 
                   13048: sub receipt {
1.474     albertel 13049:     my ($part)=@_;
1.790     albertel 13050:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13051:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13052: }
1.260     ng       13053: 
1.790     albertel 13054: sub whichuser {
                   13055:     my ($passedsymb)=@_;
                   13056:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13057:     if (defined($env{'form.grade_symb'})) {
                   13058: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13059: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13060: 	if (!$allowed &&
                   13061: 	    exists($env{'request.course.sec'}) &&
                   13062: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13063: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13064: 			      '/'.$env{'request.course.sec'});
                   13065: 	}
                   13066: 	if ($allowed) {
                   13067: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13068: 	    $courseid=$tmp_courseid;
                   13069: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13070: 	    ($name)=&get_env_multiple('form.grade_username');
                   13071: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13072: 	}
                   13073:     }
                   13074:     if (!$passedsymb) {
                   13075: 	$symb=&symbread();
                   13076:     } else {
                   13077: 	$symb=$passedsymb;
                   13078:     }
                   13079:     $courseid=$env{'request.course.id'};
                   13080:     $domain=$env{'user.domain'};
                   13081:     $name=$env{'user.name'};
                   13082:     if ($name eq 'public' && $domain eq 'public') {
                   13083: 	if (!defined($env{'form.username'})) {
                   13084: 	    $env{'form.username'}.=time.rand(10000000);
                   13085: 	}
                   13086: 	$name.=$env{'form.username'};
                   13087:     }
                   13088:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13089: 
                   13090: }
                   13091: 
1.36      albertel 13092: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13093: # returns either the contents of the file or 
                   13094: # -1 if the file doesn't exist
1.481     raeburn  13095: #
                   13096: # if the target is a file that was uploaded via DOCS, 
                   13097: # a check will be made to see if a current copy exists on the local server,
                   13098: # if it does this will be served, otherwise a copy will be retrieved from
                   13099: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13100: # the local server.   
1.472     albertel 13101: 
1.36      albertel 13102: sub getfile {
1.538     albertel 13103:     my ($file) = @_;
1.609     banghart 13104:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13105:     &repcopy($file);
                   13106:     return &readfile($file);
                   13107: }
                   13108: 
                   13109: sub repcopy_userfile {
                   13110:     my ($file)=@_;
1.1142    raeburn  13111:     my $londocroot = $perlvar{'lonDocRoot'};
                   13112:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13113:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13114:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13115: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13116:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13117:     if (-e "$file") {
1.828     www      13118: # we already have a local copy, check it out
1.538     albertel 13119: 	my @fileinfo = stat($file);
1.828     www      13120: 	my $rtncode;
                   13121: 	my $info;
1.538     albertel 13122: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13123: 	if ($lwpresp ne 'ok') {
1.828     www      13124: # there is no such file anymore, even though we had a local copy
1.482     albertel 13125: 	    if ($rtncode eq '404') {
1.538     albertel 13126: 		unlink($file);
1.482     albertel 13127: 	    }
                   13128: 	    return -1;
                   13129: 	}
                   13130: 	if ($info < $fileinfo[9]) {
1.828     www      13131: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13132: 	    return 'ok';
1.828     www      13133: 	} else {
                   13134: # the file is outdated, get rid of it
                   13135: 	    unlink($file);
1.482     albertel 13136: 	}
1.828     www      13137:     }
                   13138: # one way or the other, at this point, we don't have the file
                   13139: # construct the correct path for the file
                   13140:     my @parts = ($cdom,$cnum); 
                   13141:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13142: 	push @parts, split(/\//,$1);
                   13143:     }
                   13144:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13145:     foreach my $part (@parts) {
                   13146: 	$path .= '/'.$part;
                   13147: 	if (!-e $path) {
                   13148: 	    mkdir($path,0770);
1.482     albertel 13149: 	}
                   13150:     }
1.828     www      13151: # now the path exists for sure
                   13152: # get a user agent
                   13153:     my $ua=new LWP::UserAgent;
                   13154:     my $transferfile=$file.'.in.transfer';
                   13155: # FIXME: this should flock
                   13156:     if (-e $transferfile) { return 'ok'; }
                   13157:     my $request;
                   13158:     $uri=~s/^\///;
1.980     raeburn  13159:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.118.  .3(raebu 13160:20):     my $hostname = &hostname($homeserver);
1.980     raeburn  13161:     my $protocol = $protocol{$homeserver};
                   13162:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu 13163:20):     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      13164:     my $response=$ua->request($request,$transferfile);
                   13165: # did it work?
                   13166:     if ($response->is_error()) {
                   13167: 	unlink($transferfile);
                   13168: 	&logthis("Userfile repcopy failed for $uri");
                   13169: 	return -1;
                   13170:     }
                   13171: # worked, rename the transfer file
                   13172:     rename($transferfile,$file);
1.607     raeburn  13173:     return 'ok';
1.481     raeburn  13174: }
                   13175: 
1.517     albertel 13176: sub tokenwrapper {
                   13177:     my $uri=shift;
1.980     raeburn  13178:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13179:     $uri=~s|^/||;
1.620     albertel 13180:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13181:     my $token=$1;
1.552     albertel 13182:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13183:     if ($udom && $uname && $file) {
                   13184: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13185:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13186:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.118.  .3(raebu 13187:20):         my $hostname = &hostname($homeserver);
1.980     raeburn  13188:         my $protocol = $protocol{$homeserver};
                   13189:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu 13190:20):         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13191:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13192:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13193:     } else {
                   13194:         return '/adm/notfound.html';
                   13195:     }
                   13196: }
                   13197: 
1.828     www      13198: # call with reqtype HEAD: get last modification time
                   13199: # call with reqtype GET: get the file contents
                   13200: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13201: #
1.481     raeburn  13202: sub getuploaded {
                   13203:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13204:     $uri=~s/^\///;
1.980     raeburn  13205:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.118.  .3(raebu 13206:20):     my $hostname = &hostname($homeserver);
1.980     raeburn  13207:     my $protocol = $protocol{$homeserver};
                   13208:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu 13209:20):     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13210:     my $ua=new LWP::UserAgent;
                   13211:     my $request=new HTTP::Request($reqtype,$uri);
                   13212:     my $response=$ua->request($request);
                   13213:     $$rtncode = $response->code;
1.482     albertel 13214:     if (! $response->is_success()) {
                   13215: 	return 'failed';
                   13216:     }      
                   13217:     if ($reqtype eq 'HEAD') {
1.486     www      13218: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13219:     } elsif ($reqtype eq 'GET') {
                   13220: 	$$info = $response->content;
1.472     albertel 13221:     }
1.482     albertel 13222:     return 'ok';
1.36      albertel 13223: }
                   13224: 
1.481     raeburn  13225: sub readfile {
                   13226:     my $file = shift;
                   13227:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13228:     my $fh;
1.1172.2.96  raeburn  13229:     open($fh,"<",$file);
1.481     raeburn  13230:     my $a='';
1.800     albertel 13231:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13232:     return $a;
                   13233: }
                   13234: 
1.36      albertel 13235: sub filelocation {
1.590     banghart 13236:     my ($dir,$file) = @_;
                   13237:     my $location;
                   13238:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13239: 
                   13240:     if ($file =~ m-^/adm/-) {
                   13241: 	$file=~s-^/adm/wrapper/-/-;
                   13242: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13243:     }
1.882     albertel 13244: 
1.1139    www      13245:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13246:         $location = $file;
1.609     banghart 13247:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13248:         my ($udom,$uname,$filename)=
1.811     albertel 13249:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13250:         my $home=&homeserver($uname,$udom);
                   13251:         my $is_me=0;
                   13252:         my @ids=&current_machine_ids();
                   13253:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13254:         if ($is_me) {
1.1117    foxr     13255:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13256:         } else {
                   13257:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13258:   	      $udom.'/'.$uname.'/'.$filename;
                   13259:         }
1.882     albertel 13260:     } elsif ($file =~ m-^/adm/-) {
                   13261: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13262:     } else {
                   13263:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13264:         $file=~s:^/(res|priv)/:/:;
                   13265:         my $space=$1;
1.590     banghart 13266:         if ( !( $file =~ m:^/:) ) {
                   13267:             $location = $dir. '/'.$file;
                   13268:         } else {
1.1142    raeburn  13269:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13270:         }
1.59      albertel 13271:     }
1.590     banghart 13272:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13273:     while ($location=~m{/\.\./}) {
                   13274: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13275: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13276: 	} else {
                   13277: 	    $location=~ s{/\.\./}{/}g;
                   13278: 	}
                   13279:     } #remove dir/..
1.590     banghart 13280:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13281:     return $location;
1.46      www      13282: }
1.36      albertel 13283: 
1.46      www      13284: sub hreflocation {
                   13285:     my ($dir,$file)=@_;
1.980     raeburn  13286:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13287: 	$file=filelocation($dir,$file);
1.700     albertel 13288:     } elsif ($file=~m-^/adm/-) {
                   13289: 	$file=~s-^/adm/wrapper/-/-;
                   13290: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13291:     }
                   13292:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13293: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13294:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13295: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13296: 	        {/uploaded/$1/$2/}x;
1.46      www      13297:     }
1.913     albertel 13298:     if ($file=~ m{^/userfiles/}) {
                   13299: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13300:     }
1.462     albertel 13301:     return $file;
1.465     albertel 13302: }
                   13303: 
1.1139    www      13304: 
                   13305: 
                   13306: 
                   13307: 
1.465     albertel 13308: sub current_machine_domains {
1.853     albertel 13309:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13310: }
                   13311: 
                   13312: sub machine_domains {
                   13313:     my ($hostname) = @_;
1.465     albertel 13314:     my @domains;
1.838     albertel 13315:     my %hostname = &all_hostnames();
1.465     albertel 13316:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13317: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13318: 	if ($hostname eq $name) {
1.844     albertel 13319: 	    push(@domains,&host_domain($id));
1.465     albertel 13320: 	}
                   13321:     }
                   13322:     return @domains;
                   13323: }
                   13324: 
                   13325: sub current_machine_ids {
1.853     albertel 13326:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13327: }
                   13328: 
                   13329: sub machine_ids {
                   13330:     my ($hostname) = @_;
                   13331:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13332:     my @ids;
1.888     albertel 13333:     my %name_to_host = &all_names();
1.889     albertel 13334:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13335: 	return @{ $name_to_host{$hostname} };
                   13336:     }
                   13337:     return;
1.31      www      13338: }
                   13339: 
1.824     raeburn  13340: sub additional_machine_domains {
                   13341:     my @domains;
1.1172.2.96  raeburn  13342:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13343:     while( my $line = <$fh>) {
                   13344:         $line =~ s/\s//g;
                   13345:         push(@domains,$line);
                   13346:     }
                   13347:     return @domains;
                   13348: }
                   13349: 
                   13350: sub default_login_domain {
                   13351:     my $domain = $perlvar{'lonDefDomain'};
                   13352:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13353:     foreach my $posdom (&current_machine_domains(),
                   13354:                         &additional_machine_domains()) {
                   13355:         if (lc($posdom) eq lc($testdomain)) {
                   13356:             $domain=$posdom;
                   13357:             last;
                   13358:         }
                   13359:     }
                   13360:     return $domain;
                   13361: }
                   13362: 
1.1172.2.106  raeburn  13363: sub shared_institution {
                   13364:     my ($dom) = @_;
                   13365:     my $same_intdom;
                   13366:     my $hostintdom = &internet_dom($perlvar{'lonHostID'});
                   13367:     if ($hostintdom ne '') {
                   13368:         my %iphost = &get_iphost();
                   13369:         my $primary_id = &domain($dom,'primary');
                   13370:         my $primary_ip = &get_host_ip($primary_id);
                   13371:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   13372:             foreach my $id (@{$iphost{$primary_ip}}) {
                   13373:                 my $intdom = &internet_dom($id);
                   13374:                 if ($intdom eq $hostintdom) {
                   13375:                     $same_intdom = 1;
                   13376:                     last;
                   13377:                 }
                   13378:             }
                   13379:         }
                   13380:     }
                   13381:     return $same_intdom;
                   13382: }
                   13383: 
1.1172.2.118.  .3(raebu 13384:20): sub uses_sts {
                   13385:20):     my ($ignore_cache) = @_;
                   13386:20):     my $lonhost = $perlvar{'lonHostID'};
                   13387:20):     my $hostname = &hostname($lonhost);
                   13388:20):     my $sts_on;
                   13389:20):     if ($protocol{$lonhost} eq 'https') {
                   13390:20):         my $cachetime = 12*3600;
                   13391:20):         if (!$ignore_cache) {
                   13392:20):             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   13393:20):             if (defined($cached)) {
                   13394:20):                 return $sts_on;
                   13395:20):             }
                   13396:20):         }
          .4(raebu 13397:20):         my $ua=new LWP::UserAgent;
          .3(raebu 13398:20):         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   13399:20):         my $request=new HTTP::Request('HEAD',$url);
          .4(raebu 13400:20):         my $response=$ua->request($request);
          .3(raebu 13401:20):         if ($response->is_success) {
                   13402:20):             my $has_sts = $response->header('Strict-Transport-Security');
                   13403:20):             if ($has_sts eq '') {
                   13404:20):                 $sts_on = 0;
                   13405:20):             } else {
                   13406:20):                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   13407:20):                     my $maxage = $1;
                   13408:20):                     if ($maxage) {
                   13409:20):                         $sts_on = 1;
                   13410:20):                     } else {
                   13411:20):                         $sts_on = 0;
                   13412:20):                     }
                   13413:20):                 } else {
                   13414:20):                     $sts_on = 0;
                   13415:20):                 }
                   13416:20):             }
                   13417:20):             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   13418:20):         }
                   13419:20):     }
                   13420:20):     return;
                   13421:20): }
                   13422:20): 
1.31      www      13423: # ------------------------------------------------------------- Declutters URLs
                   13424: 
                   13425: sub declutter {
                   13426:     my $thisfn=shift;
1.569     albertel 13427:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  13428:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13429:         $thisfn=~s{^/home/httpd/html}{};
                   13430:     }
1.31      www      13431:     $thisfn=~s/^\///;
1.697     albertel 13432:     $thisfn=~s|^adm/wrapper/||;
                   13433:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13434:     $thisfn=~s/^res\///;
1.1172    bisitz   13435:     $thisfn=~s/^priv\///;
1.1032    raeburn  13436:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13437:         $thisfn=~s/\?.+$//;
                   13438:     }
1.268     www      13439:     return $thisfn;
                   13440: }
                   13441: 
                   13442: # ------------------------------------------------------------- Clutter up URLs
                   13443: 
                   13444: sub clutter {
                   13445:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13446:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13447: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13448:        $thisfn='/res'.$thisfn; 
                   13449:     }
1.1031    raeburn  13450:     if ($thisfn !~m|^/adm|) {
                   13451: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13452: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13453: 	} else {
                   13454: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13455: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13456: 	    if ($embstyle eq 'ssi'
                   13457: 		|| ($embstyle eq 'hdn')
                   13458: 		|| ($embstyle eq 'rat')
                   13459: 		|| ($embstyle eq 'prv')
                   13460: 		|| ($embstyle eq 'ign')) {
                   13461: 		#do nothing with these
                   13462: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13463: 		|| ($embstyle eq 'emb')
                   13464: 		|| ($embstyle eq 'wrp')) {
                   13465: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13466: 	    } elsif ($embstyle eq 'unk'
                   13467: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13468: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13469: 	    } else {
1.718     www      13470: #		&logthis("Got a blank emb style");
1.695     albertel 13471: 	    }
1.694     albertel 13472: 	}
1.1172.2.118.  .1(raebu 13473:20):     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
                   13474:20):         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 13475:     }
1.31      www      13476:     return $thisfn;
1.12      www      13477: }
                   13478: 
1.787     albertel 13479: sub clutter_with_no_wrapper {
                   13480:     my $uri = &clutter(shift);
                   13481:     if ($uri =~ m-^/adm/-) {
                   13482: 	$uri =~ s-^/adm/wrapper/-/-;
                   13483: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13484:     }
                   13485:     return $uri;
                   13486: }
                   13487: 
1.557     albertel 13488: sub freeze_escape {
                   13489:     my ($value)=@_;
                   13490:     if (ref($value)) {
                   13491: 	$value=&nfreeze($value);
                   13492: 	return '__FROZEN__'.&escape($value);
                   13493:     }
                   13494:     return &escape($value);
                   13495: }
                   13496: 
1.11      www      13497: 
1.557     albertel 13498: sub thaw_unescape {
                   13499:     my ($value)=@_;
                   13500:     if ($value =~ /^__FROZEN__/) {
                   13501: 	substr($value,0,10,undef);
                   13502: 	$value=&unescape($value);
                   13503: 	return &thaw($value);
                   13504:     }
                   13505:     return &unescape($value);
                   13506: }
                   13507: 
1.436     albertel 13508: sub correct_line_ends {
                   13509:     my ($result)=@_;
                   13510:     $$result =~s/\r\n/\n/mg;
                   13511:     $$result =~s/\r/\n/mg;
1.415     albertel 13512: }
1.1       albertel 13513: # ================================================================ Main Program
                   13514: 
1.184     www      13515: sub goodbye {
1.204     albertel 13516:    &logthis("Starting Shut down");
1.443     albertel 13517: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13518:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13519: #converted
1.599     albertel 13520: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13521:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13522: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13523: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13524: #1.1 only
1.870     albertel 13525: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13526: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13527: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13528: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13529:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13530:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13531:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13532:    &flushcourselogs();
                   13533:    &logthis("Shutting down");
                   13534: }
                   13535: 
1.852     albertel 13536: sub get_dns {
1.1172.2.17  raeburn  13537:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13538:     if (!$ignore_cache) {
                   13539: 	my ($content,$cached)=
                   13540: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13541: 	if ($cached) {
1.1172.2.17  raeburn  13542: 	    &$func($content,$hashref);
1.869     albertel 13543: 	    return;
                   13544: 	}
                   13545:     }
                   13546: 
                   13547:     my %alldns;
1.1172.2.96  raeburn  13548:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13549:         foreach my $dns (<$config>) {
                   13550: 	    next if ($dns !~ /^\^(\S*)/x);
                   13551:             my $line = $1;
                   13552:             my ($host,$protocol) = split(/:/,$line);
                   13553:             if ($protocol ne 'https') {
                   13554:                 $protocol = 'http';
                   13555:             }
                   13556: 	    $alldns{$host} = $protocol;
1.979     raeburn  13557:         }
1.1172.2.96  raeburn  13558:         close($config);
1.869     albertel 13559:     }
                   13560:     while (%alldns) {
1.1172.2.52  raeburn  13561: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 13562: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  13563:         $ua->timeout(30);
1.979     raeburn  13564: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 13565: 	my $response=$ua->request($request);
1.979     raeburn  13566:         delete($alldns{$dns});
1.852     albertel 13567: 	next if ($response->is_error());
                   13568: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  13569:         unless ($nocache) {
1.1172.2.23  raeburn  13570: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  13571:         }
                   13572: 	&$func(\@content,$hashref);
1.869     albertel 13573: 	return;
1.852     albertel 13574:     }
1.871     albertel 13575:     my $which = (split('/',$url))[3];
                   13576:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  13577:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13578:         my @content = <$config>;
                   13579:         &$func(\@content,$hashref);
                   13580:     }
1.1172.2.17  raeburn  13581:     return;
                   13582: }
                   13583: 
                   13584: # ------------------------------------------------------Get DNS checksums file
                   13585: sub parse_dns_checksums_tab {
                   13586:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  13587:     my $lonhost = $perlvar{'lonHostID'};
                   13588:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  13589:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  13590:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13591:     my $webconfdir = '/etc/httpd/conf';
                   13592:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13593:         $webconfdir = '/etc/apache2';
                   13594:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13595:         if ($1 >= 10) {
                   13596:             $webconfdir = '/etc/apache2';
                   13597:         }
                   13598:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13599:         if ($1 >= 10.0) {
                   13600:             $webconfdir = '/etc/apache2';
                   13601:         }
                   13602:     }
1.1172.2.17  raeburn  13603:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13604:     my (%chksum,%revnum);
                   13605:     if (ref($lines) eq 'ARRAY') {
                   13606:         chomp(@{$lines});
1.1172.2.34  raeburn  13607:         my $version = shift(@{$lines});
                   13608:         if ($version eq $release) {
1.1172.2.17  raeburn  13609:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  13610:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  13611:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13612:                     if ($webconfdir eq '/etc/apache2') {
                   13613:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13614:                     }
                   13615:                 }
1.1172.2.34  raeburn  13616:                 $chksum{$file} = $shasum;
                   13617:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  13618:             }
                   13619:             if (ref($hashref) eq 'HASH') {
                   13620:                 %{$hashref} = (
                   13621:                                 sums     => \%chksum,
                   13622:                                 versions => \%revnum,
                   13623:                               );
                   13624:             }
                   13625:         }
                   13626:     }
1.869     albertel 13627:     return;
1.852     albertel 13628: }
1.1172.2.17  raeburn  13629: 
                   13630: sub fetch_dns_checksums {
                   13631:     my %checksums;
1.1172.2.34  raeburn  13632:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  13633:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  13634:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13635:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  13636:              \%checksums);
                   13637:     return \%checksums;
                   13638: }
                   13639: 
1.327     albertel 13640: # ------------------------------------------------------------ Read domain file
                   13641: {
1.852     albertel 13642:     my $loaded;
1.846     albertel 13643:     my %domain;
                   13644: 
1.852     albertel 13645:     sub parse_domain_tab {
                   13646: 	my ($lines) = @_;
                   13647: 	foreach my $line (@$lines) {
                   13648: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13649: 
1.846     albertel 13650: 	    chomp($line);
1.852     albertel 13651: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13652: 	    my %this_domain;
                   13653: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13654: 			       'lang_def', 'city', 'longi', 'lati',
                   13655: 			       'primary') {
                   13656: 		$this_domain{$field} = shift(@elements);
                   13657: 	    }
                   13658: 	    $domain{$name} = \%this_domain;
1.852     albertel 13659: 	}
                   13660:     }
1.864     albertel 13661: 
                   13662:     sub reset_domain_info {
                   13663: 	undef($loaded);
                   13664: 	undef(%domain);
                   13665:     }
                   13666: 
1.852     albertel 13667:     sub load_domain_tab {
1.1172.2.70  raeburn  13668: 	my ($ignore_cache,$nocache) = @_;
                   13669: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13670: 	my $fh;
1.1172.2.96  raeburn  13671: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13672: 	    my @lines = <$fh>;
                   13673: 	    &parse_domain_tab(\@lines);
1.448     albertel 13674: 	}
1.852     albertel 13675: 	close($fh);
                   13676: 	$loaded = 1;
1.327     albertel 13677:     }
1.846     albertel 13678: 
                   13679:     sub domain {
1.852     albertel 13680: 	&load_domain_tab() if (!$loaded);
                   13681: 
1.846     albertel 13682: 	my ($name,$what) = @_;
                   13683: 	return if ( !exists($domain{$name}) );
                   13684: 
                   13685: 	if (!$what) {
                   13686: 	    return $domain{$name}{'description'};
                   13687: 	}
                   13688: 	return $domain{$name}{$what};
                   13689:     }
1.974     raeburn  13690: 
                   13691:     sub domain_info {
                   13692:         &load_domain_tab() if (!$loaded);
                   13693:         return %domain;
                   13694:     }
                   13695: 
1.327     albertel 13696: }
                   13697: 
                   13698: 
1.1       albertel 13699: # ------------------------------------------------------------- Read hosts file
                   13700: {
1.838     albertel 13701:     my %hostname;
1.844     albertel 13702:     my %hostdom;
1.845     albertel 13703:     my %libserv;
1.852     albertel 13704:     my $loaded;
1.888     albertel 13705:     my %name_to_host;
1.1074    raeburn  13706:     my %internetdom;
1.1107    raeburn  13707:     my %LC_dns_serv;
1.852     albertel 13708: 
                   13709:     sub parse_hosts_tab {
                   13710: 	my ($file) = @_;
                   13711: 	foreach my $configline (@$file) {
                   13712: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13713:             chomp($configline);
                   13714: 	    if ($configline =~ /^\^/) {
                   13715:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13716:                     $LC_dns_serv{$1} = 1;
                   13717:                 }
                   13718:                 next;
                   13719:             }
1.1074    raeburn  13720: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13721: 	    $name=~s/\s//g;
                   13722: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  13723:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13724:                     my $curr = $hostname{$id};
                   13725:                     my $skip;
                   13726:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13727:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13728:                             $skip = 1;
                   13729:                         } else {
                   13730:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13731:                         }
                   13732:                     }
                   13733:                     unless ($skip) {
                   13734:                         push(@{$name_to_host{$name}},$id);
                   13735:                     }
                   13736:                 } else {
                   13737:                     push(@{$name_to_host{$name}},$id);
                   13738:                 }
1.852     albertel 13739: 		$hostname{$id}=$name;
                   13740: 		$hostdom{$id}=$domain;
                   13741: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13742:                 if (defined($protocol)) {
                   13743:                     if ($protocol eq 'https') {
                   13744:                         $protocol{$id} = $protocol;
                   13745:                     } else {
                   13746:                         $protocol{$id} = 'http'; 
                   13747:                     }
1.968     raeburn  13748:                 } else {
1.969     raeburn  13749:                     $protocol{$id} = 'http';
1.968     raeburn  13750:                 }
1.1074    raeburn  13751:                 if (defined($intdom)) {
                   13752:                     $internetdom{$id} = $intdom;
                   13753:                 }
1.852     albertel 13754: 	    }
                   13755: 	}
                   13756:     }
1.864     albertel 13757:     
                   13758:     sub reset_hosts_info {
1.897     albertel 13759: 	&purge_remembered();
1.864     albertel 13760: 	&reset_domain_info();
                   13761: 	&reset_hosts_ip_info();
1.892     albertel 13762: 	undef(%name_to_host);
1.864     albertel 13763: 	undef(%hostname);
                   13764: 	undef(%hostdom);
                   13765: 	undef(%libserv);
                   13766: 	undef($loaded);
                   13767:     }
1.1       albertel 13768: 
1.852     albertel 13769:     sub load_hosts_tab {
1.1172.2.70  raeburn  13770: 	my ($ignore_cache,$nocache) = @_;
                   13771: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  13772: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13773: 	my @config = <$config>;
                   13774: 	&parse_hosts_tab(\@config);
                   13775: 	close($config);
                   13776: 	$loaded=1;
1.1       albertel 13777:     }
1.852     albertel 13778: 
1.838     albertel 13779:     sub hostname {
1.852     albertel 13780: 	&load_hosts_tab() if (!$loaded);
                   13781: 
1.838     albertel 13782: 	my ($lonid) = @_;
                   13783: 	return $hostname{$lonid};
                   13784:     }
1.845     albertel 13785: 
1.838     albertel 13786:     sub all_hostnames {
1.852     albertel 13787: 	&load_hosts_tab() if (!$loaded);
                   13788: 
1.838     albertel 13789: 	return %hostname;
                   13790:     }
1.845     albertel 13791: 
1.888     albertel 13792:     sub all_names {
1.1172.2.70  raeburn  13793:         my ($ignore_cache,$nocache) = @_;
                   13794: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13795: 
                   13796: 	return %name_to_host;
                   13797:     }
                   13798: 
1.974     raeburn  13799:     sub all_host_domain {
                   13800:         &load_hosts_tab() if (!$loaded);
                   13801:         return %hostdom;
                   13802:     }
                   13803: 
1.845     albertel 13804:     sub is_library {
1.852     albertel 13805: 	&load_hosts_tab() if (!$loaded);
                   13806: 
1.845     albertel 13807: 	return exists($libserv{$_[0]});
                   13808:     }
                   13809: 
                   13810:     sub all_library {
1.852     albertel 13811: 	&load_hosts_tab() if (!$loaded);
                   13812: 
1.845     albertel 13813: 	return %libserv;
                   13814:     }
                   13815: 
1.1062    droeschl 13816:     sub unique_library {
                   13817: 	#2x reverse removes all hostnames that appear more than once
                   13818:         my %unique = reverse &all_library();
                   13819:         return reverse %unique;
                   13820:     }
                   13821: 
1.841     albertel 13822:     sub get_servers {
1.852     albertel 13823: 	&load_hosts_tab() if (!$loaded);
                   13824: 
1.841     albertel 13825: 	my ($domain,$type) = @_;
                   13826: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13827: 	                                          : %hostname;
                   13828: 	my %result;
1.842     albertel 13829: 	if (ref($domain) eq 'ARRAY') {
                   13830: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13831: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13832: 		    $result{$host} = $hostname;
                   13833: 		}
                   13834: 	    }
                   13835: 	} else {
                   13836: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13837: 		if ($hostdom{$host} eq $domain) {
                   13838: 		    $result{$host} = $hostname;
                   13839: 		}
1.841     albertel 13840: 	    }
                   13841: 	}
                   13842: 	return %result;
                   13843:     }
1.845     albertel 13844: 
1.1062    droeschl 13845:     sub get_unique_servers {
                   13846:         my %unique = reverse &get_servers(@_);
                   13847: 	return reverse %unique;
                   13848:     }
                   13849: 
1.844     albertel 13850:     sub host_domain {
1.852     albertel 13851: 	&load_hosts_tab() if (!$loaded);
                   13852: 
1.844     albertel 13853: 	my ($lonid) = @_;
                   13854: 	return $hostdom{$lonid};
                   13855:     }
                   13856: 
1.841     albertel 13857:     sub all_domains {
1.852     albertel 13858: 	&load_hosts_tab() if (!$loaded);
                   13859: 
1.841     albertel 13860: 	my %seen;
                   13861: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13862: 	return @uniq;
                   13863:     }
1.1074    raeburn  13864: 
                   13865:     sub internet_dom {
                   13866:         &load_hosts_tab() if (!$loaded);
                   13867: 
                   13868:         my ($lonid) = @_;
                   13869:         return $internetdom{$lonid};
                   13870:     }
1.1107    raeburn  13871: 
                   13872:     sub is_LC_dns {
                   13873:         &load_hosts_tab() if (!$loaded);
                   13874: 
                   13875:         my ($hostname) = @_;
                   13876:         return exists($LC_dns_serv{$hostname});
                   13877:     }
                   13878: 
1.1       albertel 13879: }
                   13880: 
1.847     albertel 13881: { 
                   13882:     my %iphost;
1.856     albertel 13883:     my %name_to_ip;
                   13884:     my %lonid_to_ip;
1.869     albertel 13885: 
1.847     albertel 13886:     sub get_hosts_from_ip {
                   13887: 	my ($ip) = @_;
                   13888: 	my %iphosts = &get_iphost();
                   13889: 	if (ref($iphosts{$ip})) {
                   13890: 	    return @{$iphosts{$ip}};
                   13891: 	}
                   13892: 	return;
1.839     albertel 13893:     }
1.864     albertel 13894:     
                   13895:     sub reset_hosts_ip_info {
                   13896: 	undef(%iphost);
                   13897: 	undef(%name_to_ip);
                   13898: 	undef(%lonid_to_ip);
                   13899:     }
1.856     albertel 13900: 
                   13901:     sub get_host_ip {
                   13902: 	my ($lonid) = @_;
                   13903: 	if (exists($lonid_to_ip{$lonid})) {
                   13904: 	    return $lonid_to_ip{$lonid};
                   13905: 	}
                   13906: 	my $name=&hostname($lonid);
                   13907:    	my $ip = gethostbyname($name);
                   13908: 	return if (!$ip || length($ip) ne 4);
                   13909: 	$ip=inet_ntoa($ip);
                   13910: 	$name_to_ip{$name}   = $ip;
                   13911: 	$lonid_to_ip{$lonid} = $ip;
                   13912: 	return $ip;
                   13913:     }
1.847     albertel 13914:     
                   13915:     sub get_iphost {
1.1172.2.70  raeburn  13916: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13917: 
1.869     albertel 13918: 	if (!$ignore_cache) {
                   13919: 	    if (%iphost) {
                   13920: 		return %iphost;
                   13921: 	    }
                   13922: 	    my ($ip_info,$cached)=
                   13923: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13924: 	    if ($cached) {
                   13925: 		%iphost      = %{$ip_info->[0]};
                   13926: 		%name_to_ip  = %{$ip_info->[1]};
                   13927: 		%lonid_to_ip = %{$ip_info->[2]};
                   13928: 		return %iphost;
                   13929: 	    }
                   13930: 	}
1.894     albertel 13931: 
                   13932: 	# get yesterday's info for fallback
                   13933: 	my %old_name_to_ip;
                   13934: 	my ($ip_info,$cached)=
                   13935: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13936: 	if ($cached) {
                   13937: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13938: 	}
                   13939: 
1.1172.2.70  raeburn  13940: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13941: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13942: 	    my $ip;
                   13943: 	    if (!exists($name_to_ip{$name})) {
                   13944: 		$ip = gethostbyname($name);
                   13945: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13946: 		    if (defined($old_name_to_ip{$name})) {
                   13947: 			$ip = $old_name_to_ip{$name};
                   13948: 			&logthis("Can't find $name defaulting to old $ip");
                   13949: 		    } else {
                   13950: 			&logthis("Name $name no IP found");
                   13951: 			next;
                   13952: 		    }
                   13953: 		} else {
                   13954: 		    $ip=inet_ntoa($ip);
1.847     albertel 13955: 		}
                   13956: 		$name_to_ip{$name} = $ip;
                   13957: 	    } else {
                   13958: 		$ip = $name_to_ip{$name};
1.653     albertel 13959: 	    }
1.888     albertel 13960: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13961: 		$lonid_to_ip{$id} = $ip;
                   13962: 	    }
                   13963: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13964: 	}
1.1172.2.70  raeburn  13965:         unless ($nocache) {
                   13966: 	    &do_cache_new('iphost','iphost',
                   13967: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13968: 		          48*60*60);
                   13969:         }
1.869     albertel 13970: 
1.847     albertel 13971: 	return %iphost;
1.598     albertel 13972:     }
                   13973: 
1.992     raeburn  13974:     #
                   13975:     #  Given a DNS returns the loncapa host name for that DNS 
                   13976:     # 
                   13977:     sub host_from_dns {
                   13978:         my ($dns) = @_;
                   13979:         my @hosts;
                   13980:         my $ip;
                   13981: 
1.993     raeburn  13982:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13983:             $ip = $name_to_ip{$dns};
                   13984:         }
                   13985:         if (!$ip) {
                   13986:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13987:             if (length($ip) == 4) { 
                   13988: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13989:             }
                   13990:         }
                   13991:         if ($ip) {
                   13992: 	    @hosts = get_hosts_from_ip($ip);
                   13993: 	    return $hosts[0];
                   13994:         }
                   13995:         return undef;
1.986     foxr     13996:     }
1.992     raeburn  13997: 
1.1074    raeburn  13998:     sub get_internet_names {
                   13999:         my ($lonid) = @_;
                   14000:         return if ($lonid eq '');
                   14001:         my ($idnref,$cached)=
                   14002:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14003:         if ($cached) {
                   14004:             return $idnref;
                   14005:         }
                   14006:         my $ip = &get_host_ip($lonid);
                   14007:         my @hosts = &get_hosts_from_ip($ip);
                   14008:         my %iphost = &get_iphost();
                   14009:         my (@idns,%seen);
                   14010:         foreach my $id (@hosts) {
                   14011:             my $dom = &host_domain($id);
                   14012:             my $prim_id = &domain($dom,'primary');
                   14013:             my $prim_ip = &get_host_ip($prim_id);
                   14014:             next if ($seen{$prim_ip});
                   14015:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14016:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14017:                     my $intdom = &internet_dom($id);
                   14018:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14019:                         push(@idns,$intdom);
                   14020:                     }
                   14021:                 }
                   14022:             }
                   14023:             $seen{$prim_ip} = 1;
                   14024:         }
1.1172.2.23  raeburn  14025:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14026:     }
                   14027: 
1.986     foxr     14028: }
                   14029: 
1.1079    raeburn  14030: sub all_loncaparevs {
1.1172.2.39  raeburn  14031:     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  14032: }
                   14033: 
1.1172.2.27  raeburn  14034: # ------------------------------------------------------- Read loncaparev table
                   14035: {
                   14036:     sub load_loncaparevs {
                   14037:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  14038:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  14039:                 while (my $configline=<$config>) {
                   14040:                     chomp($configline);
                   14041:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14042:                     $loncaparevs{$hostid}=$loncaparev;
                   14043:                 }
                   14044:                 close($config);
                   14045:             }
                   14046:         }
                   14047:     }
                   14048: }
                   14049: 
                   14050: # ----------------------------------------------------- Read serverhostID table
                   14051: {
                   14052:     sub load_serverhomeIDs {
                   14053:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  14054:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  14055:                 while (my $configline=<$config>) {
                   14056:                     chomp($configline);
                   14057:                     my ($name,$id)=split(/:/,$configline);
                   14058:                     $serverhomeIDs{$name}=$id;
                   14059:                 }
                   14060:                 close($config);
                   14061:             }
                   14062:         }
                   14063:     }
                   14064: }
                   14065: 
                   14066: 
1.862     albertel 14067: BEGIN {
                   14068: 
                   14069: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14070:     unless ($readit) {
                   14071: {
                   14072:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14073:     %perlvar = (%perlvar,%{$configvars});
                   14074: }
                   14075: 
                   14076: 
1.1       albertel 14077: # ------------------------------------------------------ Read spare server file
                   14078: {
1.1172.2.96  raeburn  14079:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14080: 
                   14081:     while (my $configline=<$config>) {
                   14082:        chomp($configline);
1.284     matthew  14083:        if ($configline) {
1.784     albertel 14084: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14085: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14086: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14087:        }
                   14088:     }
1.448     albertel 14089:     close($config);
1.1       albertel 14090: }
1.11      www      14091: # ------------------------------------------------------------ Read permissions
                   14092: {
1.1172.2.96  raeburn  14093:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14094: 
                   14095:     while (my $configline=<$config>) {
1.448     albertel 14096: 	chomp($configline);
                   14097: 	if ($configline) {
                   14098: 	    my ($role,$perm)=split(/ /,$configline);
                   14099: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14100: 	}
1.11      www      14101:     }
1.448     albertel 14102:     close($config);
1.11      www      14103: }
                   14104: 
                   14105: # -------------------------------------------- Read plain texts for permissions
                   14106: {
1.1172.2.96  raeburn  14107:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14108: 
                   14109:     while (my $configline=<$config>) {
1.448     albertel 14110: 	chomp($configline);
                   14111: 	if ($configline) {
1.742     raeburn  14112: 	    my ($short,@plain)=split(/:/,$configline);
                   14113:             %{$prp{$short}} = ();
                   14114: 	    if (@plain > 0) {
                   14115:                 $prp{$short}{'std'} = $plain[0];
                   14116:                 for (my $i=1; $i<@plain; $i++) {
                   14117:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14118:                 }
                   14119:             }
1.448     albertel 14120: 	}
1.135     www      14121:     }
1.448     albertel 14122:     close($config);
1.135     www      14123: }
                   14124: 
                   14125: # ---------------------------------------------------------- Read package table
                   14126: {
1.1172.2.96  raeburn  14127:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14128: 
                   14129:     while (my $configline=<$config>) {
1.483     albertel 14130: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14131: 	chomp($configline);
                   14132: 	my ($short,$plain)=split(/:/,$configline);
                   14133: 	my ($pack,$name)=split(/\&/,$short);
                   14134: 	if ($plain ne '') {
                   14135: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14136: 	    $packagetab{$short}=$plain; 
                   14137: 	}
1.11      www      14138:     }
1.448     albertel 14139:     close($config);
1.329     matthew  14140: }
                   14141: 
1.1172.2.27  raeburn  14142: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  14143: 
1.1172.2.27  raeburn  14144: &load_loncaparevs();
                   14145: 
                   14146: # ------------------------------------------------------- Read serverhostID table
                   14147: 
                   14148: &load_serverhomeIDs();
1.1074    raeburn  14149: 
1.1172.2.27  raeburn  14150: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14151: {
                   14152:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14153:     if (-e $file) {
                   14154:         my $parser = HTML::LCParser->new($file);
                   14155:         while (my $token = $parser->get_token()) {
                   14156:             if ($token->[0] eq 'S') {
                   14157:                 my $item = $token->[1];
                   14158:                 my $name = $token->[2]{'name'};
                   14159:                 my $value = $token->[2]{'value'};
                   14160:                 if ($item ne '' && $name ne '' && $value ne '') {
                   14161:                     my $release = $parser->get_text();
                   14162:                     $release =~ s/(^\s*|\s*$ )//gx;
                   14163:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   14164:                 }
                   14165:             }
                   14166:         }
                   14167:     }
1.1073    raeburn  14168: }
                   14169: 
1.1138    raeburn  14170: # ---------------------------------------------------------- Read managers table
                   14171: {
                   14172:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  14173:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14174:             while (my $configline=<$config>) {
                   14175:                 chomp($configline);
                   14176:                 next if ($configline =~ /^\#/);
                   14177:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14178:                     $managerstab{$configline} = 1;
                   14179:                 }
                   14180:             }
                   14181:             close($config);
                   14182:         }
                   14183:     }
                   14184: }
                   14185: 
1.329     matthew  14186: # ------------- set up temporary directory
                   14187: {
1.1117    foxr     14188:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14189: 
1.11      www      14190: }
                   14191: 
1.1172.2.104  raeburn  14192: # ------------- set default texengine (domain default overrides this)
                   14193: {
                   14194:     $deftex = LONCAPA::texengine();
                   14195: }
                   14196: 
1.1172.2.114  raeburn  14197: # ------------- set default minimum length for passwords for internal auth users
                   14198: {
                   14199:     $passwdmin = LONCAPA::passwd_min();
                   14200: }
                   14201: 
1.794     albertel 14202: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14203: 				'compress_threshold'=> 20_000,
                   14204:  			        });
1.185     www      14205: 
1.281     www      14206: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14207: $dumpcount=0;
1.958     www      14208: $locknum=0;
1.22      www      14209: 
1.163     harris41 14210: &logtouch();
1.672     albertel 14211: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14212: $readit=1;
1.564     albertel 14213:     {
                   14214: 	use integer;
                   14215: 	my $test=(2**32)+1;
1.568     albertel 14216: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14217: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14218:     }
1.195     www      14219: }
1.1       albertel 14220: }
1.179     www      14221: 
1.1       albertel 14222: 1;
1.191     harris41 14223: __END__
                   14224: 
1.243     albertel 14225: =pod
                   14226: 
1.191     harris41 14227: =head1 NAME
                   14228: 
1.243     albertel 14229: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14230: 
                   14231: =head1 SYNOPSIS
                   14232: 
1.243     albertel 14233: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14234: 
                   14235:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14236: 
1.243     albertel 14237: Common parameters:
                   14238: 
                   14239: =over 4
                   14240: 
                   14241: =item *
                   14242: 
                   14243: $uname : an internal username (if $cname expecting a course Id specifically)
                   14244: 
                   14245: =item *
                   14246: 
                   14247: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14248: 
                   14249: =item *
                   14250: 
                   14251: $symb : a resource instance identifier
                   14252: 
                   14253: =item *
                   14254: 
                   14255: $namespace : the name of a .db file that contains the data needed or
                   14256: being set.
                   14257: 
                   14258: =back
                   14259: 
1.394     bowersj2 14260: =head1 OVERVIEW
1.191     harris41 14261: 
1.394     bowersj2 14262: lonnet provides subroutines which interact with the
                   14263: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14264: about classes, users, and resources.
1.243     albertel 14265: 
                   14266: For many of these objects you can also use this to store data about
                   14267: them or modify them in various ways.
1.191     harris41 14268: 
1.394     bowersj2 14269: =head2 Symbs
1.191     harris41 14270: 
1.394     bowersj2 14271: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14272: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14273: map, the resource number of the resource in the map, and the URL of
                   14274: the resource itself. The latter is somewhat redundant, but might help
                   14275: if maps change.
                   14276: 
                   14277: An example is
                   14278: 
                   14279:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14280: 
                   14281: The respective map entry is
                   14282: 
                   14283:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14284:   title="Problem 2">
                   14285:  </resource>
                   14286: 
                   14287: Symbs are used by the random number generator, as well as to store and
                   14288: restore data specific to a certain instance of for example a problem.
                   14289: 
                   14290: =head2 Storing And Retrieving Data
                   14291: 
                   14292: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14293: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14294: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14295: is is the non-critical message twin of cstore. These functions are for
                   14296: handlers to store a perl hash to a user's permanent data space in an
                   14297: easy manner, and to retrieve it again on another call. It is expected
                   14298: that a handler would use this once at the beginning to retrieve data,
                   14299: and then again once at the end to send only the new data back.
                   14300: 
                   14301: The data is stored in the user's data directory on the user's
                   14302: homeserver under the ID of the course.
                   14303: 
                   14304: The hash that is returned by restore will have all of the previous
                   14305: value for all of the elements of the hash.
                   14306: 
                   14307: Example:
                   14308: 
                   14309:  #creating a hash
                   14310:  my %hash;
                   14311:  $hash{'foo'}='bar';
                   14312: 
                   14313:  #storing it
                   14314:  &Apache::lonnet::cstore(\%hash);
                   14315: 
                   14316:  #changing a value
                   14317:  $hash{'foo'}='notbar';
                   14318: 
                   14319:  #adding a new value
                   14320:  $hash{'bar'}='foo';
                   14321:  &Apache::lonnet::cstore(\%hash);
                   14322: 
                   14323:  #retrieving the hash
                   14324:  my %history=&Apache::lonnet::restore();
                   14325: 
                   14326:  #print the hash
                   14327:  foreach my $key (sort(keys(%history))) {
                   14328:    print("\%history{$key} = $history{$key}");
                   14329:  }
                   14330: 
                   14331: Will print out:
1.191     harris41 14332: 
1.394     bowersj2 14333:  %history{1:foo} = bar
                   14334:  %history{1:keys} = foo:timestamp
                   14335:  %history{1:timestamp} = 990455579
                   14336:  %history{2:bar} = foo
                   14337:  %history{2:foo} = notbar
                   14338:  %history{2:keys} = foo:bar:timestamp
                   14339:  %history{2:timestamp} = 990455580
                   14340:  %history{bar} = foo
                   14341:  %history{foo} = notbar
                   14342:  %history{timestamp} = 990455580
                   14343:  %history{version} = 2
                   14344: 
                   14345: Note that the special hash entries C<keys>, C<version> and
                   14346: C<timestamp> were added to the hash. C<version> will be equal to the
                   14347: total number of versions of the data that have been stored. The
                   14348: C<timestamp> attribute will be the UNIX time the hash was
                   14349: stored. C<keys> is available in every historical section to list which
                   14350: keys were added or changed at a specific historical revision of a
                   14351: hash.
                   14352: 
                   14353: B<Warning>: do not store the hash that restore returns directly. This
                   14354: will cause a mess since it will restore the historical keys as if the
                   14355: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14356: 
1.394     bowersj2 14357: Calling convention:
1.191     harris41 14358: 
1.1172.2.27  raeburn  14359:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  14360:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14361: 
1.394     bowersj2 14362: For more detailed information, see lonnet specific documentation.
1.191     harris41 14363: 
1.394     bowersj2 14364: =head1 RETURN MESSAGES
1.191     harris41 14365: 
1.394     bowersj2 14366: =over 4
1.191     harris41 14367: 
1.394     bowersj2 14368: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14369: 
1.394     bowersj2 14370: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14371: when the connection is brought back up
1.191     harris41 14372: 
1.394     bowersj2 14373: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14374: for later delivery
1.191     harris41 14375: 
1.967     bisitz   14376: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14377: 
1.394     bowersj2 14378: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14379: that was requested
1.191     harris41 14380: 
1.243     albertel 14381: =back
1.191     harris41 14382: 
1.243     albertel 14383: =head1 PUBLIC SUBROUTINES
1.191     harris41 14384: 
1.243     albertel 14385: =head2 Session Environment Functions
1.191     harris41 14386: 
1.243     albertel 14387: =over 4
1.191     harris41 14388: 
1.394     bowersj2 14389: =item * 
                   14390: X<appenv()>
1.949     raeburn  14391: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14392: the user envirnoment file, and will be restored for each access this
1.620     albertel 14393: user makes during this session, also modifies the %env for the current
1.949     raeburn  14394: process. Optional rolesarrayref - if defined contains a reference to an array
                   14395: of roles which are exempt from the restriction on modifying user.role entries 
                   14396: in the user's environment.db and in %env.    
1.191     harris41 14397: 
                   14398: =item *
1.394     bowersj2 14399: X<delenv()>
1.987     raeburn  14400: B<delenv($delthis,$regexp)>: removes all items from the session
                   14401: environment file that begin with $delthis. If the 
                   14402: optional second arg - $regexp - is true, $delthis is treated as a 
                   14403: regular expression, otherwise \Q$delthis\E is used. 
                   14404: The values are also deleted from the current processes %env.
1.191     harris41 14405: 
1.795     albertel 14406: =item * get_env_multiple($name) 
                   14407: 
                   14408: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14409: values may be defined and end up as an array ref.
                   14410: 
                   14411: returns an array of values
                   14412: 
1.243     albertel 14413: =back
                   14414: 
                   14415: =head2 User Information
1.191     harris41 14416: 
1.243     albertel 14417: =over 4
1.191     harris41 14418: 
                   14419: =item *
1.394     bowersj2 14420: X<queryauthenticate()>
                   14421: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14422: authentication scheme
                   14423: 
                   14424: =item *
1.394     bowersj2 14425: X<authenticate()>
1.1073    raeburn  14426: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14427: authenticate user from domain's lib servers (first use the current
                   14428: one). C<$upass> should be the users password.
1.1073    raeburn  14429: $checkdefauth is optional (value is 1 if a check should be made to
                   14430:    authenticate user using default authentication method, and allow
                   14431:    account creation if username does not have account in the domain).
                   14432: $clientcancheckhost is optional (value is 1 if checking whether the
                   14433:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14434: 
                   14435: =item *
1.394     bowersj2 14436: X<homeserver()>
                   14437: B<homeserver($uname,$udom)>: find the server which has
                   14438: the user's directory and files (there must be only one), this caches
                   14439: the answer, and also caches if there is a borken connection.
1.191     harris41 14440: 
                   14441: =item *
1.394     bowersj2 14442: X<idget()>
                   14443: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   14444: (IDs are a unique resource in a domain, there must be only 1 ID per
                   14445: username, and only 1 username per ID in a specific domain) (returns
                   14446: hash: id=>name,id=>name)
1.191     harris41 14447: 
                   14448: =item *
1.394     bowersj2 14449: X<idrget()>
                   14450: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14451: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14452: 
                   14453: =item *
1.394     bowersj2 14454: X<idput()>
                   14455: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 14456: 
                   14457: =item *
1.394     bowersj2 14458: X<rolesinit()>
1.1169    droeschl 14459: B<rolesinit($udom,$username)>: get user privileges.
                   14460: returns user role, first access and timer interval hashes
1.243     albertel 14461: 
                   14462: =item *
1.1171    droeschl 14463: X<privileged()>
                   14464: B<privileged($username,$domain)>: returns a true if user has a
                   14465: privileged and active role (i.e. su or dc), false otherwise.
                   14466: 
                   14467: =item *
1.551     albertel 14468: X<getsection()>
                   14469: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14470: course $cname, return section name/number or '' for "not in course"
                   14471: and '-1' for "no section"
                   14472: 
                   14473: =item *
1.394     bowersj2 14474: X<userenvironment()>
                   14475: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14476: passed in @what from the requested user's environment, returns a hash
                   14477: 
1.858     raeburn  14478: =item * 
                   14479: X<userlog_query()>
1.859     albertel 14480: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14481: activity.log file. %filters defines filters applied when parsing the
                   14482: log file. These can be start or end timestamps, or the type of action
                   14483: - log to look for Login or Logout events, check for Checkin or
                   14484: Checkout, role for role selection. The response is in the form
                   14485: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14486: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14487: 
1.243     albertel 14488: =back
                   14489: 
                   14490: =head2 User Roles
                   14491: 
                   14492: =over 4
                   14493: 
                   14494: =item *
                   14495: 
1.1172.2.65  raeburn  14496: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14497: returns codes for allowed actions.
                   14498: 
                   14499: The first argument is required, all others are optional.
                   14500: 
                   14501: $priv is the privilege being checked.
                   14502: $uri contains additional information about what is being checked for access (e.g.,
                   14503: URL, course ID etc.).
                   14504: $symb is the unique resource instance identifier in a course; if needed,
                   14505: but not provided, it will be retrieved via a call to &symbread().
                   14506: $role is the role for which a priv is being checked (only used if priv is evb).
                   14507: $clientip is the user's IP address (only used when checking for access to portfolio
                   14508: files).
                   14509: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   14510: prevents recursive calls to &allowed.
                   14511: 
1.243     albertel 14512:  F: full access
                   14513:  U,I,K: authentication modes (cxx only)
                   14514:  '': forbidden
                   14515:  1: user needs to choose course
                   14516:  2: browse allowed
1.766     albertel 14517:  A: passphrase authentication needed
1.1172.2.65  raeburn  14518:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14519: 
                   14520: =item *
                   14521: 
1.1172.2.13  raeburn  14522: constructaccess($url,$setpriv) : check for access to construction space URL
                   14523: 
                   14524: See if the owner domain and name in the URL match those in the
                   14525: expected environment.  If so, return three element list
                   14526: ($ownername,$ownerdomain,$ownerhome).
                   14527: 
                   14528: Otherwise return the null string.
                   14529: 
                   14530: If second argument 'setpriv' is true, it assigns the privileges,
                   14531: and returns the same three element list, unless the owner has
                   14532: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14533: in which case the null string is returned.
                   14534: 
                   14535: =item *
                   14536: 
1.1172.2.84  raeburn  14537: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14538: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14539: for system, domain, and course level. $uname and $udom are optional (current
                   14540: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14541: 
                   14542: =item *
                   14543: 
1.988     raeburn  14544: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14545: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14546: $type is Course (default) or Community.
1.988     raeburn  14547: If $forcedefault evaluates to true, text returned will be default 
                   14548: text for $type. Otherwise, if this is a course, the text returned 
                   14549: will be a custom name for the role (if defined in the course's 
                   14550: environment).  If no custom name is defined the default is returned.
                   14551:    
1.832     raeburn  14552: =item *
                   14553: 
1.1172.2.23  raeburn  14554: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14555: All arguments are optional. Returns a hash of a roles, either for
                   14556: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14557: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14558: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14559: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14560: For each key, value is set to colon-separated start and end times for
                   14561: the role.  If no username and domain are specified, will default to
1.934     raeburn  14562: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14563: of role statuses (active, future or previous), roles 
                   14564: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14565: to restrict the list of roles reported. If no array ref is 
                   14566: provided for types, will default to return only active roles.
1.834     albertel 14567: 
1.1172.2.13  raeburn  14568: =item *
                   14569: 
                   14570: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   14571: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   14572: 
                   14573: Additional optional arguments are: $type (if role checking is to be restricted
                   14574: to certain user status types -- previous (expired roles), active (currently
                   14575: available roles) or future (roles available in the future), and
                   14576: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  14577: have active Domain Coordinator role in course's domain or in additional
                   14578: domains (specified in 'Domains to check for privileged users' in course
                   14579: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14580: 
                   14581: =item *
                   14582: 
                   14583: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14584: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14585: $possdomains and $possroles are optional array refs -- to domains to check and
                   14586: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14587: users' roles.db to check for a dc or su role in any domain. This can be
                   14588: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14589: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14590: this then allows &privileged_by_domain() to be used, which caches the identity
                   14591: of privileged users, eliminating the need for repeated calls to &dump().
                   14592: 
                   14593: =item *
                   14594: 
                   14595: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14596: where the outer hash keys are domains specified in the $possdomains array ref,
                   14597: next inner hash keys are privileged roles specified in the $roles array ref,
                   14598: and the innermost hash contains key = value pairs for username:domain = end:start
                   14599: for active or future "privileged" users with that role in that domain. To avoid
                   14600: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14601: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  14602: 
1.243     albertel 14603: =back
                   14604: 
                   14605: =head2 User Modification
                   14606: 
                   14607: =over 4
                   14608: 
                   14609: =item *
                   14610: 
1.957     raeburn  14611: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14612: user for the level given by URL.  Optional start and end dates (leave empty
                   14613: string or zero for "no date")
1.191     harris41 14614: 
                   14615: =item *
                   14616: 
1.243     albertel 14617: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14618: change a users, password, possible return values are: ok,
                   14619: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14620: refused
1.191     harris41 14621: 
                   14622: =item *
                   14623: 
1.243     albertel 14624: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14625: 
                   14626: =item *
                   14627: 
1.1058    raeburn  14628: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14629:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14630: 
                   14631: will update user information (firstname,middlename,lastname,generation,
                   14632: permanentemail), and if forceid is true, student/employee ID also.
                   14633: A user's institutional affiliation(s) can also be updated.
                   14634: User information fields will not be overwritten with empty entries 
                   14635: unless the field is included in the $candelete array reference.
                   14636: This array is included when a single user is modified via "Manage Users",
                   14637: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14638: 
                   14639: =item *
                   14640: 
1.286     matthew  14641: modifystudent
                   14642: 
1.957     raeburn  14643: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  14644: The course id is resolved based on the current user's environment.  
                   14645: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14646: associated with a course.
                   14647: 
1.297     matthew  14648: This call is essentially a wrapper for lonnet::modifyuser and
                   14649: lonnet::modify_student_enrollment
1.286     matthew  14650: 
                   14651: Inputs: 
                   14652: 
                   14653: =over 4
                   14654: 
1.957     raeburn  14655: =item B<$udom> Student's loncapa domain
1.286     matthew  14656: 
1.957     raeburn  14657: =item B<$uname> Student's loncapa login name
1.286     matthew  14658: 
1.964     bisitz   14659: =item B<$uid> Student/Employee ID
1.286     matthew  14660: 
1.957     raeburn  14661: =item B<$umode> Student's authentication mode
1.286     matthew  14662: 
1.957     raeburn  14663: =item B<$upass> Student's password
1.286     matthew  14664: 
1.957     raeburn  14665: =item B<$first> Student's first name
1.286     matthew  14666: 
1.957     raeburn  14667: =item B<$middle> Student's middle name
1.286     matthew  14668: 
1.957     raeburn  14669: =item B<$last> Student's last name
1.286     matthew  14670: 
1.957     raeburn  14671: =item B<$gene> Student's generation
1.286     matthew  14672: 
1.957     raeburn  14673: =item B<$usec> Student's section in course
1.286     matthew  14674: 
                   14675: =item B<$end> Unix time of the roles expiration
                   14676: 
                   14677: =item B<$start> Unix time of the roles start date
                   14678: 
                   14679: =item B<$forceid> If defined, allow $uid to be changed
                   14680: 
                   14681: =item B<$desiredhome> server to use as home server for student
                   14682: 
1.957     raeburn  14683: =item B<$email> Student's permanent e-mail address
                   14684: 
                   14685: =item B<$type> Type of enrollment (auto or manual)
                   14686: 
1.963     raeburn  14687: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14688: 
                   14689: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14690: 
1.963     raeburn  14691: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14692: 
1.963     raeburn  14693: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14694: 
1.1172.2.19  raeburn  14695: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14696: 
                   14697: =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  14698: 
1.286     matthew  14699: =back
1.297     matthew  14700: 
                   14701: =item *
                   14702: 
                   14703: modify_student_enrollment
                   14704: 
1.1172.2.31  raeburn  14705: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14706: 'role.request.course' must be defined for this function to proceed.
                   14707: 
                   14708: Inputs:
                   14709: 
                   14710: =over 4
                   14711: 
1.1172.2.31  raeburn  14712: =item $udom, student's domain
1.297     matthew  14713: 
1.1172.2.31  raeburn  14714: =item $uname, student's name
1.297     matthew  14715: 
1.1172.2.31  raeburn  14716: =item $uid, student's user id
1.297     matthew  14717: 
1.1172.2.31  raeburn  14718: =item $first, student's first name
1.297     matthew  14719: 
                   14720: =item $middle
                   14721: 
                   14722: =item $last
                   14723: 
                   14724: =item $gene
                   14725: 
                   14726: =item $usec
                   14727: 
                   14728: =item $end
                   14729: 
                   14730: =item $start
                   14731: 
1.957     raeburn  14732: =item $type
                   14733: 
                   14734: =item $locktype
                   14735: 
                   14736: =item $cid
                   14737: 
                   14738: =item $selfenroll
                   14739: 
                   14740: =item $context
                   14741: 
1.1172.2.19  raeburn  14742: =item $credits, number of credits student will earn from this class
                   14743: 
1.1172.2.76  raeburn  14744: =item $instsec, institutional course section code for student
                   14745: 
1.297     matthew  14746: =back
                   14747: 
1.191     harris41 14748: 
                   14749: =item *
                   14750: 
1.243     albertel 14751: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14752: custom role; give a custom role to a user for the level given by URL.  Specify
                   14753: name and domain of role author, and role name
1.191     harris41 14754: 
                   14755: =item *
                   14756: 
1.243     albertel 14757: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14758: 
                   14759: =item *
                   14760: 
1.243     albertel 14761: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14762: 
                   14763: =back
                   14764: 
                   14765: =head2 Course Infomation
                   14766: 
                   14767: =over 4
1.191     harris41 14768: 
                   14769: =item *
                   14770: 
1.1118    foxr     14771: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14772: specified course id, including all environment settings for the
                   14773: course, the description of the course will be in the hash under the
                   14774: key 'description'
1.191     harris41 14775: 
1.1118    foxr     14776: $options is an optional parameter that if supplied is a hash reference that controls
                   14777: what how this function works.  It has the following key/values:
                   14778: 
                   14779: =over 4
                   14780: 
                   14781: =item freshen_cache
                   14782: 
                   14783: If defined, and the environment cache for the course is valid, it is 
                   14784: returned in the returned hash.
                   14785: 
                   14786: =item one_time
                   14787: 
                   14788: If defined, the last cache time is set to _now_
                   14789: 
                   14790: =item user
                   14791: 
                   14792: If defined, the supplied username is used instead of the current user.
                   14793: 
                   14794: 
                   14795: =back
                   14796: 
1.191     harris41 14797: =item *
                   14798: 
1.624     albertel 14799: resdata($name,$domain,$type,@which) : request for current parameter
                   14800: setting for a specific $type, where $type is either 'course' or 'user',
                   14801: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  14802: answers for 10 minutes.
1.243     albertel 14803: 
1.877     foxr     14804: =item *
                   14805: 
                   14806: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14807: data base, returning a hash that is keyed by the resource name and has
                   14808: values that are the resource value.  I believe that the timestamps and
                   14809: versions are also returned.
                   14810: 
1.1172.2.31  raeburn  14811: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14812: supplemental content area. This routine caches the number of files for
                   14813: 10 minutes.
                   14814: 
1.243     albertel 14815: =back
                   14816: 
                   14817: =head2 Course Modification
                   14818: 
                   14819: =over 4
1.191     harris41 14820: 
                   14821: =item *
                   14822: 
1.243     albertel 14823: writecoursepref($courseid,%prefs) : write preferences (environment
                   14824: database) for a course
1.191     harris41 14825: 
                   14826: =item *
                   14827: 
1.1011    raeburn  14828: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14829: 
                   14830: =item *
                   14831: 
1.1038    raeburn  14832: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14833: 
1.1167    droeschl 14834: =item *
                   14835: 
                   14836: is_course($courseid), is_course($cdom, $cnum)
                   14837: 
                   14838: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14839: two component version $cdom, $cnum. It checks if the specified course exists.
                   14840: 
                   14841: Returns:
                   14842:     undef if the course doesn't exist, otherwise
                   14843:     in scalar context the combined courseid.
                   14844:     in list context the two components of the course identifier, domain and 
                   14845:     courseid.    
                   14846: 
1.243     albertel 14847: =back
                   14848: 
1.1172.2.109  raeburn  14849: =head2 Bubblesheet Configuration
                   14850: 
                   14851: =over 4
                   14852: 
                   14853: =item *
                   14854: 
                   14855: get_scantron_config($which)
                   14856: 
                   14857: $which - the name of the configuration to parse from the file.
                   14858: 
                   14859: Parses and returns the bubblesheet configuration line selected as a
                   14860: hash of configuration file fields.
                   14861: 
                   14862: 
                   14863: Returns:
                   14864:     If the named configuration is not in the file, an empty
                   14865:     hash is returned.
                   14866: 
                   14867:     a hash with the fields
                   14868:       name         - internal name for the this configuration setup
                   14869:       description  - text to display to operator that describes this config
                   14870:       CODElocation - if 0 or the string 'none'
                   14871:                           - no CODE exists for this config
                   14872:                      if -1 || the string 'letter'
                   14873:                           - a CODE exists for this config and is
                   14874:                             a string of letters
                   14875:                      Unsupported value (but planned for future support)
                   14876:                           if a positive integer
                   14877:                                - The CODE exists as the first n items from
                   14878:                                  the question section of the form
                   14879:                           if the string 'number'
                   14880:                                - The CODE exists for this config and is
                   14881:                                  a string of numbers
                   14882:       CODEstart   - (only matter if a CODE exists) column in the line where
                   14883:                      the CODE starts
                   14884:       CODElength  - length of the CODE
                   14885:       IDstart     - column where the student/employee ID starts
                   14886:       IDlength    - length of the student/employee ID info
                   14887:       Qstart      - column where the information from the bubbled
                   14888:                     'questions' start
                   14889:       Qlength     - number of columns comprising a single bubble line from
                   14890:                     the sheet. (usually either 1 or 10)
                   14891:       Qon         - either a single character representing the character used
                   14892:                     to signal a bubble was chosen in the positional setup, or
                   14893:                     the string 'letter' if the letter of the chosen bubble is
                   14894:                     in the final, or 'number' if a number representing the
                   14895:                     chosen bubble is in the file (1->A 0->J)
                   14896:       Qoff        - the character used to represent that a bubble was
                   14897:                     left blank
                   14898:       PaperID     - if the scanning process generates a unique number for each
                   14899:                     sheet scanned the column that this ID number starts in
                   14900:       PaperIDlength - number of columns that comprise the unique ID number
                   14901:                       for the sheet of paper
                   14902:       FirstName   - column that the first name starts in
                   14903:       FirstNameLength - number of columns that the first name spans
                   14904:       LastName    - column that the last name starts in
                   14905:       LastNameLength - number of columns that the last name spans
                   14906:       BubblesPerRow - number of bubbles available in each row used to
                   14907:                       bubble an answer. (If not specified, 10 assumed).
                   14908: 
                   14909: 
                   14910: =item *
                   14911: 
                   14912: get_scantronformat_file($cdom)
                   14913: 
                   14914: $cdom - the course's domain (optional); if not supplied, uses
                   14915: domain for current $env{'request.course.id'}.
                   14916: 
                   14917: Returns an array containing lines from the scantron format file for
                   14918: the domain of the course.
                   14919: 
                   14920: If a url for a custom.tab file is listed in domain's configuration.db,
                   14921: lines are from this file.
                   14922: 
                   14923: Otherwise, if a default.tab has been published in RES space by the
                   14924: domainconfig user, lines are from this file.
                   14925: 
                   14926: Otherwise, fall back to getting lines from the legacy file on the
                   14927: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   14928: 
                   14929: =back
                   14930: 
1.243     albertel 14931: =head2 Resource Subroutines
                   14932: 
                   14933: =over 4
1.191     harris41 14934: 
                   14935: =item *
                   14936: 
1.243     albertel 14937: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14938: 
                   14939: =item *
                   14940: 
1.243     albertel 14941: repcopy($filename) : subscribes to the requested file, and attempts to
                   14942: replicate from the owning library server, Might return
1.607     raeburn  14943: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14944: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14945: resource. Expects the local filesystem pathname
                   14946: (/home/httpd/html/res/....)
                   14947: 
                   14948: =back
                   14949: 
                   14950: =head2 Resource Information
                   14951: 
                   14952: =over 4
1.191     harris41 14953: 
                   14954: =item *
                   14955: 
1.1172.2.28  raeburn  14956: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14957: and returns the value of a variety of different possible values,
                   14958: $varname should be a request string, and the other parameters can be
                   14959: used to specify who and what one is asking about. Ordinarily, $cid 
                   14960: does not need to be specified, as it is retrived from 
                   14961: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14962: within lonuserstate::loadmap() when initializing a course, before
                   14963: $env{'request.course.id'} has been set, so it needs to be provided
                   14964: in that one case.
1.243     albertel 14965: 
                   14966: Possible values for $varname are environment.lastname (or other item
                   14967: from the envirnment hash), user.name (or someother aspect about the
                   14968: user), resource.0.maxtries (or some other part and parameter of a
                   14969: resource)
1.204     albertel 14970: 
                   14971: =item *
                   14972: 
1.243     albertel 14973: directcondval($number) : get current value of a condition; reads from a state
                   14974: string
1.204     albertel 14975: 
                   14976: =item *
                   14977: 
1.243     albertel 14978: condval($condidx) : value of condition index based on state
1.204     albertel 14979: 
                   14980: =item *
                   14981: 
1.243     albertel 14982: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14983: resource's metadata, $what should be either a specific key, or either
                   14984: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14985: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14986: 
                   14987: this function automatically caches all requests
1.191     harris41 14988: 
                   14989: =item *
                   14990: 
1.243     albertel 14991: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14992: network of library servers; returns file handle of where SQL and regex results
                   14993: will be stored for query
1.191     harris41 14994: 
                   14995: =item *
                   14996: 
1.1172.2.66  raeburn  14997: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   14998: return symbolic list entry (all arguments optional).
                   14999: 
                   15000: Args: filename is the filename (including path) for the file for which a symb
                   15001: is required; donotrecurse, if true will prevent calls to allowed() being made
                   15002: to check access status if more than one resource was found in the bighash
                   15003: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   15004: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   15005: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15006: cause possible symbs to be checked to determine if they are subject to content
                   15007: blocking, if so they will not be included as possible symbs; possibles is a
                   15008: ref to a hash, which, as a side effect, will be populated with all possible
                   15009: symbs (content blocking not tested).
                   15010: 
1.243     albertel 15011: returns the data handle
1.191     harris41 15012: 
                   15013: =item *
                   15014: 
1.1172.2.17  raeburn  15015: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  15016: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15017: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  15018: on failure, user must be in a course, as it assumes the existence of
                   15019: the course initial hash, and uses $env('request.course.id'}.  The third
                   15020: arg is an optional reference to a scalar.  If this arg is passed in the
                   15021: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15022: encrypted; otherwise it will be null.
1.243     albertel 15023: 
1.191     harris41 15024: =item *
                   15025: 
1.243     albertel 15026: symbclean($symb) : removes versions numbers from a symb, returns the
                   15027: cleaned symb
1.191     harris41 15028: 
                   15029: =item *
                   15030: 
1.243     albertel 15031: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15032: course map, user must be in a course for it to work.
1.191     harris41 15033: 
                   15034: =item *
                   15035: 
1.243     albertel 15036: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15037: 
                   15038: =item *
                   15039: 
1.243     albertel 15040: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15041: a random seed, all arguments are optional, if they aren't sent it uses the
                   15042: environment to derive them. Note: if symb isn't sent and it can't get one
                   15043: from &symbread it will use the current time as its return value
1.191     harris41 15044: 
                   15045: =item *
                   15046: 
1.243     albertel 15047: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15048: unfakeable, receipt
1.191     harris41 15049: 
                   15050: =item *
                   15051: 
1.620     albertel 15052: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15053: 
                   15054: =item *
                   15055: 
1.243     albertel 15056: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15057: 
                   15058: =item *
                   15059: 
1.243     albertel 15060: 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 15061: 
                   15062: =item *
                   15063: 
1.243     albertel 15064: 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 15065: 
                   15066: =item *
                   15067: 
1.243     albertel 15068: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15069: 
                   15070: =item *
                   15071: 
1.243     albertel 15072: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15073: forcing spreadsheet to reevaluate the resource scores next time.
                   15074: 
1.1172.2.13  raeburn  15075: =item *
                   15076: 
                   15077: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15078: when viewing in course context.
                   15079: 
                   15080:  input: six args -- filename (decluttered), course number, course domain,
                   15081:                     url, symb (if registered) and group (if this is a
                   15082:                     group item -- e.g., bulletin board, group page etc.).
                   15083: 
                   15084:  output: array of five scalars --
                   15085:          $cfile -- url for file editing if editable on current server
                   15086:          $home -- homeserver of resource (i.e., for author if published,
                   15087:                                           or course if uploaded.).
                   15088:          $switchserver --  1 if server switch will be needed.
                   15089:          $forceedit -- 1 if icon/link should be to go to edit mode
                   15090:          $forceview -- 1 if icon/link should be to go to view mode
                   15091: 
                   15092: =item *
                   15093: 
                   15094: is_course_upload($file,$cnum,$cdom)
                   15095: 
                   15096: Used in course context to determine if current file was uploaded to
                   15097: the course (i.e., would be found in /userfiles/docs on the course's
                   15098: homeserver.
                   15099: 
                   15100:   input: 3 args -- filename (decluttered), course number and course domain.
                   15101:   output: boolean -- 1 if file was uploaded.
                   15102: 
1.243     albertel 15103: =back
                   15104: 
                   15105: =head2 Storing/Retreiving Data
                   15106: 
                   15107: =over 4
1.191     harris41 15108: 
                   15109: =item *
                   15110: 
1.1172.2.64  raeburn  15111: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   15112: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15113: the remaining args aren't required and if they aren't passed or are '' they will
                   15114: be derived from the env (with the exception of $laststore, which is an
                   15115: optional arg used when a user's submission is stored in grading).
                   15116: $laststore is $version=$timestamp, where $version is the most recent version
                   15117: number retrieved for the corresponding $symb in the $namespace db file, and
                   15118: $timestamp is the timestamp for that transaction (UNIX time).
                   15119: $laststore is currently only passed when cstore() is called by
                   15120: structuretags::finalize_storage().
1.191     harris41 15121: 
                   15122: =item *
                   15123: 
1.1172.2.64  raeburn  15124: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   15125: but uses critical subroutine
1.191     harris41 15126: 
                   15127: =item *
                   15128: 
1.243     albertel 15129: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15130: all args are optional
1.191     harris41 15131: 
                   15132: =item *
                   15133: 
1.717     albertel 15134: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15135: dumps the complete (or key matching regexp) namespace into a hash
                   15136: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15137: normally &store()ed into
                   15138: 
                   15139: $range should be either an integer '100' (give me the first 100
                   15140:                                            matching records)
                   15141:               or be  two integers sperated by a - with no spaces
                   15142:                  '30-50' (give me the 30th through the 50th matching
                   15143:                           records)
                   15144: 
                   15145: 
                   15146: =item *
                   15147: 
1.1172.2.59  raeburn  15148: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15149: replaces a &store() version of data with a replacement set of data
                   15150: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  15151: reference. If $tolog is true, the transaction is logged in the courselog
                   15152: with an action=PUTSTORE.
1.717     albertel 15153: 
                   15154: =item *
                   15155: 
1.243     albertel 15156: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15157: works very similar to store/cstore, but all data is stored in a
                   15158: temporary location and can be reset using tmpreset, $storehash should
                   15159: be a hash reference, returns nothing on success
1.191     harris41 15160: 
                   15161: =item *
                   15162: 
1.243     albertel 15163: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15164: similar to restore, but all data is stored in a temporary location and
                   15165: can be reset using tmpreset. Returns a hash of values on success,
                   15166: error string otherwise.
1.191     harris41 15167: 
                   15168: =item *
                   15169: 
1.243     albertel 15170: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15171: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15172: 
                   15173: =item *
                   15174: 
1.243     albertel 15175: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15176: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15177: 
                   15178: =item *
                   15179: 
1.243     albertel 15180: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15181: namesp ($udom and $uname are optional)
1.191     harris41 15182: 
                   15183: =item *
                   15184: 
1.702     albertel 15185: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15186: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15187: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15188: 
1.702     albertel 15189: $range should be either an integer '100' (give me the first 100
                   15190:                                            matching records)
                   15191:               or be  two integers sperated by a - with no spaces
                   15192:                  '30-50' (give me the 30th through the 50th matching
                   15193:                           records)
1.449     matthew  15194: =item *
                   15195: 
                   15196: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15197: $store can be a scalar, an array reference, or if the amount to be 
                   15198: incremented is > 1, a hash reference.
                   15199: 
                   15200: ($udom and $uname are optional)
1.191     harris41 15201: 
                   15202: =item *
                   15203: 
1.243     albertel 15204: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15205: ($udom and $uname are optional)
1.191     harris41 15206: 
                   15207: =item *
                   15208: 
1.243     albertel 15209: cput($namespace,$storehash,$udom,$uname) : critical put
                   15210: ($udom and $uname are optional)
1.191     harris41 15211: 
                   15212: =item *
                   15213: 
1.748     albertel 15214: newput($namespace,$storehash,$udom,$uname) :
                   15215: 
                   15216: Attempts to store the items in the $storehash, but only if they don't
                   15217: currently exist, if this succeeds you can be certain that you have 
                   15218: successfully created a new key value pair in the $namespace db.
                   15219: 
                   15220: 
                   15221: Args:
                   15222:  $namespace: name of database to store values to
                   15223:  $storehash: hashref to store to the db
                   15224:  $udom: (optional) domain of user containing the db
                   15225:  $uname: (optional) name of user caontaining the db
                   15226: 
                   15227: Returns:
                   15228:  'ok' -> succeeded in storing all keys of $storehash
                   15229:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15230:                         least <key> already existed in the db (other
                   15231:                         requested keys may also already exist)
1.967     bisitz   15232:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15233:  'con_lost' -> unable to contact request server
                   15234:  'refused' -> action was not allowed by remote machine
                   15235: 
                   15236: 
                   15237: =item *
                   15238: 
1.243     albertel 15239: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15240: reference filled in from namesp (encrypts the return communication)
                   15241: ($udom and $uname are optional)
1.191     harris41 15242: 
                   15243: =item *
                   15244: 
1.243     albertel 15245: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15246: critical subroutine
                   15247: 
1.806     raeburn  15248: =item *
                   15249: 
1.860     raeburn  15250: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15251: array reference filled in from namespace found in domain level on either
                   15252: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15253: 
                   15254: =item *
                   15255: 
1.860     raeburn  15256: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15257: domain level either on specified domain server ($uhome) or primary domain 
                   15258: server ($udom and $uhome are optional)
1.806     raeburn  15259: 
1.943     raeburn  15260: =item * 
                   15261: 
1.1172.2.35  raeburn  15262: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   15263: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15264: the target domain.
                   15265: 
                   15266: May also include additional key => value pairs for the following groups:
                   15267: 
                   15268: =over
                   15269: 
                   15270: =item
                   15271: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15272: 
                   15273: =over
                   15274: 
                   15275: =item defaultquota, authorquota
                   15276: 
                   15277: =back
                   15278: 
                   15279: =item
                   15280: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15281: portfolio for users).
                   15282: 
                   15283: =over
                   15284: 
                   15285: =item
                   15286: aboutme, blog, webdav, portfolio
                   15287: 
                   15288: =back
                   15289: 
                   15290: =item
                   15291: requestcourses: ability to request courses, and how requests are processed.
                   15292: 
                   15293: =over
                   15294: 
                   15295: =item
1.1172.2.37  raeburn  15296: official, unofficial, community, textbook
1.1172.2.35  raeburn  15297: 
                   15298: =back
                   15299: 
                   15300: =item
                   15301: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15302: 
                   15303: =over
                   15304: 
                   15305: =item
1.1172.2.44  raeburn  15306: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  15307: 
                   15308: =back
                   15309: 
                   15310: =item
                   15311: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15312: for course's uploaded content.
                   15313: 
                   15314: =over
                   15315: 
                   15316: =item
1.1172.2.68  raeburn  15317: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   15318: communityquota, textbookquota
1.1172.2.35  raeburn  15319: 
                   15320: =back
                   15321: 
                   15322: =item
                   15323: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15324: on your servers.
                   15325: 
                   15326: =over
                   15327: 
                   15328: =item
                   15329: remotesessions, hostedsessions
                   15330: 
                   15331: =back
                   15332: 
                   15333: =back
                   15334: 
                   15335: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15336: utility to create a configuration.db file on a domain's primary library server
                   15337: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15338: -- corresponding values are authentication type (internal, krb4, krb5,
                   15339: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   15340: will be available. Values are retrieved from cache (if current), unless the
                   15341: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15342: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15343: 
                   15344: Typical usage:
1.943     raeburn  15345: 
1.1172.2.35  raeburn  15346: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15347: 
1.243     albertel 15348: =back
                   15349: 
                   15350: =head2 Network Status Functions
                   15351: 
                   15352: =over 4
1.191     harris41 15353: 
                   15354: =item *
                   15355: 
1.1137    raeburn  15356: dirlist() : return directory list based on URI (first arg).
                   15357: 
                   15358: Inputs: 1 required, 5 optional.
                   15359: 
                   15360: =over
                   15361: 
                   15362: =item 
                   15363: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15364: 
                   15365: =item
                   15366: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15367: 
                   15368: =item
                   15369: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15370: 
                   15371: =item
                   15372: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15373: 
                   15374: =item
                   15375: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15376: 
                   15377: =item 
                   15378: $alternateRoot - path to prepend in place of path from $uri.
                   15379: 
                   15380: =back
                   15381: 
                   15382: Returns: Array of up to two items.
                   15383: 
                   15384: =over
                   15385: 
                   15386: a reference to an array of files/subdirectories
                   15387: 
                   15388: =over
                   15389: 
                   15390: Each element in the array of files/subdirectories is a & separated list of
                   15391: item name and the result of running stat on the item.  If dirlist was requested
                   15392: for a file instead of a directory, the item name will be ''. For a directory 
                   15393: listing, if the item is a metadata file, the element will end &N&M 
                   15394: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15395: default copyright set (1).  
                   15396: 
                   15397: =back
                   15398: 
                   15399: a scalar containing error condition (if encountered).
                   15400: 
                   15401: =over
                   15402: 
                   15403: =item 
                   15404: no_host (no homeserver identified for $username:$domain).
                   15405: 
                   15406: =item 
                   15407: no_such_host (server contacted for listing not identified as valid host).
                   15408: 
                   15409: =item 
                   15410: con_lost (connection to remote server failed).
                   15411: 
                   15412: =item 
                   15413: refused (invalid $username:$domain received on lond side).
                   15414: 
                   15415: =item 
                   15416: no_such_dir (directory at specified path on lond side does not exist). 
                   15417: 
                   15418: =item 
                   15419: empty (directory at specified path on lond side is empty).
                   15420: 
                   15421: =over
                   15422: 
                   15423: This is currently not encountered because the &ls3, &ls2, 
                   15424: &ls (_handler) routines on the lond side do not filter out
                   15425: . and .. from a directory listing. 
                   15426: 
                   15427: =back
                   15428: 
                   15429: =back
                   15430: 
                   15431: =back
1.191     harris41 15432: 
                   15433: =item *
                   15434: 
1.243     albertel 15435: spareserver() : find server with least workload from spare.tab
                   15436: 
1.986     foxr     15437: 
                   15438: =item *
                   15439: 
                   15440: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15441: if there is no corresponding loncapa host.
                   15442: 
1.243     albertel 15443: =back
                   15444: 
1.986     foxr     15445: 
1.243     albertel 15446: =head2 Apache Request
                   15447: 
                   15448: =over 4
1.191     harris41 15449: 
                   15450: =item *
                   15451: 
1.243     albertel 15452: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15453: localhost, posts hash
                   15454: 
                   15455: =back
                   15456: 
                   15457: =head2 Data to String to Data
                   15458: 
                   15459: =over 4
1.191     harris41 15460: 
                   15461: =item *
                   15462: 
1.243     albertel 15463: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15464: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15465: 
                   15466: =item *
                   15467: 
1.243     albertel 15468: hashref2str($hashref) : convert a hashref into a string complete with
                   15469: escaping and '=' and '&' separators, supports elements that are
                   15470: arrayrefs and hashrefs
1.191     harris41 15471: 
                   15472: =item *
                   15473: 
1.243     albertel 15474: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15475: with escaping and '&' separators, supports elements that are arrayrefs
                   15476: and hashrefs
1.191     harris41 15477: 
                   15478: =item *
                   15479: 
1.243     albertel 15480: str2hash($string) : convert string to hash using unescaping and
                   15481: splitting on '=' and '&', supports elements that are arrayrefs and
                   15482: hashrefs
1.191     harris41 15483: 
                   15484: =item *
                   15485: 
1.243     albertel 15486: str2array($string) : convert string to hash using unescaping and
                   15487: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15488: 
                   15489: =back
                   15490: 
                   15491: =head2 Logging Routines
                   15492: 
                   15493: 
                   15494: These routines allow one to make log messages in the lonnet.log and
                   15495: lonnet.perm logfiles.
1.191     harris41 15496: 
1.1119    foxr     15497: =over 4
                   15498: 
1.191     harris41 15499: =item *
                   15500: 
1.243     albertel 15501: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15502: 
                   15503: =item *
                   15504: 
1.243     albertel 15505: logthis() : append message to the normal lonnet.log file, it gets
                   15506: preiodically rolled over and deleted.
1.191     harris41 15507: 
                   15508: =item *
                   15509: 
1.243     albertel 15510: logperm() : append a permanent message to lonnet.perm.log, this log
                   15511: file never gets deleted by any automated portion of the system, only
                   15512: messages of critical importance should go in here.
                   15513: 
1.1119    foxr     15514: 
1.243     albertel 15515: =back
                   15516: 
                   15517: =head2 General File Helper Routines
                   15518: 
                   15519: =over 4
1.191     harris41 15520: 
                   15521: =item *
                   15522: 
1.481     raeburn  15523: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15524: (a) files in /uploaded
                   15525:   (i) If a local copy of the file exists - 
                   15526:       compares modification date of local copy with last-modified date for 
                   15527:       definitive version stored on home server for course. If local copy is 
                   15528:       stale, requests a new version from the home server and stores it. 
                   15529:       If the original has been removed from the home server, then local copy 
                   15530:       is unlinked.
                   15531:   (ii) If local copy does not exist -
                   15532:       requests the file from the home server and stores it. 
                   15533:   
                   15534:   If $caller is 'uploadrep':  
                   15535:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15536:     for request for files originally uploaded via DOCS. 
                   15537:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15538:   
                   15539:   Otherwise:
                   15540:      This indicates a call from the content generation phase of the request.
                   15541:      -  returns the entire contents of the file or -1.
                   15542:      
                   15543: (b) files in /res
                   15544:    - returns the entire contents of a file or -1; 
                   15545:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15546: 
1.712     albertel 15547: 
                   15548: =item *
                   15549: 
                   15550: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15551:                   reference
                   15552: 
                   15553: returns either a stat() list of data about the file or an empty list
                   15554: if the file doesn't exist or couldn't find out about it (connection
                   15555: problems or user unknown)
                   15556: 
1.191     harris41 15557: =item *
                   15558: 
1.243     albertel 15559: filelocation($dir,$file) : returns file system location of a file
                   15560: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15561: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15562: and a file of ../bob will become /a/bob)
1.191     harris41 15563: 
                   15564: =item *
                   15565: 
                   15566: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15567: filelocation except for hrefs
                   15568: 
                   15569: =item *
                   15570: 
1.1172.2.49  raeburn  15571: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15572: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15573: 
1.243     albertel 15574: =back
                   15575: 
1.608     albertel 15576: =head2 Usererfile file routines (/uploaded*)
                   15577: 
                   15578: =over 4
                   15579: 
                   15580: =item *
                   15581: 
                   15582: userfileupload(): main rotine for putting a file in a user or course's
                   15583:                   filespace, arguments are,
                   15584: 
1.620     albertel 15585:  formname - required - this is the name of the element in $env where the
1.608     albertel 15586:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15587:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15588:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15589:  context - if coursedoc, store the file in the course of the active role
                   15590:              of the current user; 
                   15591:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15592:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15593:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15594:          if undefined, it will be placed in "unknown"
                   15595: 
                   15596:  (This routine calls clean_filename() to remove any dangerous
                   15597:  characters from the filename, and then calls finuserfileupload() to
                   15598:  complete the transaction)
                   15599: 
                   15600:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15601:  and /adm/notfound.html if unsuccessful
                   15602: 
                   15603: =item *
                   15604: 
                   15605: clean_filename(): routine for cleaing a filename up for storage in
                   15606:                  userfile space, argument is:
                   15607: 
                   15608:  filename - proposed filename
                   15609: 
                   15610: returns: the new clean filename
                   15611: 
                   15612: =item *
                   15613: 
1.1090    raeburn  15614: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15615: userspace, probably shouldn't be called directly
                   15616: 
                   15617:   docuname: username or courseid of destination for the file
                   15618:   docudom: domain of user/course of destination for the file
                   15619:   formname: same as for userfileupload()
1.1090    raeburn  15620:   fname: filename (including subdirectories) for the file
                   15621:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  15622:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  15623:   allfiles: reference to hash used to store objects found by parser
                   15624:   codebase: reference to hash used for codebases of java objects found by parser
                   15625:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15626:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15627:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15628:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15629:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15630:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15631:   mimetype: reference to scalar to accommodate mime type determined
                   15632:             from File::MMagic if $parser = parse.
1.608     albertel 15633: 
                   15634:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15635:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15636:  was 'overwrite').
                   15637:  
1.608     albertel 15638: 
                   15639: =item *
                   15640: 
                   15641: renameuserfile(): renames an existing userfile to a new name
                   15642: 
                   15643:   Args:
                   15644:    docuname: username or courseid of destination for the file
                   15645:    docudom: domain of user/course of destination for the file
                   15646:    old: current file name (including any subdirs under userfiles)
                   15647:    new: desired file name (including any subdirs under userfiles)
                   15648: 
                   15649: =item *
                   15650: 
                   15651: mkdiruserfile(): creates a directory is a userfiles dir
                   15652: 
                   15653:   Args:
                   15654:    docuname: username or courseid of destination for the file
                   15655:    docudom: domain of user/course of destination for the file
                   15656:    dir: dir to create (including any subdirs under userfiles)
                   15657: 
                   15658: =item *
                   15659: 
                   15660: removeuserfile(): removes a file that exists in userfiles
                   15661: 
                   15662:   Args:
                   15663:    docuname: username or courseid of destination for the file
                   15664:    docudom: domain of user/course of destination for the file
                   15665:    fname: filname to delete (including any subdirs under userfiles)
                   15666: 
                   15667: =item *
                   15668: 
                   15669: removeuploadedurl(): convience function for removeuserfile()
                   15670: 
                   15671:   Args:
                   15672:    url:  a full /uploaded/... url to delete
                   15673: 
1.747     albertel 15674: =item * 
                   15675: 
                   15676: get_portfile_permissions():
                   15677:   Args:
                   15678:     domain: domain of user or course contain the portfolio files
                   15679:     user: name of user or num of course contain the portfolio files
                   15680:   Returns:
                   15681:     hashref of a dump of the proper file_permissions.db
                   15682:    
                   15683: 
                   15684: =item * 
                   15685: 
                   15686: get_access_controls():
                   15687: 
                   15688: Args:
                   15689:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15690:   group: (optional) the group you want the files associated with
                   15691:   file: (optional) the file you want access info on
                   15692: 
                   15693: Returns:
1.749     raeburn  15694:     a hash (keys are file names) of hashes containing
                   15695:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15696:         values are XML containing access control settings (see below) 
1.747     albertel 15697: 
                   15698: Internal notes:
                   15699: 
1.749     raeburn  15700:  access controls are stored in file_permissions.db as key=value pairs.
                   15701:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15702:         where scope -> public,guest,course,group,domains or users.
                   15703:               end -> UNIX time for end of access (0 -> no end date)
                   15704:               start -> UNIX time for start of access
                   15705: 
                   15706:     value -> XML description of access control
                   15707:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15708:             <start></start>
                   15709:             <end></end>
                   15710: 
                   15711:             <password></password>  for scope type = guest
                   15712: 
                   15713:             <domain></domain>     for scope type = course or group
                   15714:             <number></number>
                   15715:             <roles id="">
                   15716:              <role></role>
                   15717:              <access></access>
                   15718:              <section></section>
                   15719:              <group></group>
                   15720:             </roles>
                   15721: 
                   15722:             <dom></dom>         for scope type = domains
                   15723: 
                   15724:             <users>             for scope type = users
                   15725:              <user>
                   15726:               <uname></uname>
                   15727:               <udom></udom>
                   15728:              </user>
                   15729:             </users>
                   15730:            </scope> 
                   15731:               
                   15732:  Access data is also aggregated for each file in an additional key=value pair:
                   15733:  key -> path to file/file_name\0accesscontrol 
                   15734:  value -> reference to hash
                   15735:           hash contains key = value pairs
                   15736:           where key = uniqueID:scope_end_start
                   15737:                 value = UNIX time record was last updated
                   15738: 
                   15739:           Used to improve speed of look-ups of access controls for each file.  
                   15740:  
                   15741:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15742: 
1.1172.2.13  raeburn  15743: =item *
                   15744: 
1.749     raeburn  15745: modify_access_controls():
                   15746: 
                   15747: Modifies access controls for a portfolio file
                   15748: Args
                   15749: 1. file name
                   15750: 2. reference to hash of required changes,
                   15751: 3. domain
                   15752: 4. username
                   15753:   where domain,username are the domain of the portfolio owner 
                   15754:   (either a user or a course) 
                   15755: 
                   15756: Returns:
                   15757: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15758: 2. result of deletions ('ok' or 'error', with error message).
                   15759: 3. reference to hash of any new or updated access controls.
                   15760: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15761:    key = integer (inbound ID)
1.1172.2.13  raeburn  15762:    value = uniqueID
                   15763: 
                   15764: =item *
                   15765: 
                   15766: get_timebased_id():
                   15767: 
                   15768: Attempts to get a unique timestamp-based suffix for use with items added to a
                   15769: course via the Course Editor (e.g., folders, composite pages,
                   15770: group bulletin boards).
                   15771: 
                   15772: Args: (first three required; six others optional)
                   15773: 
                   15774: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15775:    docssequence, or name of group
                   15776: 
                   15777: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15778:    e.g., num, boardids
                   15779: 
                   15780: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   15781:    file will be named nohist_namespace.db
                   15782: 
                   15783: 4. cdom: domain of course; default is current course domain from %env
                   15784: 
                   15785: 5. cnum: course number; default is current course number from %env
                   15786: 
                   15787: 6. idtype: set to concat if an additional digit is to be appended to the
                   15788:    unix timestamp to form the suffix, if the plain timestamp is already
                   15789:    in use.  Default is to not do this, but simply increment the unix
                   15790:    timestamp by 1 until a unique key is obtained.
                   15791: 
                   15792: 7. who: holder of locking key; defaults to user:domain for user.
                   15793: 
                   15794: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   15795:    retrying); default is 3.
                   15796: 
                   15797: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   15798: 
                   15799: Returns:
                   15800: 
                   15801: 1. suffix obtained (numeric)
                   15802: 
                   15803: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15804: 
                   15805: 3. error: contains (localized) error message if an error occurred.
                   15806: 
1.747     albertel 15807: 
1.608     albertel 15808: =back
                   15809: 
1.243     albertel 15810: =head2 HTTP Helper Routines
                   15811: 
                   15812: =over 4
                   15813: 
1.191     harris41 15814: =item *
                   15815: 
                   15816: escape() : unpack non-word characters into CGI-compatible hex codes
                   15817: 
                   15818: =item *
                   15819: 
                   15820: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15821: 
1.243     albertel 15822: =back
                   15823: 
                   15824: =head1 PRIVATE SUBROUTINES
                   15825: 
                   15826: =head2 Underlying communication routines (Shouldn't call)
                   15827: 
                   15828: =over 4
                   15829: 
                   15830: =item *
                   15831: 
                   15832: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15833: 
                   15834: =item *
                   15835: 
                   15836: reply() : uses subreply to send a message to remote machine, logs all failures
                   15837: 
                   15838: =item *
                   15839: 
                   15840: critical() : passes a critical message to another server; if cannot
                   15841: get through then place message in connection buffer directory and
                   15842: returns con_delayed, if incapable of saving message, returns
                   15843: con_failed
                   15844: 
                   15845: =item *
                   15846: 
                   15847: reconlonc() : tries to reconnect lonc client processes.
                   15848: 
                   15849: =back
                   15850: 
                   15851: =head2 Resource Access Logging
                   15852: 
                   15853: =over 4
                   15854: 
                   15855: =item *
                   15856: 
                   15857: flushcourselogs() : flush (save) buffer logs and access logs
                   15858: 
                   15859: =item *
                   15860: 
                   15861: courselog($what) : save message for course in hash
                   15862: 
                   15863: =item *
                   15864: 
                   15865: courseacclog($what) : save message for course using &courselog().  Perform
                   15866: special processing for specific resource types (problems, exams, quizzes, etc).
                   15867: 
1.191     harris41 15868: =item *
                   15869: 
                   15870: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15871: as a PerlChildExitHandler
1.243     albertel 15872: 
                   15873: =back
                   15874: 
                   15875: =head2 Other
                   15876: 
                   15877: =over 4
                   15878: 
                   15879: =item *
                   15880: 
                   15881: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15882: 
                   15883: =back
                   15884: 
                   15885: =cut
1.877     foxr     15886: 

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