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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.118.  .12(raeb    4:-20): # $Id: lonnet.pm,v 1.1172.2.118.2.11 2020/10/26 01:32:59 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: 
1.1172.2.118.  .11(raeb 1085:-20): sub updatebalcookie {
                   1086:-20):     my ($cookie,$balancer,$lastentry)=@_;
                   1087:-20):     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1088:-20):         my ($udom,$uname) = ($1,$2);
                   1089:-20):         my $uprimary_id = &domain($udom,'primary');
                   1090:-20):         my $uintdom = &internet_dom($uprimary_id);
                   1091:-20):         my $intdom = &internet_dom($balancer);
                   1092:-20):         my $serverhomedom = &host_domain($balancer);
                   1093:-20):         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1094:-20):             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
                   1095:-20):         }
                   1096:-20):     }
                   1097:-20):     return;
                   1098:-20): }
                   1099:-20): 
1.1172.2.107  raeburn  1100: sub delbalcookie {
                   1101:     my ($cookie,$balancer) =@_;
                   1102:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1103:         my ($udom,$uname) = ($1,$2);
                   1104:         my $uprimary_id = &domain($udom,'primary');
                   1105:         my $uintdom = &internet_dom($uprimary_id);
                   1106:         my $intdom = &internet_dom($balancer);
                   1107:         my $serverhomedom = &host_domain($balancer);
                   1108:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1172.2.118.  .11(raeb 1109:-20):             return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1172.2.107  raeburn  1110:         }
                   1111:     }
                   1112: }
                   1113: 
1.914     albertel 1114: # -------------------------------- ask if server already has a session for user
                   1115: sub has_user_session {
                   1116:     my ($lonid,$udom,$uname) = @_;
                   1117:     my $result = &reply(join(':','userhassession',
                   1118: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1119:     return 1 if ($result eq 'ok');
                   1120: 
                   1121:     return 0;
                   1122: }
                   1123: 
1.1076    raeburn  1124: # --------- determine least loaded server in a user's domain which allows login
                   1125: 
                   1126: sub choose_server {
1.1172.2.47  raeburn  1127:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1128:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1129:     my %servers = &get_servers($udom);
1.1076    raeburn  1130:     my $lowest_load = 30000;
1.1172.2.47  raeburn  1131:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1132:     if ($skiploadbal) {
                   1133:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1134:         unless (defined($cached)) {
                   1135:             my $cachetime = 60*60*24;
                   1136:             my %domconfig =
                   1137:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1138:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1139:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1140:                                            $cachetime);
                   1141:             }
                   1142:         }
                   1143:     }
1.1076    raeburn  1144:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn  1145:         my $loginvia;
1.1172.2.47  raeburn  1146:         if ($skiploadbal) {
                   1147:             if (ref($balancers) eq 'HASH') {
                   1148:                 next if (exists($balancers->{$lonhost}));
                   1149:             }
                   1150:         }
1.1115    raeburn  1151:         if ($checkloginvia) {
                   1152:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1153:             if ($loginvia) {
                   1154:                 my ($server,$path) = split(/:/,$loginvia);
                   1155:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1156:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1157:                 if ($login_host eq $server) {
                   1158:                     $portal_path = $path;
1.1151    raeburn  1159:                     $isredirect = 1;
1.1116    raeburn  1160:                 }
                   1161:             } else {
                   1162:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1163:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1164:                 if ($login_host eq $lonhost) {
                   1165:                     $portal_path = '';
1.1151    raeburn  1166:                     $isredirect = ''; 
1.1116    raeburn  1167:                 }
                   1168:             }
                   1169:         } else {
1.1076    raeburn  1170:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1171:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1172:         }
                   1173:     }
                   1174:     if ($login_host ne '') {
1.1116    raeburn  1175:         $hostname = &hostname($login_host);
1.1076    raeburn  1176:     }
1.1172.2.88  raeburn  1177:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1178: }
                   1179: 
1.1172.2.118.  .5(raebu 1180:20): sub get_course_sessions {
                   1181:20):     my ($cnum,$cdom,$lastactivity) = @_;
                   1182:20):     my %servers = &internet_dom_servers($cdom);
                   1183:20):     my %returnhash;
                   1184:20):     foreach my $server (sort(keys(%servers))) {
                   1185:20):         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
                   1186:20):         my @pairs=split(/\&/,$rep);
                   1187:20):         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
                   1188:20):             foreach my $item (@pairs) {
                   1189:20):                 my ($key,$value)=split(/=/,$item,2);
                   1190:20):                 $key = &unescape($key);
                   1191:20):                 next if ($key =~ /^error: 2 /);
                   1192:20):                 if (exists($returnhash{$key})) {
                   1193:20):                     next if ($value < $returnhash{$key});
                   1194:20):                 }
                   1195:20):                 $returnhash{$key}=$value;
                   1196:20):             }
                   1197:20):         }
                   1198:20):     }
                   1199:20):     return %returnhash;
                   1200:20): }
                   1201:20): 
1.202     matthew  1202: # --------------------------------------------- Try to change a user's password
                   1203: 
                   1204: sub changepass {
1.799     raeburn  1205:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1206:     $currentpass = &escape($currentpass);
                   1207:     $newpass     = &escape($newpass);
1.1030    raeburn  1208:     my $lonhost = $perlvar{'lonHostID'};
                   1209:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1210: 		       $server);
                   1211:     if (! $answer) {
                   1212: 	&logthis("No reply on password change request to $server ".
                   1213: 		 "by $uname in domain $udom.");
                   1214:     } elsif ($answer =~ "^ok") {
                   1215:         &logthis("$uname in $udom successfully changed their password ".
                   1216: 		 "on $server.");
                   1217:     } elsif ($answer =~ "^pwchange_failure") {
                   1218: 	&logthis("$uname in $udom was unable to change their password ".
                   1219: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1220: 		 "or pwchange");
                   1221:     } elsif ($answer =~ "^non_authorized") {
                   1222:         &logthis("$uname in $udom did not get their password correct when ".
                   1223: 		 "attempting to change it on $server.");
                   1224:     } elsif ($answer =~ "^auth_mode_error") {
                   1225:         &logthis("$uname in $udom attempted to change their password despite ".
                   1226: 		 "not being locally or internally authenticated on $server.");
                   1227:     } elsif ($answer =~ "^unknown_user") {
                   1228:         &logthis("$uname in $udom attempted to change their password ".
                   1229: 		 "on $server but were unable to because $server is not ".
                   1230: 		 "their home server.");
                   1231:     } elsif ($answer =~ "^refused") {
                   1232: 	&logthis("$server refused to change $uname in $udom password because ".
                   1233: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1234:     } elsif ($answer =~ "invalid_client") {
                   1235:         &logthis("$server refused to change $uname in $udom password because ".
                   1236:                  "it was a reset by e-mail originating from an invalid server.");
1.1172.2.113  raeburn  1237:     } elsif ($answer =~ "^prioruse") {
                   1238:        &logthis("$server refused to change $uname in $udom password because ".
                   1239:                 "the password had been used before");
1.202     matthew  1240:     }
                   1241:     return $answer;
1.1       albertel 1242: }
                   1243: 
1.169     harris41 1244: # ----------------------- Try to determine user's current authentication scheme
                   1245: 
                   1246: sub queryauthenticate {
                   1247:     my ($uname,$udom)=@_;
1.456     albertel 1248:     my $uhome=&homeserver($uname,$udom);
                   1249:     if (!$uhome) {
                   1250: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1251: 	return 'no_host';
                   1252:     }
                   1253:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1254:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1255: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1256:     }
1.456     albertel 1257:     return $answer;
1.169     harris41 1258: }
                   1259: 
1.1       albertel 1260: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1261: 
1.1       albertel 1262: sub authenticate {
1.1073    raeburn  1263:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1264:     $upass=&escape($upass);
                   1265:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1266:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1267:     my $newhome;
1.836     www      1268:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1269: # Maybe the machine was offline and only re-appeared again recently?
                   1270:         &reconlonc();
                   1271: # One more
1.952     raeburn  1272: 	$uhome=&homeserver($uname,$udom,1);
                   1273:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1274:             if (defined(&domain($udom,'primary'))) {
                   1275:                 $newhome=&domain($udom,'primary');
                   1276:             }
                   1277:             if ($newhome ne '') {
                   1278:                 $uhome = $newhome;
                   1279:             }
                   1280:         }
1.836     www      1281: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1282: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1283: 	    return 'no_host';
                   1284:         }
1.1       albertel 1285:     }
1.1073    raeburn  1286:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1287:     if ($answer eq 'authorized') {
1.952     raeburn  1288:         if ($newhome) {
                   1289:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1290:             return 'no_account_on_host'; 
                   1291:         } else {
                   1292:             &logthis("User $uname at $udom authorized by $uhome");
                   1293:             return $uhome;
                   1294:         }
1.471     albertel 1295:     }
                   1296:     if ($answer eq 'non_authorized') {
                   1297: 	&logthis("User $uname at $udom rejected by $uhome");
                   1298: 	return 'no_host'; 
1.9       www      1299:     }
1.471     albertel 1300:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1301:     return 'no_host';
                   1302: }
                   1303: 
1.1073    raeburn  1304: sub can_host_session {
1.1074    raeburn  1305:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1306:     my $canhost = 1;
1.1074    raeburn  1307:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1308:     if (ref($remotesessions) eq 'HASH') {
                   1309:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1310:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1311:                 $canhost = 0;
                   1312:             } else {
                   1313:                 $canhost = 1;
                   1314:             }
                   1315:         }
                   1316:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1317:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1318:                 $canhost = 1;
                   1319:             } else {
                   1320:                 $canhost = 0;
                   1321:             }
                   1322:         }
                   1323:         if ($canhost) {
                   1324:             if ($remotesessions->{'version'} ne '') {
                   1325:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1326:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1327:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1328:                         my $major = $1;
                   1329:                         my $minor = $2;
                   1330:                         if (($major < $reqmajor ) ||
                   1331:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1332:                             $canhost = 0;
                   1333:                         }
                   1334:                     } else {
                   1335:                         $canhost = 0;
                   1336:                     }
                   1337:                 }
                   1338:             }
                   1339:         }
                   1340:     }
                   1341:     if ($canhost) {
                   1342:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1343:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1344:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1345:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1346:                 if (($uint_dom ne '') && 
                   1347:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1348:                     $canhost = 0;
                   1349:                 } else {
                   1350:                     $canhost = 1;
                   1351:                 }
                   1352:             }
                   1353:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1354:                 if (($uint_dom ne '') && 
                   1355:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1356:                     $canhost = 1;
                   1357:                 } else {
                   1358:                     $canhost = 0;
                   1359:                 }
                   1360:             }
                   1361:         }
                   1362:     }
                   1363:     return $canhost;
                   1364: }
                   1365: 
1.1083    raeburn  1366: sub spare_can_host {
                   1367:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1368:     my $canhost=1;
1.1172.2.62  raeburn  1369:     my $try_server_hostname = &hostname($try_server);
                   1370:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1371:     my $serverhomedom = &host_domain($serverhomeID);
                   1372:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1373:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1374:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1375:             $canhost = 0;
                   1376:         }
                   1377:     }
                   1378:     if (($canhost) && ($uint_dom)) {
                   1379:         my @intdoms;
                   1380:         my $internet_names = &get_internet_names($try_server);
                   1381:         if (ref($internet_names) eq 'ARRAY') {
                   1382:             @intdoms = @{$internet_names};
                   1383:         }
                   1384:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1385:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1386:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1387:                                          $remotesessions,
                   1388:                                          $defdomdefaults{'hostedsessions'});
                   1389:         }
1.1083    raeburn  1390:     }
                   1391:     return $canhost;
                   1392: }
                   1393: 
1.1123    raeburn  1394: sub this_host_spares {
                   1395:     my ($dom) = @_;
1.1126    raeburn  1396:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1397:     my @hosts = &current_machine_ids();
                   1398:     foreach my $lonhost (@hosts) {
                   1399:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1400:             $dom_in_use = $dom;
                   1401:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1402:             last;
                   1403:         }
                   1404:     }
1.1126    raeburn  1405:     if ($dom_in_use ne '') {
                   1406:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1407:     }
                   1408:     if (ref($result) ne 'HASH') {
                   1409:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1410:         $dom_in_use = &host_domain($lonhost_in_use);
                   1411:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1412:         if (ref($result) ne 'HASH') {
                   1413:             $result = \%spareid;
                   1414:         }
                   1415:     }
                   1416:     return $result;
                   1417: }
                   1418: 
                   1419: sub spares_for_offload  {
                   1420:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1421:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1422:     if (defined($cached)) {
                   1423:         return $result;
                   1424:     } else {
1.1126    raeburn  1425:         my $cachetime = 60*60*24;
                   1426:         my %domconfig =
                   1427:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1428:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1429:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1430:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1431:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1432:                 }
                   1433:             }
                   1434:         }
                   1435:     }
1.1126    raeburn  1436:     return;
1.1123    raeburn  1437: }
                   1438: 
1.1129    raeburn  1439: sub get_lonbalancer_config {
                   1440:     my ($servers) = @_;
                   1441:     my ($currbalancer,$currtargets);
                   1442:     if (ref($servers) eq 'HASH') {
                   1443:         foreach my $server (keys(%{$servers})) {
                   1444:             my %what = (
                   1445:                          spareid => 1,
                   1446:                          perlvar => 1,
                   1447:                        );
                   1448:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1449:             if ($result eq 'ok') {
                   1450:                 if (ref($returnhash) eq 'HASH') {
                   1451:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1452:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1453:                             $currbalancer = $server;
                   1454:                             $currtargets = {};
                   1455:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1456:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1457:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1458:                                 }
                   1459:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1460:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1461:                                 }
                   1462:                             }
                   1463:                             last;
                   1464:                         }
                   1465:                     }
                   1466:                 }
                   1467:             }
                   1468:         }
                   1469:     }
                   1470:     return ($currbalancer,$currtargets);
                   1471: }
                   1472: 
                   1473: sub check_loadbalancing {
1.1172.2.88  raeburn  1474:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1475:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107  raeburn  1476:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129    raeburn  1477:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1478:     my @hosts = &current_machine_ids();
1.1129    raeburn  1479:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1480:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1481:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1482:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1483:     my $domneedscache; 
1.1129    raeburn  1484:     my $cachetime = 60*60*24;
                   1485: 
                   1486:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1487:         $dom_in_use = $udom;
                   1488:         $homeintdom = 1;
                   1489:     } else {
                   1490:         $dom_in_use = $serverhomedom;
                   1491:     }
                   1492:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1493:     unless (defined($cached)) {
                   1494:         my %domconfig =
                   1495:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1496:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1497:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1498:         } else {
                   1499:             $domneedscache = $dom_in_use;
1.1129    raeburn  1500:         }
                   1501:     }
                   1502:     if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1503:         ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1504:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1505:         if ($is_balancer) {
                   1506:             if (ref($currrules) eq 'HASH') {
                   1507:                 if ($homeintdom) {
                   1508:                     if ($uname ne '') {
                   1509:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1510:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1511:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1512:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1513:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1514:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1515:                             }
                   1516:                         }
                   1517:                         if ($rule_in_effect eq '') {
                   1518:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1519:                             if ($userenv{'inststatus'} ne '') {
                   1520:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1521:                                 my ($othertitle,$usertypes,$types) =
                   1522:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1523:                                 if (ref($types) eq 'ARRAY') {
                   1524:                                     foreach my $type (@{$types}) {
                   1525:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1526:                                             if (exists($currrules->{$type})) {
                   1527:                                                 $rule_in_effect = $currrules->{$type};
                   1528:                                             }
                   1529:                                         }
                   1530:                                     }
                   1531:                                 }
                   1532:                             } else {
                   1533:                                 if (exists($currrules->{'default'})) {
                   1534:                                     $rule_in_effect = $currrules->{'default'};
                   1535:                                 }
                   1536:                             }
                   1537:                         }
                   1538:                     } else {
                   1539:                         if (exists($currrules->{'default'})) {
                   1540:                             $rule_in_effect = $currrules->{'default'};
                   1541:                         }
                   1542:                     }
                   1543:                 } else {
                   1544:                     if ($currrules->{'_LC_external'} ne '') {
                   1545:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1546:                     }
                   1547:                 }
                   1548:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1549:                                                        $uname,$udom);
                   1550:             }
                   1551:         }
                   1552:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1553:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1554:         unless (defined($cached)) {
                   1555:             my %domconfig =
                   1556:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1557:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1558:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1559:             } else {
                   1560:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1561:             }
                   1562:         }
                   1563:         if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1564:             ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1565:                 &check_balancer_result($result,@hosts);
                   1566:             if ($is_balancer) {
1.1129    raeburn  1567:                 if (ref($currrules) eq 'HASH') {
                   1568:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1569:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1570:                     }
                   1571:                 }
                   1572:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1573:                                                        $uname,$udom);
                   1574:             }
                   1575:         } else {
                   1576:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1577:                 $is_balancer = 1;
                   1578:                 $offloadto = &this_host_spares($dom_in_use);
                   1579:             }
1.1172.2.75  raeburn  1580:             unless (defined($cached)) {
                   1581:                 $domneedscache = $serverhomedom;
                   1582:             }
1.1129    raeburn  1583:         }
                   1584:     } else {
                   1585:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1586:             $is_balancer = 1;
                   1587:             $offloadto = &this_host_spares($dom_in_use);
                   1588:         }
1.1172.2.75  raeburn  1589:         unless (defined($cached)) {
                   1590:             $domneedscache = $serverhomedom;
                   1591:         }
                   1592:     }
                   1593:     if ($domneedscache) {
                   1594:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1595:     }
1.1172.2.118.  .11(raeb 1596:-20):     if (($is_balancer) && ($caller ne 'switchserver')) {
1.1172.2.5  raeburn  1597:         my $lowest_load = 30000;
                   1598:         if (ref($offloadto) eq 'HASH') {
                   1599:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1600:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1601:                     ($otherserver,$lowest_load) =
                   1602:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1603:                 }
1.1129    raeburn  1604:             }
1.1172.2.5  raeburn  1605:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1606: 
1.1172.2.5  raeburn  1607:             if (!$found_server) {
                   1608:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1609:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1610:                         ($otherserver,$lowest_load) =
                   1611:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1612:                     }
                   1613:                 }
                   1614:             }
                   1615:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1616:             if (@{$offloadto} == 1) {
                   1617:                 $otherserver = $offloadto->[0];
                   1618:             } elsif (@{$offloadto} > 1) {
                   1619:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1620:                     ($otherserver,$lowest_load) =
                   1621:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1622:                 }
                   1623:             }
                   1624:         }
1.1172.2.88  raeburn  1625:         unless ($caller eq 'login') {
                   1626:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1627:                 $is_balancer = 0;
                   1628:                 if ($uname ne '' && $udom ne '') {
                   1629:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1630:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1631:                                  'user.loadbalcheck.time' => time});
                   1632:                     }
1.1172.2.5  raeburn  1633:                 }
1.1129    raeburn  1634:             }
                   1635:         }
1.1172.2.118.  .11(raeb 1636:-20):     }
                   1637:-20):     if (($is_balancer) && (!$homeintdom)) {
                   1638:-20):         undef($setcookie);
1.1129    raeburn  1639:     }
1.1172.2.107  raeburn  1640:     return ($is_balancer,$otherserver,$setcookie);
1.1129    raeburn  1641: }
                   1642: 
1.1172.2.12  raeburn  1643: sub check_balancer_result {
                   1644:     my ($result,@hosts) = @_;
1.1172.2.107  raeburn  1645:     my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1646:     if (ref($result) eq 'HASH') {
                   1647:         if ($result->{'lonhost'} ne '') {
                   1648:             my $currbalancer = $result->{'lonhost'};
                   1649:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1650:                 $is_balancer = 1;
                   1651:                 $currtargets = $result->{'targets'};
                   1652:                 $currrules = $result->{'rules'};
                   1653:             }
                   1654:         } else {
                   1655:             foreach my $key (keys(%{$result})) {
                   1656:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1657:                     (ref($result->{$key}) eq 'HASH')) {
                   1658:                     $is_balancer = 1;
                   1659:                     $currrules = $result->{$key}{'rules'};
                   1660:                     $currtargets = $result->{$key}{'targets'};
1.1172.2.107  raeburn  1661:                     $setcookie = $result->{$key}{'cookie'};
1.1172.2.12  raeburn  1662:                     last;
                   1663:                 }
                   1664:             }
                   1665:         }
                   1666:     }
1.1172.2.107  raeburn  1667:     return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1668: }
                   1669: 
1.1129    raeburn  1670: sub get_loadbalancer_targets {
                   1671:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1672:     my $offloadto;
1.1172.2.4  raeburn  1673:     if ($rule_in_effect eq 'none') {
                   1674:         return [$perlvar{'lonHostID'}];
                   1675:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1676:         $offloadto = $currtargets;
                   1677:     } else {
                   1678:         if ($rule_in_effect eq 'homeserver') {
                   1679:             my $homeserver = &homeserver($uname,$udom);
                   1680:             if ($homeserver ne 'no_host') {
                   1681:                 $offloadto = [$homeserver];
                   1682:             }
                   1683:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1684:             my %domconfig =
                   1685:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1686:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1687:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1688:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1689:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1690:                     }
                   1691:                 }
                   1692:             } else {
1.1172.2.7  raeburn  1693:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1694:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1695:                 if (&hostname($remotebalancer) ne '') {
                   1696:                     $offloadto = [$remotebalancer];
                   1697:                 }
                   1698:             }
                   1699:         } elsif (&hostname($rule_in_effect) ne '') {
                   1700:             $offloadto = [$rule_in_effect];
                   1701:         }
                   1702:     }
                   1703:     return $offloadto;
                   1704: }
                   1705: 
1.1127    raeburn  1706: sub internet_dom_servers {
                   1707:     my ($dom) = @_;
                   1708:     my (%uniqservers,%servers);
                   1709:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1710:     my @machinedoms = &machine_domains($primaryserver);
                   1711:     foreach my $mdom (@machinedoms) {
                   1712:         my %currservers = %servers;
                   1713:         my %server = &get_servers($mdom);
                   1714:         %servers = (%currservers,%server);
                   1715:     }
                   1716:     my %by_hostname;
                   1717:     foreach my $id (keys(%servers)) {
                   1718:         push(@{$by_hostname{$servers{$id}}},$id);
                   1719:     }
                   1720:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1721:         if (@{$by_hostname{$hostname}} > 1) {
                   1722:             my $match = 0;
                   1723:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1724:                 if (&host_domain($id) eq $dom) {
                   1725:                     $uniqservers{$id} = $hostname;
                   1726:                     $match = 1;
                   1727:                 }
                   1728:             }
                   1729:             unless ($match) {
                   1730:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1731:             }
                   1732:         } else {
                   1733:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1734:         }
                   1735:     }
                   1736:     return %uniqservers;
                   1737: }
                   1738: 
1.1       albertel 1739: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1740: 
1.599     albertel 1741: my %homecache;
1.1       albertel 1742: sub homeserver {
1.230     stredwic 1743:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1744:     my $index="$uname:$udom";
1.426     albertel 1745: 
1.599     albertel 1746:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1747: 
                   1748:     my %servers = &get_servers($udom,'library');
                   1749:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1750:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1751: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1752: 
                   1753: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1754: 	if ($answer eq 'found') {
                   1755: 	    delete($badServerCache{$tryserver}); 
                   1756: 	    return $homecache{$index}=$tryserver;
                   1757: 	} elsif ($answer eq 'no_host') {
                   1758: 	    $badServerCache{$tryserver}=1;
                   1759: 	}
1.1       albertel 1760:     }    
                   1761:     return 'no_host';
1.70      www      1762: }
                   1763: 
                   1764: # ------------------------------------- Find the usernames behind a list of IDs
                   1765: 
                   1766: sub idget {
                   1767:     my ($udom,@ids)=@_;
                   1768:     my %returnhash=();
                   1769:     
1.841     albertel 1770:     my %servers = &get_servers($udom,'library');
                   1771:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1772: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1773: 	$idlist=~tr/A-Z/a-z/; 
                   1774: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1775: 	my @answer=();
                   1776: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1777: 	    @answer=split(/\&/,$reply);
                   1778: 	}                    ;
                   1779: 	my $i;
                   1780: 	for ($i=0;$i<=$#ids;$i++) {
                   1781: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1782: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1783: 	    } 
                   1784: 	}
                   1785:     } 
1.70      www      1786:     return %returnhash;
                   1787: }
                   1788: 
                   1789: # ------------------------------------- Find the IDs behind a list of usernames
                   1790: 
                   1791: sub idrget {
                   1792:     my ($udom,@unames)=@_;
                   1793:     my %returnhash=();
1.800     albertel 1794:     foreach my $uname (@unames) {
                   1795:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1796:     }
1.70      www      1797:     return %returnhash;
                   1798: }
                   1799: 
                   1800: # ------------------------------- Store away a list of names and associated IDs
                   1801: 
                   1802: sub idput {
                   1803:     my ($udom,%ids)=@_;
                   1804:     my %servers=();
1.800     albertel 1805:     foreach my $uname (keys(%ids)) {
                   1806: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1807:         my $uhom=&homeserver($uname,$udom);
1.70      www      1808:         if ($uhom ne 'no_host') {
1.800     albertel 1809:             my $id=&escape($ids{$uname});
1.70      www      1810:             $id=~tr/A-Z/a-z/;
1.800     albertel 1811:             my $esc_unam=&escape($uname);
1.70      www      1812: 	    if ($servers{$uhom}) {
1.800     albertel 1813: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1814:             } else {
1.800     albertel 1815:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1816:             }
                   1817:         }
1.191     harris41 1818:     }
1.800     albertel 1819:     foreach my $server (keys(%servers)) {
                   1820:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1821:     }
1.344     www      1822: }
                   1823: 
1.1172.2.30  raeburn  1824: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1825: 
                   1826: sub iddel {
                   1827:     my ($udom,$idshashref,$uhome)=@_;
                   1828:     my %result=();
                   1829:     unless (ref($idshashref) eq 'HASH') {
                   1830:         return %result;
                   1831:     }
                   1832:     my %servers=();
                   1833:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1834:         my $uhom;
                   1835:         if ($uhome) {
                   1836:             $uhom = $uhome;
                   1837:         } else {
                   1838:             $uhom=&homeserver($uname,$udom);
                   1839:         }
                   1840:         if ($uhom ne 'no_host') {
                   1841:             if ($servers{$uhom}) {
                   1842:                 $servers{$uhom}.='&'.&escape($id);
                   1843:             } else {
                   1844:                 $servers{$uhom}=&escape($id);
                   1845:             }
                   1846:         }
                   1847:     }
                   1848:     foreach my $server (keys(%servers)) {
                   1849:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1850:     }
                   1851:     return %result;
                   1852: }
                   1853: 
1.1023    raeburn  1854: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1855: sub dump_dom {
1.1165    droeschl 1856:     my ($namespace, $udom, $regexp) = @_;
                   1857: 
                   1858:     $udom ||= $env{'user.domain'};
                   1859: 
                   1860:     return () unless $udom;
                   1861: 
                   1862:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1863: }
                   1864: 
1.1023    raeburn  1865: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1866: 
                   1867: sub get_dom {
1.860     raeburn  1868:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1869:     return if ($udom eq 'public');
1.806     raeburn  1870:     my $items='';
                   1871:     foreach my $item (@$storearr) {
                   1872:         $items.=&escape($item).'&';
                   1873:     }
                   1874:     $items=~s/\&$//;
1.860     raeburn  1875:     if (!$udom) {
                   1876:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1877:         return if ($udom eq 'public');
1.860     raeburn  1878:         if (defined(&domain($udom,'primary'))) {
                   1879:             $uhome=&domain($udom,'primary');
                   1880:         } else {
1.874     albertel 1881:             undef($uhome);
1.860     raeburn  1882:         }
                   1883:     } else {
                   1884:         if (!$uhome) {
                   1885:             if (defined(&domain($udom,'primary'))) {
                   1886:                 $uhome=&domain($udom,'primary');
                   1887:             }
                   1888:         }
                   1889:     }
                   1890:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1172.2.118.  .1(raebu 1891:20):         my $rep;
                   1892:20):         if ($namespace =~ /^enc/) {
                   1893:20):             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   1894:20):         } else {
                   1895:20):             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   1896:20):         }
1.866     raeburn  1897:         my %returnhash;
1.875     albertel 1898:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1899:             return %returnhash;
                   1900:         }
1.806     raeburn  1901:         my @pairs=split(/\&/,$rep);
                   1902:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1903:             return @pairs;
                   1904:         }
                   1905:         my $i=0;
                   1906:         foreach my $item (@$storearr) {
                   1907:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1908:             $i++;
                   1909:         }
                   1910:         return %returnhash;
                   1911:     } else {
1.880     banghart 1912:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1913:     }
                   1914: }
                   1915: 
                   1916: # -------------------------------------------- put items in domain db files 
                   1917: 
                   1918: sub put_dom {
1.860     raeburn  1919:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1920:     if (!$udom) {
                   1921:         $udom=$env{'user.domain'};
                   1922:         if (defined(&domain($udom,'primary'))) {
                   1923:             $uhome=&domain($udom,'primary');
                   1924:         } else {
1.874     albertel 1925:             undef($uhome);
1.860     raeburn  1926:         }
                   1927:     } else {
                   1928:         if (!$uhome) {
                   1929:             if (defined(&domain($udom,'primary'))) {
                   1930:                 $uhome=&domain($udom,'primary');
                   1931:             }
                   1932:         }
                   1933:     } 
                   1934:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1935:         my $items='';
                   1936:         foreach my $item (keys(%$storehash)) {
                   1937:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1938:         }
                   1939:         $items=~s/\&$//;
1.1172.2.118.  .1(raebu 1940:20):         if ($namespace =~ /^enc/) {
                   1941:20):             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   1942:20):         } else {
                   1943:20):             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1944:20):         }
1.806     raeburn  1945:     } else {
1.860     raeburn  1946:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1947:     }
                   1948: }
                   1949: 
1.1023    raeburn  1950: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1951: sub newput_dom {
1.1023    raeburn  1952:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1953:     my $result;
                   1954:     if (!$udom) {
                   1955:         $udom=$env{'user.domain'};
                   1956:     }
1.1023    raeburn  1957:     if ($udom) {
                   1958:         my $uname = &get_domainconfiguser($udom);
                   1959:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1960:     }
                   1961:     return $result;
                   1962: }
                   1963: 
1.1023    raeburn  1964: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1965: sub del_dom {
1.1023    raeburn  1966:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1967:     if (ref($storearr) eq 'ARRAY') {
                   1968:         if (!$udom) {
                   1969:             $udom=$env{'user.domain'};
                   1970:         }
1.1023    raeburn  1971:         if ($udom) {
                   1972:             my $uname = &get_domainconfiguser($udom); 
                   1973:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1974:         }
                   1975:     }
                   1976: }
                   1977: 
1.1023    raeburn  1978: # ----------------------------------construct domainconfig user for a domain 
                   1979: sub get_domainconfiguser {
                   1980:     my ($udom) = @_;
                   1981:     return $udom.'-domainconfig';
                   1982: }
                   1983: 
1.837     raeburn  1984: sub retrieve_inst_usertypes {
                   1985:     my ($udom) = @_;
                   1986:     my (%returnhash,@order);
1.989     raeburn  1987:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1988:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1989:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  1990:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1991:     } else {
                   1992:         if (defined(&domain($udom,'primary'))) {
                   1993:             my $uhome=&domain($udom,'primary');
                   1994:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1995:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  1996:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1997:                 return (\%returnhash,\@order);
                   1998:             }
                   1999:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2000:             my @pairs=split(/\&/,$hashitems);
                   2001:             foreach my $item (@pairs) {
                   2002:                 my ($key,$value)=split(/=/,$item,2);
                   2003:                 $key = &unescape($key);
                   2004:                 next if ($key =~ /^error: 2 /);
                   2005:                 $returnhash{$key}=&thaw_unescape($value);
                   2006:             }
                   2007:             my @esc_order = split(/\&/,$orderitems);
                   2008:             foreach my $item (@esc_order) {
                   2009:                 push(@order,&unescape($item));
                   2010:             }
                   2011:         } else {
1.1172.2.44  raeburn  2012:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2013:         }
1.1172.2.44  raeburn  2014:         return (\%returnhash,\@order);
1.837     raeburn  2015:     }
                   2016: }
                   2017: 
1.868     raeburn  2018: sub is_domainimage {
                   2019:     my ($url) = @_;
1.1172.2.74  raeburn  2020:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2021:         if (&domain($1) ne '') {
                   2022:             return '1';
                   2023:         }
                   2024:     }
                   2025:     return;
                   2026: }
                   2027: 
1.899     raeburn  2028: sub inst_directory_query {
                   2029:     my ($srch) = @_;
                   2030:     my $udom = $srch->{'srchdomain'};
                   2031:     my %results;
                   2032:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2033:     my $outcome;
1.899     raeburn  2034:     if ($homeserver ne '') {
1.1172.2.116  raeburn  2035:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2036:             if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2037:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116  raeburn  2038:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
                   2039:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2040:                     (($major == 2) && ($minor < 11)) ||
                   2041:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
                   2042:                     return;
                   2043:                 }
                   2044:             }
                   2045:         }
1.904     albertel 2046: 	my $queryid=&reply("querysend:instdirsearch:".
                   2047: 			   &escape($srch->{'srchby'}).':'.
                   2048: 			   &escape($srch->{'srchterm'}).':'.
                   2049: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2050: 	my $host=&hostname($homeserver);
                   2051: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  2052: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2053: 	    return;
                   2054: 	}
                   2055: 	my $response = &get_query_reply($queryid);
                   2056: 	my $maxtries = 5;
                   2057: 	my $tries = 1;
                   2058: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2059: 	    $response = &get_query_reply($queryid);
                   2060: 	    $tries ++;
                   2061: 	}
                   2062: 
                   2063:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2064:             if ($response eq 'unavailable') {
                   2065:                 $outcome = $response;
                   2066:             } else {
                   2067:                 $outcome = 'ok';
                   2068:                 my @matches = split(/\n/,$response);
                   2069:                 foreach my $match (@matches) {
                   2070:                     my ($key,$value) = split(/=/,$match);
                   2071:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2072:                 }
1.899     raeburn  2073:             }
                   2074:         }
                   2075:     }
1.909     raeburn  2076:     return ($outcome,%results);
1.899     raeburn  2077: }
                   2078: 
                   2079: sub usersearch {
                   2080:     my ($srch) = @_;
                   2081:     my $dom = $srch->{'srchdomain'};
                   2082:     my %results;
                   2083:     my %libserv = &all_library();
                   2084:     my $query = 'usersearch';
                   2085:     foreach my $tryserver (keys(%libserv)) {
                   2086:         if (&host_domain($tryserver) eq $dom) {
1.1172.2.116  raeburn  2087:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2088:                 if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2089:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.118.  .2(raebu 2090:20):                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116  raeburn  2091:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2092:                              (($major == 2) && ($minor < 11)) ||
                   2093:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
                   2094:                 }
                   2095:             }
1.899     raeburn  2096:             my $host=&hostname($tryserver);
                   2097:             my $queryid=
1.911     raeburn  2098:                 &reply("querysend:".&escape($query).':'.
                   2099:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2100:                        &escape($srch->{'srchtype'}).':'.
                   2101:                        &escape($srch->{'srchterm'}),$tryserver);
                   2102:             if ($queryid !~/^\Q$host\E\_/) {
                   2103:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2104:                 next;
1.899     raeburn  2105:             }
                   2106:             my $reply = &get_query_reply($queryid);
                   2107:             my $maxtries = 1;
                   2108:             my $tries = 1;
                   2109:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2110:                 $reply = &get_query_reply($queryid);
                   2111:                 $tries ++;
                   2112:             }
                   2113:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2114:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2115:             } else {
1.911     raeburn  2116:                 my @matches;
                   2117:                 if ($reply =~ /\n/) {
                   2118:                     @matches = split(/\n/,$reply);
                   2119:                 } else {
                   2120:                     @matches = split(/\&/,$reply);
                   2121:                 }
1.899     raeburn  2122:                 foreach my $match (@matches) {
                   2123:                     my ($uname,$udom,%userhash);
1.911     raeburn  2124:                     foreach my $entry (split(/:/,$match)) {
                   2125:                         my ($key,$value) =
                   2126:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2127:                         $userhash{$key} = $value;
                   2128:                         if ($key eq 'username') {
                   2129:                             $uname = $value;
                   2130:                         } elsif ($key eq 'domain') {
                   2131:                             $udom = $value;
1.911     raeburn  2132:                         }
1.899     raeburn  2133:                     }
                   2134:                     $results{$uname.':'.$udom} = \%userhash;
                   2135:                 }
                   2136:             }
                   2137:         }
                   2138:     }
                   2139:     return %results;
                   2140: }
                   2141: 
1.912     raeburn  2142: sub get_instuser {
                   2143:     my ($udom,$uname,$id) = @_;
                   2144:     my $homeserver = &domain($udom,'primary');
                   2145:     my ($outcome,%results);
                   2146:     if ($homeserver ne '') {
                   2147:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2148:                            &escape($id).':'.&escape($udom),$homeserver);
                   2149:         my $host=&hostname($homeserver);
                   2150:         if ($queryid !~/^\Q$host\E\_/) {
                   2151:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2152:             return;
                   2153:         }
                   2154:         my $response = &get_query_reply($queryid);
                   2155:         my $maxtries = 5;
                   2156:         my $tries = 1;
                   2157:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2158:             $response = &get_query_reply($queryid);
                   2159:             $tries ++;
                   2160:         }
                   2161:         if (!&error($response) && $response ne 'refused') {
                   2162:             if ($response eq 'unavailable') {
                   2163:                 $outcome = $response;
                   2164:             } else {
                   2165:                 $outcome = 'ok';
                   2166:                 my @matches = split(/\n/,$response);
                   2167:                 foreach my $match (@matches) {
                   2168:                     my ($key,$value) = split(/=/,$match);
                   2169:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2170:                 }
                   2171:             }
                   2172:         }
                   2173:     }
                   2174:     my %userinfo;
                   2175:     if (ref($results{$uname}) eq 'HASH') {
                   2176:         %userinfo = %{$results{$uname}};
                   2177:     } 
                   2178:     return ($outcome,%userinfo);
                   2179: }
                   2180: 
1.1172.2.69  raeburn  2181: sub get_multiple_instusers {
                   2182:     my ($udom,$users,$caller) = @_;
                   2183:     my ($outcome,$results);
                   2184:     if (ref($users) eq 'HASH') {
                   2185:         my $count = keys(%{$users});
                   2186:         my $requested = &freeze_escape($users);
                   2187:         my $homeserver = &domain($udom,'primary');
                   2188:         if ($homeserver ne '') {
                   2189:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2190:             my $host=&hostname($homeserver);
                   2191:             if ($queryid !~/^\Q$host\E\_/) {
                   2192:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2193:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2194:                 return ($outcome,$results);
                   2195:             }
                   2196:             my $response = &get_query_reply($queryid);
                   2197:             my $maxtries = 5;
                   2198:             if ($count > 100) {
                   2199:                 $maxtries = 1+int($count/20);
                   2200:             }
                   2201:             my $tries = 1;
                   2202:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2203:                 $response = &get_query_reply($queryid);
                   2204:                 $tries ++;
                   2205:             }
                   2206:             if ($response eq '') {
                   2207:                 $results = {};
                   2208:                 foreach my $key (keys(%{$users})) {
                   2209:                     my ($uname,$id);
                   2210:                     if ($caller eq 'id') {
                   2211:                         $id = $key;
                   2212:                     } else {
                   2213:                         $uname = $key;
                   2214:                     }
                   2215:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2216:                     $outcome = $resp;
                   2217:                     if ($resp eq 'ok') {
                   2218:                         %{$results} = (%{$results}, %info);
                   2219:                     } else {
                   2220:                         last;
                   2221:                     }
                   2222:                 }
                   2223:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2224:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2225:                     $outcome = $response;
                   2226:                 } else {
                   2227:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2228:                     if ($outcome eq 'ok') {
                   2229:                         $results = &thaw_unescape($userdata);
                   2230:                     }
                   2231:                 }
                   2232:             }
                   2233:         }
                   2234:     }
                   2235:     return ($outcome,$results);
                   2236: }
                   2237: 
1.912     raeburn  2238: sub inst_rulecheck {
1.923     raeburn  2239:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2240:     my %returnhash;
                   2241:     if ($udom ne '') {
                   2242:         if (ref($rules) eq 'ARRAY') {
                   2243:             @{$rules} = map {&escape($_);} (@{$rules});
                   2244:             my $rulestr = join(':',@{$rules});
                   2245:             my $homeserver=&domain($udom,'primary');
                   2246:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2247:                 my $response;
                   2248:                 if ($item eq 'username') {                
                   2249:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2250:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2251:                                               $homeserver));
1.923     raeburn  2252:                 } elsif ($item eq 'id') {
                   2253:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2254:                                               ':'.&escape($id).':'.$rulestr,
                   2255:                                               $homeserver));
1.945     raeburn  2256:                 } elsif ($item eq 'selfcreate') {
                   2257:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2258:                                                &escape($udom).':'.&escape($uname).
                   2259:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2260:                 }
1.912     raeburn  2261:                 if ($response ne 'refused') {
                   2262:                     my @pairs=split(/\&/,$response);
                   2263:                     foreach my $item (@pairs) {
                   2264:                         my ($key,$value)=split(/=/,$item,2);
                   2265:                         $key = &unescape($key);
                   2266:                         next if ($key =~ /^error: 2 /);
                   2267:                         $returnhash{$key}=&thaw_unescape($value);
                   2268:                     }
                   2269:                 }
                   2270:             }
                   2271:         }
                   2272:     }
                   2273:     return %returnhash;
                   2274: }
                   2275: 
                   2276: sub inst_userrules {
1.923     raeburn  2277:     my ($udom,$check) = @_;
1.912     raeburn  2278:     my (%ruleshash,@ruleorder);
                   2279:     if ($udom ne '') {
                   2280:         my $homeserver=&domain($udom,'primary');
                   2281:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2282:             my $response;
                   2283:             if ($check eq 'id') {
                   2284:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2285:                                  $homeserver);
1.943     raeburn  2286:             } elsif ($check eq 'email') {
                   2287:                 $response=&reply('instemailrules:'.&escape($udom),
                   2288:                                  $homeserver);
1.923     raeburn  2289:             } else {
                   2290:                 $response=&reply('instuserrules:'.&escape($udom),
                   2291:                                  $homeserver);
                   2292:             }
1.912     raeburn  2293:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2294:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2295:                 ($response ne 'no_such_host')) {
                   2296:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2297:                 my @pairs=split(/\&/,$hashitems);
                   2298:                 foreach my $item (@pairs) {
                   2299:                     my ($key,$value)=split(/=/,$item,2);
                   2300:                     $key = &unescape($key);
                   2301:                     next if ($key =~ /^error: 2 /);
                   2302:                     $ruleshash{$key}=&thaw_unescape($value);
                   2303:                 }
                   2304:                 my @esc_order = split(/\&/,$orderitems);
                   2305:                 foreach my $item (@esc_order) {
                   2306:                     push(@ruleorder,&unescape($item));
                   2307:                 }
                   2308:             }
                   2309:         }
                   2310:     }
                   2311:     return (\%ruleshash,\@ruleorder);
                   2312: }
                   2313: 
1.976     raeburn  2314: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2315: 
                   2316: sub get_domain_defaults {
1.1172.2.35  raeburn  2317:     my ($domain,$ignore_cache) = @_;
                   2318:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2319:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2320:     unless ($ignore_cache) {
                   2321:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2322:         if (defined($cached)) {
                   2323:             if (ref($result) eq 'HASH') {
                   2324:                 return %{$result};
                   2325:             }
1.943     raeburn  2326:         }
                   2327:     }
                   2328:     my %domdefaults;
                   2329:     my %domconfig =
1.989     raeburn  2330:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2331:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2332:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2333:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2334:                                   'coursecategories','autoenroll',
                   2335:                                   'helpsettings'],$domain);
1.1172.2.41  raeburn  2336:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2337:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2338:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2339:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2340:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2341:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2342:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2343:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2344:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2345:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2346:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2347:     } else {
                   2348:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2349:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2350:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2351:     }
1.976     raeburn  2352:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2353:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2354:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2355:         } else {
                   2356:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2357:         }
1.1172.2.6  raeburn  2358:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2359:         foreach my $item (@usertools) {
                   2360:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2361:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2362:             }
                   2363:         }
1.1172.2.29  raeburn  2364:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2365:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2366:         }
1.976     raeburn  2367:     }
1.985     raeburn  2368:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2369:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2370:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2371:         }
                   2372:     }
1.1172.2.9  raeburn  2373:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2374:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2375:     }
1.989     raeburn  2376:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2377:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2378:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2379:         }
                   2380:     }
1.1047    raeburn  2381:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2382:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2383:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2384:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2385:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2386:         }
1.1172.2.41  raeburn  2387:         foreach my $type (@coursetypes) {
                   2388:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2389:                 unless ($type eq 'community') {
                   2390:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2391:                 }
                   2392:             }
                   2393:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2394:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2395:             }
1.1172.2.60  raeburn  2396:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2397:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2398:                     $domdefaults{$type.'postsubtimeout'} =
                   2399:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2400:                 }
                   2401:             }
1.1172.2.30  raeburn  2402:         }
1.1172.2.67  raeburn  2403:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2404:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2405:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2406:                 if (@clonecodes) {
                   2407:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2408:                 }
                   2409:             }
                   2410:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2411:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2412:         }
1.1172.2.103  raeburn  2413:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2414:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2415:         }
1.1047    raeburn  2416:     }
1.1073    raeburn  2417:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2418:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2419:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2420:         }
                   2421:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2422:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2423:         }
1.1172.2.62  raeburn  2424:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2425:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2426:         }
1.1073    raeburn  2427:     }
1.1172.2.41  raeburn  2428:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2429:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2430:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2431:                             'approval','limit');
                   2432:             foreach my $type (@coursetypes) {
                   2433:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2434:                     my @mgrdc = ();
                   2435:                     foreach my $item (@settings) {
                   2436:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2437:                             push(@mgrdc,$item);
                   2438:                         }
                   2439:                     }
                   2440:                     if (@mgrdc) {
                   2441:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2442:                     }
                   2443:                 }
                   2444:             }
                   2445:         }
                   2446:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2447:             foreach my $type (@coursetypes) {
                   2448:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2449:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2450:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2451:                     }
                   2452:                 }
                   2453:             }
                   2454:         }
                   2455:     }
1.1172.2.46  raeburn  2456:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2457:         $domdefaults{'catauth'} = 'std';
                   2458:         $domdefaults{'catunauth'} = 'std';
                   2459:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2460:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2461:         }
                   2462:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2463:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2464:         }
                   2465:     }
1.1172.2.76  raeburn  2466:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2467:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2468:     }
1.1172.2.89  raeburn  2469:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2470:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2471:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2472:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2473:         }
                   2474:     }
1.1172.2.23  raeburn  2475:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2476:     return %domdefaults;
                   2477: }
                   2478: 
1.1172.2.106  raeburn  2479: sub get_dom_cats {
                   2480:     my ($dom) = @_;
                   2481:     return unless (&domain($dom));
                   2482:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2483:     unless (defined($cached)) {
                   2484:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2485:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2486:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2487:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2488:             } else {
                   2489:                 $cats = {};
                   2490:             }
                   2491:         } else {
                   2492:             $cats = {};
                   2493:         }
                   2494:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2495:     }
                   2496:     return $cats;
                   2497: }
                   2498: 
                   2499: sub get_dom_instcats {
                   2500:     my ($dom) = @_;
                   2501:     return unless (&domain($dom));
                   2502:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2503:     unless (defined($cached)) {
                   2504:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2505:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2506:         if ($totcodes > 0) {
                   2507:             my $caller = 'global';
                   2508:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2509:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2510:                 $instcats = {
                   2511:                                 codes => \%codes,
                   2512:                                 codetitles => \@codetitles,
                   2513:                                 cat_titles => \%cat_titles,
                   2514:                                 cat_order => \%cat_order,
                   2515:                             };
                   2516:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2517:             }
                   2518:         }
                   2519:     }
                   2520:     return $instcats;
                   2521: }
                   2522: 
                   2523: sub retrieve_instcodes {
                   2524:     my ($coursecodes,$dom) = @_;
                   2525:     my $totcodes;
                   2526:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2527:     foreach my $course (keys(%courses)) {
                   2528:         if (ref($courses{$course}) eq 'HASH') {
                   2529:             if ($courses{$course}{'inst_code'} ne '') {
                   2530:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2531:                 $totcodes ++;
                   2532:             }
                   2533:         }
                   2534:     }
                   2535:     return $totcodes;
                   2536: }
                   2537: 
1.1172.2.113  raeburn  2538: # --------------------------------------------- Get domain config for passwords
                   2539: 
                   2540: sub get_passwdconf {
                   2541:     my ($dom) = @_;
                   2542:     my (%passwdconf,$gotconf,$lookup);
                   2543:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2544:     if (defined($cached)) {
                   2545:         if (ref($result) eq 'HASH') {
                   2546:             %passwdconf = %{$result};
                   2547:             $gotconf = 1;
                   2548:         }
                   2549:     }
                   2550:     unless ($gotconf) {
                   2551:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2552:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2553:             %passwdconf = %{$domconfig{'passwords'}};
                   2554:         }
                   2555:         my $cachetime = 24*60*60;
                   2556:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2557:     }
                   2558:     return %passwdconf;
                   2559: }
                   2560: 
1.1172.2.118.  .1(raebu 2561:20): sub course_portal_url {
                   2562:20):     my ($cnum,$cdom) = @_;
                   2563:20):     my $chome = &homeserver($cnum,$cdom);
                   2564:20):     my $hostname = &hostname($chome);
                   2565:20):     my $protocol = $protocol{$chome};
                   2566:20):     $protocol = 'http' if ($protocol ne 'https');
                   2567:20):     my %domdefaults = &get_domain_defaults($cdom);
                   2568:20):     my $firsturl;
                   2569:20):     if ($domdefaults{'portal_def'}) {
                   2570:20):         $firsturl = $domdefaults{'portal_def'};
                   2571:20):     } else {
                   2572:20):         $firsturl = $protocol.'://'.$hostname;
                   2573:20):     }
                   2574:20):     return $firsturl;
                   2575:20): }
                   2576:20): 
1.344     www      2577: # --------------------------------------------------- Assign a key to a student
                   2578: 
                   2579: sub assign_access_key {
1.364     www      2580: #
                   2581: # a valid key looks like uname:udom#comments
                   2582: # comments are being appended
                   2583: #
1.498     www      2584:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2585:     $kdom=
1.620     albertel 2586:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2587:     $knum=
1.620     albertel 2588:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2589:     $cdom=
1.620     albertel 2590:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2591:     $cnum=
1.620     albertel 2592:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2593:     $udom=$env{'user.name'} unless (defined($udom));
                   2594:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2595:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2596:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2597:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2598:                                                   # assigned to this person
                   2599:                                                   # - this should not happen,
1.345     www      2600:                                                   # unless something went wrong
                   2601:                                                   # the first time around
                   2602: # ready to assign
1.364     www      2603:         $logentry=$1.'; '.$logentry;
1.496     www      2604:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2605:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2606: # key now belongs to user
1.346     www      2607: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2608:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2609:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2610:                 return 'ok';
                   2611:             } else {
                   2612:                 return 
                   2613:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2614: 	    }
                   2615:         } else {
                   2616:             return 'error: Could not assign key, try again later.';
                   2617:         }
1.364     www      2618:     } elsif (!$existing{$ckey}) {
1.345     www      2619: # the key does not exist
                   2620: 	return 'error: The key does not exist';
                   2621:     } else {
                   2622: # the key is somebody else's
                   2623: 	return 'error: The key is already in use';
                   2624:     }
1.344     www      2625: }
                   2626: 
1.364     www      2627: # ------------------------------------------ put an additional comment on a key
                   2628: 
                   2629: sub comment_access_key {
                   2630: #
                   2631: # a valid key looks like uname:udom#comments
                   2632: # comments are being appended
                   2633: #
                   2634:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2635:     $cdom=
1.620     albertel 2636:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2637:     $cnum=
1.620     albertel 2638:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2639:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2640:     if ($existing{$ckey}) {
                   2641:         $existing{$ckey}.='; '.$logentry;
                   2642: # ready to assign
1.367     www      2643:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2644:                                                  $cdom,$cnum) eq 'ok') {
                   2645: 	    return 'ok';
                   2646:         } else {
                   2647: 	    return 'error: Count not store comment.';
                   2648:         }
                   2649:     } else {
                   2650: # the key does not exist
                   2651: 	return 'error: The key does not exist';
                   2652:     }
                   2653: }
                   2654: 
1.344     www      2655: # ------------------------------------------------------ Generate a set of keys
                   2656: 
                   2657: sub generate_access_keys {
1.364     www      2658:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2659:     $cdom=
1.620     albertel 2660:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2661:     $cnum=
1.620     albertel 2662:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2663:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2664:     unless (($cdom) && ($cnum)) { return 0; }
                   2665:     if ($number>10000) { return 0; }
                   2666:     sleep(2); # make sure don't get same seed twice
                   2667:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2668:     my $total=0;
                   2669:     for (my $i=1;$i<=$number;$i++) {
                   2670:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2671:                   sprintf("%lx",int(100000*rand)).'-'.
                   2672:                   sprintf("%lx",int(100000*rand));
                   2673:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2674:        $newkey=~s/0/h/g; # and also 0 and O
                   2675:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2676:        if ($existing{$newkey}) {
                   2677:            $i--;
                   2678:        } else {
1.364     www      2679: 	  if (&put('accesskeys',
                   2680:               { $newkey => '# generated '.localtime().
1.620     albertel 2681:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2682:                            '; '.$logentry },
                   2683: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2684:               $total++;
                   2685: 	  }
                   2686:        }
                   2687:     }
1.620     albertel 2688:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2689:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2690:     return $total;
                   2691: }
                   2692: 
                   2693: # ------------------------------------------------------- Validate an accesskey
                   2694: 
                   2695: sub validate_access_key {
                   2696:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2697:     $cdom=
1.620     albertel 2698:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2699:     $cnum=
1.620     albertel 2700:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2701:     $udom=$env{'user.domain'} unless (defined($udom));
                   2702:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2703:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2704:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2705: }
                   2706: 
                   2707: # ------------------------------------- Find the section of student in a course
1.652     albertel 2708: sub devalidate_getsection_cache {
                   2709:     my ($udom,$unam,$courseid)=@_;
                   2710:     my $hashid="$udom:$unam:$courseid";
                   2711:     &devalidate_cache_new('getsection',$hashid);
                   2712: }
1.298     matthew  2713: 
1.815     albertel 2714: sub courseid_to_courseurl {
                   2715:     my ($courseid) = @_;
                   2716:     #already url style courseid
                   2717:     return $courseid if ($courseid =~ m{^/});
                   2718: 
                   2719:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2720: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2721: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2722: 	return "/$cdom/$cnum";
                   2723:     }
                   2724: 
                   2725:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2726:     if (exists($courseinfo{'num'})) {
                   2727: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2728:     }
                   2729: 
                   2730:     return undef;
                   2731: }
                   2732: 
1.298     matthew  2733: sub getsection {
                   2734:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2735:     my $cachetime=1800;
1.551     albertel 2736: 
                   2737:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2738:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2739:     if (defined($cached)) { return $result; }
                   2740: 
1.298     matthew  2741:     my %Pending; 
                   2742:     my %Expired;
                   2743:     #
                   2744:     # Each role can either have not started yet (pending), be active, 
                   2745:     #    or have expired.
                   2746:     #
                   2747:     # If there is an active role, we are done.
                   2748:     #
                   2749:     # If there is more than one role which has not started yet, 
                   2750:     #     choose the one which will start sooner
                   2751:     # If there is one role which has not started yet, return it.
                   2752:     #
                   2753:     # If there is more than one expired role, choose the one which ended last.
                   2754:     # If there is a role which has expired, return it.
                   2755:     #
1.815     albertel 2756:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2757:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2758:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2759:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2760:         my $section=$1;
                   2761:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2762:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2763:         my $now=time;
1.548     albertel 2764:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2765:             $Expired{$end}=$section;
                   2766:             next;
                   2767:         }
1.548     albertel 2768:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2769:             $Pending{$start}=$section;
                   2770:             next;
                   2771:         }
1.599     albertel 2772:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2773:     }
                   2774:     #
                   2775:     # Presumedly there will be few matching roles from the above
                   2776:     # loop and the sorting time will be negligible.
                   2777:     if (scalar(keys(%Pending))) {
                   2778:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2779:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2780:     } 
                   2781:     if (scalar(keys(%Expired))) {
                   2782:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2783:         my $time = pop(@sorted);
1.599     albertel 2784:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2785:     }
1.599     albertel 2786:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2787: }
1.70      www      2788: 
1.599     albertel 2789: sub save_cache {
                   2790:     &purge_remembered();
1.722     albertel 2791:     #&Apache::loncommon::validate_page();
1.620     albertel 2792:     undef(%env);
1.780     albertel 2793:     undef($env_loaded);
1.599     albertel 2794: }
1.452     albertel 2795: 
1.599     albertel 2796: my $to_remember=-1;
                   2797: my %remembered;
                   2798: my %accessed;
                   2799: my $kicks=0;
                   2800: my $hits=0;
1.849     albertel 2801: sub make_key {
                   2802:     my ($name,$id) = @_;
1.872     albertel 2803:     if (length($id) > 65 
                   2804: 	&& length(&escape($id)) > 200) {
                   2805: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2806:     }
1.849     albertel 2807:     return &escape($name.':'.$id);
                   2808: }
                   2809: 
1.599     albertel 2810: sub devalidate_cache_new {
                   2811:     my ($name,$id,$debug) = @_;
                   2812:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2813:     my $remembered_id=$name.':'.$id;
1.849     albertel 2814:     $id=&make_key($name,$id);
1.599     albertel 2815:     $memcache->delete($id);
1.1172.2.81  raeburn  2816:     delete($remembered{$remembered_id});
                   2817:     delete($accessed{$remembered_id});
1.599     albertel 2818: }
                   2819: 
                   2820: sub is_cached_new {
                   2821:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2822:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2823:                                      # keys in %remembered hash, which persists for
                   2824:                                      # duration of request (no restriction on key length).
                   2825:     if (exists($remembered{$remembered_id})) {
                   2826: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2827: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2828: 	$hits++;
1.1172.2.81  raeburn  2829: 	return ($remembered{$remembered_id},1);
1.599     albertel 2830:     }
1.1172.2.81  raeburn  2831:     $id=&make_key($name,$id);
1.599     albertel 2832:     my $value = $memcache->get($id);
                   2833:     if (!(defined($value))) {
                   2834: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2835: 	return (undef,undef);
1.416     albertel 2836:     }
1.599     albertel 2837:     if ($value eq '__undef__') {
                   2838: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2839: 	$value=undef;
                   2840:     }
1.1172.2.81  raeburn  2841:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2842:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2843:     return ($value,1);
                   2844: }
                   2845: 
                   2846: sub do_cache_new {
                   2847:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2848:     my $remembered_id=$name.':'.$id;
1.849     albertel 2849:     $id=&make_key($name,$id);
1.599     albertel 2850:     my $setvalue=$value;
                   2851:     if (!defined($setvalue)) {
                   2852: 	$setvalue='__undef__';
                   2853:     }
1.623     albertel 2854:     if (!defined($time) ) {
                   2855: 	$time=600;
                   2856:     }
1.599     albertel 2857:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2858:     my $result = $memcache->set($id,$setvalue,$time);
                   2859:     if (! $result) {
1.872     albertel 2860: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2861: 	$memcache->disconnect_all();
1.872     albertel 2862:     }
1.600     albertel 2863:     # need to make a copy of $value
1.1172.2.81  raeburn  2864:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2865:     return $value;
                   2866: }
                   2867: 
                   2868: sub make_room {
1.1172.2.81  raeburn  2869:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2870: 
1.1172.2.81  raeburn  2871:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2872:                                     : $value;
1.599     albertel 2873:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2874:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2875:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2876:     my $to_kick;
                   2877:     my $max_time=0;
                   2878:     foreach my $other (keys(%accessed)) {
                   2879: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2880: 	    $to_kick=$other;
                   2881: 	    $max_time=&tv_interval($accessed{$other});
                   2882: 	}
                   2883:     }
                   2884:     delete($remembered{$to_kick});
                   2885:     delete($accessed{$to_kick});
                   2886:     $kicks++;
                   2887:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2888:     return;
                   2889: }
                   2890: 
1.599     albertel 2891: sub purge_remembered {
1.604     albertel 2892:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2893:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2894:     undef(%remembered);
                   2895:     undef(%accessed);
1.428     albertel 2896: }
1.70      www      2897: # ------------------------------------- Read an entry from a user's environment
                   2898: 
                   2899: sub userenvironment {
                   2900:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2901:     my $items;
                   2902:     foreach my $item (@what) {
                   2903:         $items.=&escape($item).'&';
                   2904:     }
                   2905:     $items=~s/\&$//;
1.70      www      2906:     my %returnhash=();
1.1009    raeburn  2907:     my $uhome = &homeserver($unam,$udom);
                   2908:     unless ($uhome eq 'no_host') {
                   2909:         my @answer=split(/\&/, 
                   2910:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2911:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2912:             return %returnhash;
                   2913:         }
1.1009    raeburn  2914:         my $i;
                   2915:         for ($i=0;$i<=$#what;$i++) {
                   2916: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2917:         }
1.70      www      2918:     }
                   2919:     return %returnhash;
1.1       albertel 2920: }
                   2921: 
1.617     albertel 2922: # ---------------------------------------------------------- Get a studentphoto
                   2923: sub studentphoto {
                   2924:     my ($udom,$unam,$ext) = @_;
                   2925:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2926:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2927:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2928:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2929:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2930:             } else {
                   2931:                 my ($result,$perm_reqd)=
1.707     albertel 2932: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2933:                 if ($result eq 'ok') {
                   2934:                     if (!($perm_reqd eq 'yes')) {
                   2935:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2936:                     }
                   2937:                 }
                   2938:             }
                   2939:         }
                   2940:     } else {
                   2941:         my ($result,$perm_reqd) = 
1.707     albertel 2942: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2943:         if ($result eq 'ok') {
                   2944:             if (!($perm_reqd eq 'yes')) {
                   2945:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2946:             }
                   2947:         }
                   2948:     }
                   2949:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2950: }
                   2951: 
                   2952: sub retrievestudentphoto {
                   2953:     my ($udom,$unam,$ext,$type) = @_;
                   2954:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2955:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2956:     if ($ret eq 'ok') {
                   2957:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2958:         if ($type eq 'thumbnail') {
                   2959:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2960:         }
                   2961:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2962:         return $tokenurl;
                   2963:     } else {
                   2964:         if ($type eq 'thumbnail') {
                   2965:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2966:         } else { 
                   2967:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2968:         }
1.617     albertel 2969:     }
                   2970: }
                   2971: 
1.263     www      2972: # -------------------------------------------------------------------- New chat
                   2973: 
                   2974: sub chatsend {
1.724     raeburn  2975:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2976:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2977:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2978:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2979:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2980: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2981: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2982: }
                   2983: 
                   2984: # ------------------------------------------ Find current version of a resource
                   2985: 
                   2986: sub getversion {
                   2987:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  2988:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2989:     return &currentversion(&filelocation('',$fname));
                   2990: }
                   2991: 
                   2992: sub currentversion {
                   2993:     my $fname=shift;
                   2994:     my $author=$fname;
                   2995:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2996:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2997:     my $home=&homeserver($uname,$udom);
1.292     www      2998:     if ($home eq 'no_host') { 
                   2999:         return -1; 
                   3000:     }
1.1112    www      3001:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3002:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3003: 	return -1;
                   3004:     }
1.1112    www      3005:     return $answer;
1.263     www      3006: }
                   3007: 
1.1111    www      3008: #
                   3009: # Return special version number of resource if set by override, empty otherwise
                   3010: #
                   3011: sub usedversion {
                   3012:     my $fname=shift;
                   3013:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3014:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3015:     if ($urlversion) { return $urlversion; }
                   3016:     return '';
                   3017: }
                   3018: 
1.1       albertel 3019: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3020: 
1.1       albertel 3021: sub subscribe {
                   3022:     my $fname=shift;
1.761     raeburn  3023:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3024:     $fname=~s/[\n\r]//g;
1.1       albertel 3025:     my $author=$fname;
                   3026:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3027:     my ($udom,$uname)=split(/\//,$author);
                   3028:     my $home=homeserver($uname,$udom);
1.335     albertel 3029:     if ($home eq 'no_host') {
                   3030:         return 'not_found';
1.1       albertel 3031:     }
                   3032:     my $answer=reply("sub:$fname",$home);
1.64      www      3033:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3034: 	$answer.=' by '.$home;
                   3035:     }
1.1       albertel 3036:     return $answer;
                   3037: }
                   3038:     
1.8       www      3039: # -------------------------------------------------------------- Replicate file
                   3040: 
                   3041: sub repcopy {
                   3042:     my $filename=shift;
1.23      www      3043:     $filename=~s/\/+/\//g;
1.1142    raeburn  3044:     my $londocroot = $perlvar{'lonDocRoot'};
                   3045:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3046:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3047:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3048: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3049: 	return &repcopy_userfile($filename);
                   3050:     }
1.532     albertel 3051:     $filename=~s/[\n\r]//g;
1.8       www      3052:     my $transname="$filename.in.transfer";
1.828     www      3053: # FIXME: this should flock
1.607     raeburn  3054:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3055:     my $remoteurl=subscribe($filename);
1.64      www      3056:     if ($remoteurl =~ /^con_lost by/) {
                   3057: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3058:            return 'unavailable';
1.8       www      3059:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3060: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3061: 	   return 'not_found';
1.64      www      3062:     } elsif ($remoteurl =~ /^rejected by/) {
                   3063: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3064:            return 'forbidden';
1.20      www      3065:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3066:            return 'ok';
1.8       www      3067:     } else {
1.290     www      3068:         my $author=$filename;
                   3069:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3070:         my ($udom,$uname)=split(/\//,$author);
                   3071:         my $home=homeserver($uname,$udom);
                   3072:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3073:            my @parts=split(/\//,$filename);
                   3074:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3075:            if ($path ne "$londocroot/res") {
1.8       www      3076:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3077: 	       return 'bad_request';
1.8       www      3078:            }
                   3079:            my $count;
                   3080:            for ($count=5;$count<$#parts;$count++) {
                   3081:                $path.="/$parts[$count]";
                   3082:                if ((-e $path)!=1) {
                   3083: 		   mkdir($path,0777);
                   3084:                }
                   3085:            }
                   3086:            my $ua=new LWP::UserAgent;
                   3087:            my $request=new HTTP::Request('GET',"$remoteurl");
                   3088:            my $response=$ua->request($request,$transname);
                   3089:            if ($response->is_error()) {
                   3090: 	       unlink($transname);
                   3091:                my $message=$response->status_line;
1.672     albertel 3092:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3093:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3094:                return 'unavailable';
1.8       www      3095:            } else {
1.16      www      3096: 	       if ($remoteurl!~/\.meta$/) {
                   3097:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   3098:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   3099:                   if ($mresponse->is_error()) {
                   3100: 		      unlink($filename.'.meta');
                   3101:                       &logthis(
1.672     albertel 3102:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3103:                   }
                   3104: 	       }
1.8       www      3105:                rename($transname,$filename);
1.607     raeburn  3106:                return 'ok';
1.8       www      3107:            }
1.290     www      3108:        }
1.8       www      3109:     }
1.330     www      3110: }
                   3111: 
1.1172.2.118.  .5(raebu 3112:20): # ------------------------------------------------- Unsubscribe from a resource
                   3113:20): 
                   3114:20): sub unsubscribe {
                   3115:20):     my ($fname) = @_;
                   3116:20):     my $answer;
                   3117:20):     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3118:20):     $fname=~s/[\n\r]//g;
                   3119:20):     my $author=$fname;
                   3120:20):     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3121:20):     my ($udom,$uname)=split(/\//,$author);
                   3122:20):     my $home=homeserver($uname,$udom);
                   3123:20):     if ($home eq 'no_host') {
                   3124:20):         $answer = 'no_host';
                   3125:20):     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3126:20):         $answer = 'home';
                   3127:20):     } else {
          .7(raebu 3128:20):         $answer = reply("unsub:$fname",$home);
          .5(raebu 3129:20):     }
                   3130:20):     return $answer;
                   3131:20): }
                   3132:20): 
1.330     www      3133: # ------------------------------------------------ Get server side include body
                   3134: sub ssi_body {
1.381     albertel 3135:     my ($filelink,%form)=@_;
1.606     matthew  3136:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3137:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3138:     }
1.953     www      3139:     my $output='';
                   3140:     my $response;
1.980     raeburn  3141:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3142:        ($output,$response)=&externalssi($filelink);
1.953     www      3143:     } else {
1.1004    droeschl 3144:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3145:        $filelink .= 'inhibitmenu=yes';
1.953     www      3146:        ($output,$response)=&ssi($filelink,%form);
                   3147:     }
1.778     albertel 3148:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3149:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3150:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3151:     if (wantarray) {
                   3152:         return ($output, $response);
                   3153:     } else {
                   3154:         return $output;
                   3155:     }
1.8       www      3156: }
                   3157: 
1.15      www      3158: # --------------------------------------------------------- Server Side Include
                   3159: 
1.782     albertel 3160: sub absolute_url {
                   3161:     my ($host_name) = @_;
                   3162:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3163:     if ($host_name eq '') {
                   3164: 	$host_name = $ENV{'SERVER_NAME'};
                   3165:     }
                   3166:     return $protocol.$host_name;
                   3167: }
                   3168: 
1.942     foxr     3169: #
                   3170: #   Server side include.
                   3171: # Parameters:
                   3172: #  fn     Possibly encrypted resource name/id.
                   3173: #  form   Hash that describes how the rendering should be done
                   3174: #         and other things.
1.944     foxr     3175: # Returns:
1.950     raeburn  3176: #   Scalar context: The content of the response.
                   3177: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3178: #     
1.15      www      3179: sub ssi {
                   3180: 
1.944     foxr     3181:     my ($fn,%form)=@_;
1.1172.2.100  raeburn  3182:     my ($request,$response);
1.711     albertel 3183: 
                   3184:     $form{'no_update_last_known'}=1;
1.895     albertel 3185:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3186:     if (%form) {
1.782     albertel 3187:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  3188:       $request->content(join('&',map {
                   3189:             my $name = escape($_);
                   3190:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3191:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3192:             : &escape($form{$_}) );
                   3193:         } keys(%form)));
1.23      www      3194:     } else {
1.782     albertel 3195:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3196:     }
                   3197: 
1.15      www      3198:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3199: 
1.1172.2.101  raeburn  3200:     if (($env{'request.course.id'}) &&
                   3201:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3202:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3203:         ($form{'grade_symb'} ne '') &&
                   3204:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3205:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3206:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3207:             my $ua=new LWP::UserAgent;
                   3208:             $ua->local_address('127.0.0.1');
                   3209:             $response = $ua->request($request);
                   3210:         } else {
                   3211:             {
                   3212:                 require LWP::Protocol::http;
                   3213:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3214:                 my $ua=new LWP::UserAgent;
                   3215:                 $response = $ua->request($request);
                   3216:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3217:             }
                   3218:         }
                   3219:     } else {
                   3220:         my $ua=new LWP::UserAgent;
                   3221:         $response = $ua->request($request);
                   3222:     }
1.944     foxr     3223:     if (wantarray) {
1.1172.2.3  raeburn  3224: 	return ($response->content, $response);
1.944     foxr     3225:     } else {
1.1172.2.3  raeburn  3226: 	return $response->content;
1.942     foxr     3227:     }
1.324     www      3228: }
                   3229: 
                   3230: sub externalssi {
                   3231:     my ($url)=@_;
                   3232:     my $ua=new LWP::UserAgent;
                   3233:     my $request=new HTTP::Request('GET',$url);
                   3234:     my $response=$ua->request($request);
1.954     raeburn  3235:     if (wantarray) {
                   3236:         return ($response->content, $response);
                   3237:     } else {
                   3238:         return $response->content;
                   3239:     }
1.15      www      3240: }
1.254     www      3241: 
1.1172.2.98  raeburn  3242: # If the local copy of a replicated resource is outdated, trigger a
                   3243: # connection from the homeserver to flush the delayed queue. If no update
                   3244: # happens, remove local copies of outdated resource (and corresponding
                   3245: # metadata file).
                   3246: 
                   3247: sub remove_stale_resfile {
                   3248:     my ($url) = @_;
                   3249:     my $removed;
                   3250:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3251:         my $audom = $1;
                   3252:         my $auname = $2;
                   3253:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3254:             my $homeserver = &homeserver($auname,$audom);
                   3255:             unless (($homeserver eq 'no_host') ||
                   3256:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3257:                 my $fname = &filelocation('',$url);
                   3258:                 if (-e $fname) {
                   3259:                     my $hostname = &hostname($homeserver);
                   3260:                     if ($hostname) {
1.1172.2.118.  .3(raebu 3261:20):                         my $protocol = $protocol{$homeserver};
                   3262:20):                         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98  raeburn  3263:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.118.  .3(raebu 3264:20):                         my $ua=new LWP::UserAgent;
                   3265:20):                         $ua->timeout(5);
1.1172.2.98  raeburn  3266:                         my $request=new HTTP::Request('HEAD',$uri);
                   3267:                         my $response=$ua->request($request);
                   3268:                         if ($response->is_success()) {
                   3269:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3270:                             my $locmodtime = (stat($fname))[9];
                   3271:                             if ($locmodtime < $remmodtime) {
                   3272:                                 my $stale;
                   3273:                                 my $answer = &reply('pong',$homeserver);
                   3274:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3275:                                     sleep(0.2);
                   3276:                                     $locmodtime = (stat($fname))[9];
                   3277:                                     if ($locmodtime < $remmodtime) {
                   3278:                                         my $posstransfer = $fname.'.in.transfer';
                   3279:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3280:                                             $removed = 1;
                   3281:                                         } else {
                   3282:                                             $stale = 1;
                   3283:                                         }
                   3284:                                     } else {
                   3285:                                         $removed = 1;
                   3286:                                     }
                   3287:                                 } else {
                   3288:                                     $stale = 1;
                   3289:                                 }
                   3290:                                 if ($stale) {
1.1172.2.118.  .5(raebu 3291:20):                                     if (unlink($fname)) {
                   3292:20):                                         if ($uri!~/\.meta$/) {
                   3293:20):                                             if (-e $fname.'.meta') {
                   3294:20):                                                 unlink($fname.'.meta');
                   3295:20):                                             }
                   3296:20):                                         }
                   3297:20):                                         my $unsubresult = &unsubscribe($fname);
                   3298:20):                                         unless ($unsubresult eq 'ok') {
                   3299:20):                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3300:20):                                         }
                   3301:20):                                         $removed = 1;
1.1172.2.98  raeburn  3302:                                     }
                   3303:                                 }
                   3304:                             }
                   3305:                         }
                   3306:                     }
                   3307:                 }
                   3308:             }
                   3309:         }
                   3310:     }
                   3311:     return $removed;
                   3312: }
                   3313: 
1.492     albertel 3314: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3315: 
                   3316: sub allowuploaded {
                   3317:     my ($srcurl,$url)=@_;
                   3318:     $url=&clutter(&declutter($url));
                   3319:     my $dir=$url;
                   3320:     $dir=~s/\/[^\/]+$//;
                   3321:     my %httpref=();
                   3322:     my $httpurl=&hreflocation('',$url);
                   3323:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3324:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3325: }
1.477     raeburn  3326: 
1.1172.2.13  raeburn  3327: #
                   3328: # Determine if the current user should be able to edit a particular resource,
                   3329: # when viewing in course context.
                   3330: # (a) When viewing resource used to determine if "Edit" item is included in
                   3331: #     Functions.
                   3332: # (b) When displaying folder contents in course editor, used to determine if
                   3333: #     "Edit" link will be displayed alongside resource.
                   3334: #
                   3335: #  input: six args -- filename (decluttered), course number, course domain,
                   3336: #                   url, symb (if registered) and group (if this is a group
                   3337: #                   item -- e.g., bulletin board, group page etc.).
                   3338: #  output: array of five scalars --
                   3339: #          $cfile -- url for file editing if editable on current server
                   3340: #          $home -- homeserver of resource (i.e., for author if published,
                   3341: #                                           or course if uploaded.).
                   3342: #          $switchserver --  1 if server switch will be needed.
                   3343: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3344: #          $forceview -- 1 if icon/link should be to go to view mode
                   3345: #
                   3346: 
                   3347: sub can_edit_resource {
                   3348:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3349:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3350: #
                   3351: # For aboutme pages user can only edit his/her own.
                   3352: #
                   3353:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3354:         my ($sdom,$sname) = ($1,$2);
                   3355:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3356:             $home = $env{'user.home'};
                   3357:             $cfile = $resurl;
                   3358:             if ($env{'form.forceedit'}) {
                   3359:                 $forceview = 1;
                   3360:             } else {
                   3361:                 $forceedit = 1;
                   3362:             }
                   3363:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3364:         } else {
                   3365:             return;
                   3366:         }
                   3367:     }
                   3368: 
                   3369:     if ($env{'request.course.id'}) {
                   3370:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3371:         if ($group ne '') {
                   3372: # if this is a group homepage or group bulletin board, check group privs
                   3373:             my $allowed = 0;
                   3374:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3375:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3376:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3377:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3378:                     $allowed = 1;
                   3379:                 }
                   3380:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3381:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3382:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3383:                     $allowed = 1;
                   3384:                 }
                   3385:             }
                   3386:             if ($allowed) {
                   3387:                 $home=&homeserver($cnum,$cdom);
                   3388:                 if ($env{'form.forceedit'}) {
                   3389:                     $forceview = 1;
                   3390:                 } else {
                   3391:                     $forceedit = 1;
                   3392:                 }
                   3393:                 $cfile = $resurl;
                   3394:             } else {
                   3395:                 return;
                   3396:             }
                   3397:         } else {
1.1172.2.15  raeburn  3398:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3399:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3400:                     return;
                   3401:                 }
                   3402:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3403: #
                   3404: # No edit allowed where CC has switched to student role.
                   3405: #
                   3406:                 return;
                   3407:             }
                   3408:         }
                   3409:     }
                   3410: 
                   3411:     if ($file ne '') {
                   3412:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3413:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3414:                 $uploaded = 1;
                   3415:                 $incourse = 1;
                   3416:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3417:                     $cfile = &hreflocation('',$file);
                   3418:                     if ($env{'form.forceedit'}) {
                   3419:                         $forceview = 1;
                   3420:                     } else {
                   3421:                         $forceedit = 1;
                   3422:                     }
                   3423:                 }
                   3424:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3425:                 $incourse = 1;
                   3426:                 if ($env{'form.forceedit'}) {
                   3427:                     $forceview = 1;
                   3428:                 } else {
                   3429:                     $forceedit = 1;
                   3430:                 }
                   3431:                 $cfile = $resurl;
                   3432:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3433:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3434:                     $incourse = 1;
                   3435:                     if ($env{'form.forceedit'}) {
                   3436:                         $forceview = 1;
                   3437:                     } else {
                   3438:                         $forceedit = 1;
                   3439:                     }
                   3440:                     $cfile = $resurl;
                   3441:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3442:                     $incourse = 1;
                   3443:                     $cfile = $resurl.'/smpedit';
                   3444:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3445:                     $incourse = 1;
                   3446:                     if ($env{'form.forceedit'}) {
                   3447:                         $forceview = 1;
                   3448:                     } else {
                   3449:                         $forceedit = 1;
                   3450:                     }
                   3451:                     $cfile = $resurl;
1.1172.2.118.  .5(raebu 3452:20):                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3453:20):                     my ($map,$id,$res) = &decode_symb($symb);
                   3454:20):                     if ($map =~ /\.page$/) {
                   3455:20):                         $incourse = 1;
                   3456:20):                         if ($env{'form.forceedit'}) {
                   3457:20):                             $forceview = 1;
                   3458:20):                             $cfile = $map;
                   3459:20):                         } else {
                   3460:20):                             $forceedit = 1;
                   3461:20):                             $cfile =  '/adm/wrapper'.$resurl;
                   3462:20):                         }
                   3463:20):                     }
          .1(raebu 3464:20):                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3465:20):                     $incourse = 1;
                   3466:20):                     if ($env{'form.forceedit'}) {
                   3467:20):                         $forceview = 1;
                   3468:20):                     } else {
                   3469:20):                         $forceedit = 1;
                   3470:20):                     }
                   3471:20):                     $cfile = $resurl;
1.1172.2.15  raeburn  3472:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3473:                     $incourse = 1;
                   3474:                     if ($env{'form.forceedit'}) {
                   3475:                         $forceview = 1;
                   3476:                     } else {
                   3477:                         $forceedit = 1;
                   3478:                     }
                   3479:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3480:                 }
                   3481:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3482:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3483:                 if (&is_on_map($template)) {
                   3484:                     $incourse = 1;
                   3485:                     $forceview = 1;
                   3486:                     $cfile = $template;
                   3487:                 }
                   3488:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118  raeburn  3489:                 $incourse = 1;
                   3490:                 if ($env{'form.forceedit'}) {
                   3491:                     $forceview = 1;
                   3492:                 } else {
                   3493:                     $forceedit = 1;
                   3494:                 }
                   3495:                 $cfile = $resurl;
1.1172.2.118.  .1(raebu 3496:20):             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3497:20):                 $incourse = 1;
                   3498:20):                 if ($env{'form.forceedit'}) {
                   3499:20):                     $forceview = 1;
                   3500:20):                 } else {
                   3501:20):                     $forceedit = 1;
                   3502:20):                 }
                   3503:20):                 $cfile = $resurl;
1.1172.2.13  raeburn  3504:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3505:                 $incourse = 1;
                   3506:                 $forceview = 1;
                   3507:                 if ($symb) {
                   3508:                     my ($map,$id,$res)=&decode_symb($symb);
                   3509:                     $env{'request.symb'} = $symb;
                   3510:                     $cfile = &clutter($res);
                   3511:                 } else {
                   3512:                     $cfile = $env{'form.suppurl'};
1.1172.2.118.  .1(raebu 3513:20):                     my $escfile = &unescape($cfile);
                   3514:20):                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3515:20):                         $cfile = '/adm/wrapper'.$escfile;
                   3516:20):                     } else {
                   3517:20):                         $escfile =~ s{^http://}{};
                   3518:20):                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3519:20):                     }
1.1172.2.13  raeburn  3520:                 }
1.1172.2.31  raeburn  3521:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3522:                 if ($env{'form.forceedit'}) {
                   3523:                     $forceview = 1;
                   3524:                 } else {
                   3525:                     $forceedit = 1;
                   3526:                 }
                   3527:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3528:             }
                   3529:         }
                   3530:         if ($uploaded || $incourse) {
                   3531:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3532:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3533:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3534:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3535:             # Check that the user has permission to edit this resource
                   3536:             my $setpriv = 1;
                   3537:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3538:             if (defined($cfudom)) {
                   3539:                 $home=&homeserver($cfuname,$cfudom);
                   3540:                 $cfile=$file;
                   3541:             }
                   3542:         }
                   3543:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3544:             (($home ne '') && ($home ne 'no_host'))) {
                   3545:             my @ids=&current_machine_ids();
                   3546:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3547:                 $switchserver=1;
                   3548:             }
                   3549:         }
                   3550:     }
                   3551:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3552: }
                   3553: 
                   3554: sub is_course_upload {
                   3555:     my ($file,$cnum,$cdom) = @_;
                   3556:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3557:     $uploadpath =~ s{^\/}{};
                   3558:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3559:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3560:         return 1;
                   3561:     }
                   3562:     return;
                   3563: }
                   3564: 
                   3565: sub in_course {
                   3566:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3567:     if ($hideprivileged) {
                   3568:         my $skipuser;
1.1172.2.23  raeburn  3569:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3570:         my @possdoms = ($cdom);
                   3571:         if ($coursehash{'checkforpriv'}) {
                   3572:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3573:         }
                   3574:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3575:             $skipuser = 1;
                   3576:             if ($coursehash{'nothideprivileged'}) {
                   3577:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3578:                     my $user;
                   3579:                     if ($item =~ /:/) {
                   3580:                         $user = $item;
                   3581:                     } else {
                   3582:                         $user = join(':',split(/[\@]/,$item));
                   3583:                     }
                   3584:                     if ($user eq $uname.':'.$udom) {
                   3585:                         undef($skipuser);
                   3586:                         last;
                   3587:                     }
                   3588:                 }
                   3589:             }
                   3590:             if ($skipuser) {
                   3591:                 return 0;
                   3592:             }
                   3593:         }
                   3594:     }
                   3595:     $type ||= 'any';
                   3596:     if (!defined($cdom) || !defined($cnum)) {
                   3597:         my $cid  = $env{'request.course.id'};
                   3598:         $cdom = $env{'course.'.$cid.'.domain'};
                   3599:         $cnum = $env{'course.'.$cid.'.num'};
                   3600:     }
                   3601:     my $typesref;
                   3602:     if (($type eq 'any') || ($type eq 'all')) {
                   3603:         $typesref = ['active','previous','future'];
                   3604:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3605:         $typesref = [$type];
                   3606:     }
                   3607:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3608:                               $typesref,undef,[$cdom]);
                   3609:     my ($tmp) = keys(%roles);
                   3610:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3611:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3612:     if (@course_roles > 0) {
                   3613:         return 1;
                   3614:     }
                   3615:     return 0;
                   3616: }
                   3617: 
1.478     albertel 3618: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3619: # input: action, courseID, current domain, intended
1.637     raeburn  3620: #        path to file, source of file, instruction to parse file for objects,
                   3621: #        ref to hash for embedded objects,
                   3622: #        ref to hash for codebase of java objects.
1.1095    raeburn  3623: #        reference to scalar to accommodate mime type determined
                   3624: #          from File::MMagic if $parser = parse.
1.637     raeburn  3625: #
1.485     raeburn  3626: # output: url to file (if action was uploaddoc), 
                   3627: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3628: #
1.478     albertel 3629: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3630: # course.
1.477     raeburn  3631: #
1.478     albertel 3632: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3633: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3634: #          course's home server.
1.477     raeburn  3635: #
1.478     albertel 3636: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3637: #          be copied from $source (current location) to 
                   3638: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3639: #         and will then be copied to
                   3640: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3641: #         course's home server.
1.485     raeburn  3642: #
1.481     raeburn  3643: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3644: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3645: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3646: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3647: #         in course's home server.
1.637     raeburn  3648: #
1.477     raeburn  3649: 
                   3650: sub process_coursefile {
1.1095    raeburn  3651:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3652:         $mimetype)=@_;
1.477     raeburn  3653:     my $fetchresult;
1.638     albertel 3654:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3655:     if ($action eq 'propagate') {
1.638     albertel 3656:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3657: 			     $home);
1.481     raeburn  3658:     } else {
1.477     raeburn  3659:         my $fpath = '';
                   3660:         my $fname = $file;
1.478     albertel 3661:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3662:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3663:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3664:         if ($action eq 'copy') {
                   3665:             if ($source eq '') {
                   3666:                 $fetchresult = 'no source file';
                   3667:                 return $fetchresult;
                   3668:             } else {
                   3669:                 my $destination = $filepath.'/'.$fname;
                   3670:                 rename($source,$destination);
                   3671:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3672:                                  $home);
1.481     raeburn  3673:             }
                   3674:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3675:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3676:             print $fh $env{'form.'.$source};
1.481     raeburn  3677:             close($fh);
1.637     raeburn  3678:             if ($parser eq 'parse') {
1.1024    raeburn  3679:                 my $mm = new File::MMagic;
1.1095    raeburn  3680:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3681:                 if ($type eq 'text/html') {
1.1024    raeburn  3682:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3683:                     unless ($parse_result eq 'ok') {
                   3684:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3685:                     }
1.637     raeburn  3686:                 }
1.1095    raeburn  3687:                 if (ref($mimetype)) {
                   3688:                     $$mimetype = $type;
                   3689:                 } 
1.637     raeburn  3690:             }
1.477     raeburn  3691:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3692:                                  $home);
1.481     raeburn  3693:             if ($fetchresult eq 'ok') {
                   3694:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3695:             } else {
                   3696:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3697:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3698:                 return '/adm/notfound.html';
                   3699:             }
1.477     raeburn  3700:         }
                   3701:     }
1.485     raeburn  3702:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3703:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3704:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3705:     }
                   3706:     return $fetchresult;
                   3707: }
                   3708: 
1.637     raeburn  3709: sub build_filepath {
                   3710:     my ($fpath) = @_;
                   3711:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3712:     unless ($fpath eq '') {
                   3713:         my @parts=split('/',$fpath);
                   3714:         foreach my $part (@parts) {
                   3715:             $filepath.= '/'.$part;
                   3716:             if ((-e $filepath)!=1) {
                   3717:                 mkdir($filepath,0777);
                   3718:             }
                   3719:         }
                   3720:     }
                   3721:     return $filepath;
                   3722: }
                   3723: 
                   3724: sub store_edited_file {
1.638     albertel 3725:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3726:     my $file = $primary_url;
                   3727:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3728:     my $fpath = '';
                   3729:     my $fname = $file;
                   3730:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3731:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3732:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3733:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3734:     print $fh $content;
                   3735:     close($fh);
1.638     albertel 3736:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3737:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3738: 			  $home);
1.637     raeburn  3739:     if ($$fetchresult eq 'ok') {
                   3740:         return '/uploaded/'.$fpath.'/'.$fname;
                   3741:     } else {
1.638     albertel 3742:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3743: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3744:         return '/adm/notfound.html';
                   3745:     }
                   3746: }
                   3747: 
1.531     albertel 3748: sub clean_filename {
1.831     albertel 3749:     my ($fname,$args)=@_;
1.315     www      3750: # Replace Windows backslashes by forward slashes
1.257     www      3751:     $fname=~s/\\/\//g;
1.831     albertel 3752:     if (!$args->{'keep_path'}) {
                   3753:         # Get rid of everything but the actual filename
                   3754: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3755:     }
1.315     www      3756: # Replace spaces by underscores
                   3757:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  3758: # Transliterate non-ascii text to ascii
                   3759:     my $lang = &Apache::lonlocal::current_language();
                   3760:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3761: # Replace all other weird characters by nothing
1.831     albertel 3762:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3763: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3764: # numbers
                   3765:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3766:     return $fname;
                   3767: }
1.1172.2.110  raeburn  3768: 
1.1051    raeburn  3769: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3770: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3771: # image with the same aspect ratio as the original, but with dimensions which do 
                   3772: # not exceed $resizewidth and $resizeheight.
                   3773:  
1.984     neumanie 3774: sub resizeImage {
1.1051    raeburn  3775:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3776:     my $ima = Image::Magick->new;
                   3777:     my $resized;
                   3778:     if (-e $img_path) {
                   3779:         $ima->Read($img_path);
                   3780:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3781:             my $width = $ima->Get('width');
                   3782:             my $height = $ima->Get('height');
                   3783:             if ($width > $resizewidth) {
                   3784: 	        my $factor = $width/$resizewidth;
                   3785:                 my $newheight = $height/$factor;
                   3786:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3787:                 $resized = 1;
                   3788:             }
                   3789:         }
                   3790:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3791:             my $width = $ima->Get('width');
                   3792:             my $height = $ima->Get('height');
                   3793:             if ($height > $resizeheight) {
                   3794:                 my $factor = $height/$resizeheight;
                   3795:                 my $newwidth = $width/$factor;
                   3796:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3797:                 $resized = 1;
                   3798:             }
                   3799:         }
                   3800:         if ($resized) {
                   3801:             $ima->Write($img_path);
                   3802:         }
                   3803:     }
                   3804:     return;
1.977     amueller 3805: }
                   3806: 
1.608     albertel 3807: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3808: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3809: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3810: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.109  raeburn  3811: #                                    canceloverwrite, scantron or ''. 
1.1090    raeburn  3812: #                   if 'coursedoc': upload to the current course
                   3813: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3814: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3815: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3816: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  3817: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3818: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3819: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   3820: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3821: #        $allfiles - reference to hash for embedded objects
                   3822: #        $codebase - reference to hash for codebase of java objects
                   3823: #        $desuname - username for permanent storage of uploaded file
                   3824: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3825: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3826: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3827: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3828: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3829: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3830: #                    from File::MMagic.
1.858     raeburn  3831: # 
1.686     albertel 3832: # output: url of file in userspace, or error: <message> 
                   3833: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3834: 
1.531     albertel 3835: sub userfileupload {
1.1090    raeburn  3836:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3837:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3838:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3839:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3840:     $fname=&clean_filename($fname);
1.1090    raeburn  3841:     # See if there is anything left
1.257     www      3842:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  3843:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   3844:     if ($fname =~ /^\./) {
                   3845:         my ($s,$usec) = &gettimeofday();
                   3846:         while (length($usec) < 6) {
                   3847:             $usec = '0'.$usec;
                   3848:         }
                   3849:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   3850:     }
1.1090    raeburn  3851:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3852:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3853:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3854:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3855:         my $now = time;
1.1090    raeburn  3856:         my $filepath;
1.1095    raeburn  3857:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3858:              $filepath = 'tmp/helprequests/'.$now;
                   3859:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3860:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3861:                          '_'.$env{'user.domain'}.'/pending';
                   3862:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3863:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3864:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3865:                 $docudom = $destudom;
                   3866:             } else {
                   3867:                 $docudom = $env{'user.domain'};
                   3868:             }
1.1172.2.96  raeburn  3869:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3870:                 $docuname = $destuname;
                   3871:             } else {
                   3872:                 $docuname = $env{'user.name'};
                   3873:             }
                   3874:             if (exists($env{'form.group'})) {
                   3875:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3876:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3877:             }
                   3878:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3879:             if ($context eq 'canceloverwrite') {
                   3880:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3881:                 if (-e  $tempfile) {
                   3882:                     my @info = stat($tempfile);
                   3883:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3884:                         unlink($tempfile);
                   3885:                     }
                   3886:                 }
                   3887:                 return;
1.523     raeburn  3888:             }
                   3889:         }
1.1090    raeburn  3890:         # Create the directory if not present
1.741     raeburn  3891:         my @parts=split(/\//,$filepath);
                   3892:         my $fullpath = $perlvar{'lonDaemons'};
                   3893:         for (my $i=0;$i<@parts;$i++) {
                   3894:             $fullpath .= '/'.$parts[$i];
                   3895:             if ((-e $fullpath)!=1) {
                   3896:                 mkdir($fullpath,0777);
                   3897:             }
                   3898:         }
1.1172.2.96  raeburn  3899:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3900:         print $fh $env{'form.'.$formname};
                   3901:         close($fh);
1.1090    raeburn  3902:         if ($context eq 'existingfile') {
                   3903:             my @info = stat($fullpath.'/'.$fname);
                   3904:             return ($fullpath.'/'.$fname,$info[9]);
                   3905:         } else {
                   3906:             return $fullpath.'/'.$fname;
                   3907:         }
1.523     raeburn  3908:     }
1.995     raeburn  3909:     if ($subdir eq 'scantron') {
                   3910:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3911:     } else {
1.995     raeburn  3912:         $fname="$subdir/$fname";
                   3913:     }
1.1090    raeburn  3914:     if ($context eq 'coursedoc') {
1.638     albertel 3915: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3916: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3917:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3918:             return &finishuserfileupload($docuname,$docudom,
                   3919: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3920: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3921:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3922:         } else {
1.1172.2.21  raeburn  3923:             if ($env{'form.folder'}) {
                   3924:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3925:             }
1.638     albertel 3926:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3927: 				       $fname,$formname,$parser,
1.1095    raeburn  3928: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3929:         }
1.719     banghart 3930:     } elsif (defined($destuname)) {
                   3931:         my $docuname=$destuname;
                   3932:         my $docudom=$destudom;
1.860     raeburn  3933: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3934: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3935:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3936:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3937:     } else {
1.638     albertel 3938:         my $docuname=$env{'user.name'};
                   3939:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3940:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3941:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3942:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3943:         }
1.860     raeburn  3944: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3945: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3946:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3947:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3948:     }
1.271     www      3949: }
                   3950: 
                   3951: sub finishuserfileupload {
1.860     raeburn  3952:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3953:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3954:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3955:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3956:   
1.860     raeburn  3957:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3958:     $file=$fname;
                   3959:     if ($fname=~m|/|) {
                   3960:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3961: 	$path.=$fnamepath.'/';
                   3962:     }
1.259     www      3963:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3964:     my $count;
                   3965:     for ($count=4;$count<=$#parts;$count++) {
                   3966:         $filepath.="/$parts[$count]";
                   3967:         if ((-e $filepath)!=1) {
                   3968: 	    mkdir($filepath,0777);
                   3969:         }
                   3970:     }
1.984     neumanie 3971: 
1.258     www      3972: # Save the file
                   3973:     {
1.1172.2.96  raeburn  3974: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3975: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3976: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3977: 	    return '/adm/notfound.html';
                   3978: 	}
1.1090    raeburn  3979:         if ($context eq 'overwrite') {
1.1117    foxr     3980:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3981:             my $target = $filepath.'/'.$file;
                   3982:             if (-e $source) {
                   3983:                 my @info = stat($source);
                   3984:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3985:                     unless (&File::Copy::move($source,$target)) {
                   3986:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3987:                         return "Moving from $source failed";
                   3988:                     }
                   3989:                 } else {
                   3990:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3991:                 }
                   3992:             } else {
                   3993:                 return "Temporary file: $source missing";
                   3994:             }
                   3995:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3996: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3997: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3998: 	    return '/adm/notfound.html';
                   3999: 	}
1.570     albertel 4000: 	close(FH);
1.1051    raeburn  4001:         if ($resizewidth && $resizeheight) {
                   4002:             my $mm = new File::MMagic;
                   4003:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4004:             if ($mime_type =~ m{^image/}) {
                   4005: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4006:             }  
1.977     amueller 4007: 	}
1.258     www      4008:     }
1.1152    raeburn  4009:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4010:         if (ref($mimetype)) {
                   4011:             if ($$mimetype eq '') {
                   4012:                 my $mm = new File::MMagic;
                   4013:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4014:                 $$mimetype = $type;
                   4015:             }
                   4016:         }
                   4017:     }
1.1172.2.109  raeburn  4018:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4019:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4020:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4021:                                                        $allfiles,$codebase);
                   4022:             unless ($parse_result eq 'ok') {
                   4023:                 &logthis('Failed to parse '.$filepath.$file.
                   4024: 	   	         ' for embedded media: '.$parse_result); 
                   4025:             }
1.637     raeburn  4026:         }
1.1172.2.109  raeburn  4027:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4028:         my $format = $env{'form.scantron_format'};
                   4029:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4030:     }
1.860     raeburn  4031:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4032:         my $input = $filepath.'/'.$file;
                   4033:         my $output = $filepath.'/'.'tn-'.$file;
                   4034:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  4035:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4036:         system({$args[0]} @args);
1.860     raeburn  4037:         if (-e $filepath.'/'.'tn-'.$file) {
                   4038:             $fetchthumb  = 1; 
                   4039:         }
                   4040:     }
1.858     raeburn  4041:  
1.259     www      4042: # Notify homeserver to grep it
                   4043: #
1.984     neumanie 4044:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4045:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4046:     if ($fetchresult eq 'ok') {
1.860     raeburn  4047:         if ($fetchthumb) {
                   4048:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4049:             if ($thumbresult ne 'ok') {
                   4050:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4051:                          $docuhome.': '.$thumbresult);
                   4052:             }
                   4053:         }
1.259     www      4054: #
1.258     www      4055: # Return the URL to it
1.494     albertel 4056:         return '/uploaded/'.$path.$file;
1.263     www      4057:     } else {
1.494     albertel 4058:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4059: 		 ': '.$fetchresult);
1.263     www      4060:         return '/adm/notfound.html';
1.858     raeburn  4061:     }
1.493     albertel 4062: }
                   4063: 
1.637     raeburn  4064: sub extract_embedded_items {
1.961     raeburn  4065:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4066:     my @state = ();
1.1164    raeburn  4067:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4068:     my %javafiles = (
                   4069:                       codebase => '',
                   4070:                       code => '',
                   4071:                       archive => ''
                   4072:                     );
                   4073:     my %mediafiles = (
                   4074:                       src => '',
                   4075:                       movie => '',
                   4076:                      );
1.648     raeburn  4077:     my $p;
                   4078:     if ($content) {
                   4079:         $p = HTML::LCParser->new($content);
                   4080:     } else {
1.961     raeburn  4081:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4082:     }
1.641     albertel 4083:     while (my $t=$p->get_token()) {
1.640     albertel 4084: 	if ($t->[0] eq 'S') {
                   4085: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4086: 	    push(@state, $tagname);
1.648     raeburn  4087:             if (lc($tagname) eq 'allow') {
                   4088:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4089:             }
1.640     albertel 4090: 	    if (lc($tagname) eq 'img') {
                   4091: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4092: 	    }
1.886     albertel 4093: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  4094:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   4095: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   4096:                 }
1.886     albertel 4097: 	    }
1.645     raeburn  4098:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4099:                 my $src;
1.645     raeburn  4100:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4101:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4102:                 } else {
1.1164    raeburn  4103:                     if ($attr->{'src'} ne '') {
                   4104:                         $src = $attr->{'src'};
                   4105:                         &add_filetype($allfiles,$src,'src');
                   4106:                     }
                   4107:                 }
                   4108:                 my $text = $p->get_trimmed_text();
                   4109:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4110:                     my @swfargs = split(/,/,$1);
                   4111:                     foreach my $item (@swfargs) {
                   4112:                         $item =~ s/["']//g;
                   4113:                         $item =~ s/^\s+//;
                   4114:                         $item =~ s/\s+$//;
                   4115:                     }
                   4116:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4117:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4118:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4119:                         } else {
                   4120:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4121:                         }
                   4122:                     }
1.645     raeburn  4123:                 }
                   4124:             }
                   4125:             if (lc($tagname) eq 'link') {
                   4126:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4127:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4128:                 }
                   4129:             }
1.640     albertel 4130: 	    if (lc($tagname) eq 'object' ||
                   4131: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4132: 		foreach my $item (keys(%javafiles)) {
                   4133: 		    $javafiles{$item} = '';
                   4134: 		}
1.1164    raeburn  4135:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4136:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4137:                 }
1.640     albertel 4138: 	    }
                   4139: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4140: 		my $name = lc($attr->{'name'});
                   4141: 		foreach my $item (keys(%javafiles)) {
                   4142: 		    if ($name eq $item) {
                   4143: 			$javafiles{$item} = $attr->{'value'};
                   4144: 			last;
                   4145: 		    }
                   4146: 		}
1.1164    raeburn  4147:                 my $pathfrom;
1.640     albertel 4148: 		foreach my $item (keys(%mediafiles)) {
                   4149: 		    if ($name eq $item) {
1.1164    raeburn  4150:                         $pathfrom = $attr->{'value'};
                   4151:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4152: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4153: 			last;
                   4154: 		    }
                   4155: 		}
1.1164    raeburn  4156:                 if ($name eq 'flashvars') {
                   4157:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4158:                 }
                   4159:                 if ($pathfrom ne '') {
                   4160:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4161:                                          $pathfrom);
                   4162:                 }
1.640     albertel 4163: 	    }
                   4164: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4165: 		foreach my $item (keys(%javafiles)) {
                   4166: 		    if ($attr->{$item}) {
                   4167: 			$javafiles{$item} = $attr->{$item};
                   4168: 			last;
                   4169: 		    }
                   4170: 		}
                   4171: 		foreach my $item (keys(%mediafiles)) {
                   4172: 		    if ($attr->{$item}) {
                   4173: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4174: 			last;
                   4175: 		    }
                   4176: 		}
1.1164    raeburn  4177:                 if (lc($tagname) eq 'embed') {
                   4178:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4179:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4180:                                              $attr->{'src'});
                   4181:                     }
                   4182:                 }
1.640     albertel 4183: 	    }
1.1172.2.35  raeburn  4184:             if (lc($tagname) eq 'iframe') {
                   4185:                 my $src = $attr->{'src'} ;
                   4186:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4187:                     &add_filetype($allfiles,$src,'src');
                   4188:                 } elsif ($src =~ m{^/}) {
                   4189:                     if ($env{'request.course.id'}) {
                   4190:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4191:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4192:                         my $url = &hreflocation('',$fullpath);
                   4193:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4194:                             my $relpath = $1;
                   4195:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4196:                                 &add_filetype($allfiles,$1,'src');
                   4197:                             }
                   4198:                         }
                   4199:                     }
                   4200:                 }
                   4201:             }
1.1164    raeburn  4202:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4203:                 pop(@state);
1.1164    raeburn  4204:             }
1.640     albertel 4205: 	} elsif ($t->[0] eq 'E') {
                   4206: 	    my ($tagname) = ($t->[1]);
                   4207: 	    if ($javafiles{'codebase'} ne '') {
                   4208: 		$javafiles{'codebase'} .= '/';
                   4209: 	    }  
                   4210: 	    if (lc($tagname) eq 'applet' ||
                   4211: 		lc($tagname) eq 'object' ||
                   4212: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4213: 		) {
                   4214: 		foreach my $item (keys(%javafiles)) {
                   4215: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4216: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4217: 			&add_filetype($allfiles,$file,$item);
                   4218: 		    }
                   4219: 		}
                   4220: 	    } 
                   4221: 	    pop @state;
                   4222: 	}
                   4223:     }
1.1164    raeburn  4224:     foreach my $id (sort(keys(%flashvars))) {
                   4225:         if ($shockwave{$id} ne '') {
                   4226:             my @pairs = split(/\&/,$flashvars{$id});
                   4227:             foreach my $pair (@pairs) {
                   4228:                 my ($key,$value) = split(/\=/,$pair);
                   4229:                 if ($key eq 'thumb') {
                   4230:                     &add_filetype($allfiles,$value,$key);
                   4231:                 } elsif ($key eq 'content') {
                   4232:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4233:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4234:                     if ($ext ne '') {
                   4235:                         &add_filetype($allfiles,$path.$value,$ext);
                   4236:                     }
                   4237:                 }
                   4238:             }
                   4239:         }
                   4240:     }
1.637     raeburn  4241:     return 'ok';
                   4242: }
                   4243: 
1.639     albertel 4244: sub add_filetype {
                   4245:     my ($allfiles,$file,$type)=@_;
                   4246:     if (exists($allfiles->{$file})) {
                   4247: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4248: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4249: 	}
                   4250:     } else {
                   4251: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4252:     }
                   4253: }
                   4254: 
1.1164    raeburn  4255: sub embedded_dependency {
                   4256:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4257:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4258:         if (($identifier ne '') &&
                   4259:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4260:             ($pathfrom ne '')) {
                   4261:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4262:             foreach my $dep (@{$related->{$identifier}}) {
                   4263:                 &add_filetype($allfiles,$path.$dep,'object');
                   4264:             }
                   4265:         }
                   4266:     }
                   4267:     return;
                   4268: }
                   4269: 
1.1172.2.109  raeburn  4270: sub bubblesheet_converter {
                   4271:     my ($cdom,$fullpath,$config,$format) = @_;
                   4272:     if ((&domain($cdom) ne '') &&
                   4273:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4274:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4275:         my (%csvcols,%csvoptions);
                   4276:         if (ref($config->{'fields'}) eq 'HASH') {
                   4277:             %csvcols = %{$config->{'fields'}};
                   4278:         }
                   4279:         if (ref($config->{'options'}) eq 'HASH') {
                   4280:             %csvoptions = %{$config->{'options'}};
                   4281:         }
                   4282:         my %csvbynum = reverse(%csvcols);
                   4283:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4284:         if (keys(%scantronconf)) {
                   4285:             my %bynum = (
                   4286:                           $scantronconf{CODEstart} => 'CODEstart',
                   4287:                           $scantronconf{IDstart}   => 'IDstart',
                   4288:                           $scantronconf{PaperID}   => 'PaperID',
                   4289:                           $scantronconf{FirstName} => 'FirstName',
                   4290:                           $scantronconf{LastName}  => 'LastName',
                   4291:                           $scantronconf{Qstart}    => 'Qstart',
                   4292:                         );
                   4293:             my @ordered;
                   4294:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4295:                 push(@ordered,$bynum{$item});
                   4296:             }
                   4297:             my %mapstart = (
                   4298:                               CODEstart => 'CODE',
                   4299:                               IDstart   => 'ID',
                   4300:                               PaperID   => 'PaperID',
                   4301:                               FirstName => 'FirstName',
                   4302:                               LastName  => 'LastName',
                   4303:                               Qstart    => 'FirstQuestion',
                   4304:                            );
                   4305:             my %maplength = (
                   4306:                               CODEstart => 'CODElength',
                   4307:                               IDstart   => 'IDlength',
                   4308:                               PaperID   => 'PaperIDlength',
                   4309:                               FirstName => 'FirstNamelength',
                   4310:                               LastName  => 'LastNamelength',
                   4311:             );
                   4312:             if (open(my $fh,'<',$fullpath)) {
                   4313:                 my $output;
                   4314:                 my %lettdig = &letter_to_digits();
                   4315:                 my %diglett = reverse(%lettdig);
                   4316:                 my $numletts = scalar(keys(%lettdig));
                   4317:                 my $num = 0;
                   4318:                 while (my $line=<$fh>) {
                   4319:                     $num ++;
                   4320:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4321:                     $line =~ s{[\r\n]+$}{};
                   4322:                     my %found;
                   4323:                     my @values = split(/,/,$line);
                   4324:                     my ($qstart,$record);
                   4325:                     for (my $i=0; $i<@values; $i++) {
                   4326:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4327:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4328:                             if ($values[$i] eq '') {
                   4329:                                 $values[$i] = $scantronconf{'Qoff'};
                   4330:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4331:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4332:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4333:                                 }
                   4334:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4335:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4336:                                     $values[$i] = $diglett{$values[$i]};
                   4337:                                 }
                   4338:                             } else {
                   4339:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4340:                                     my $digit;
                   4341:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4342:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4343:                                         if ($values[$i] eq 'J') {
                   4344:                                             $digit += $numletts;
                   4345:                                         }
                   4346:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4347:                                         $digit = $values[$i]-1;
                   4348:                                         if ($values[$i] eq '0') {
                   4349:                                             $digit += $numletts;
                   4350:                                         }
                   4351:                                     }
                   4352:                                     my $qval='';
                   4353:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4354:                                         if ($j == $digit) {
                   4355:                                             $qval .= $scantronconf{'Qon'};
                   4356:                                         } else {
                   4357:                                             $qval .= $scantronconf{'Qoff'};
                   4358:                                         }
                   4359:                                     }
                   4360:                                     $values[$i] = $qval;
                   4361:                                 }
                   4362:                             }
                   4363:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4364:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4365:                             }
                   4366:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4367:                             if ($numblank > 0) {
                   4368:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4369:                             }
                   4370:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4371:                                 $qstart = $i;
                   4372:                                 $found{$csvbynum{$i}} = $values[$i];
                   4373:                             } else {
                   4374:                                 $found{'FirstQuestion'} .= $values[$i];
                   4375:                             }
                   4376:                         } elsif (exists($csvbynum{$i})) {
                   4377:                             if ($csvoptions{'rem'}) {
                   4378:                                 $values[$i] =~ s/^\s+//;
                   4379:                             }
                   4380:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4381:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4382:                                     $values[$i] = '0'.$values[$i];
                   4383:                                 }
                   4384:                             }
                   4385:                             $found{$csvbynum{$i}} = $values[$i];
                   4386:                         }
                   4387:                     }
                   4388:                     foreach my $item (@ordered) {
                   4389:                         my $currlength = 1+length($record);
                   4390:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4391:                         if ($numspaces > 0) {
                   4392:                             $record .= (' ' x $numspaces);
                   4393:                         }
                   4394:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4395:                             unless ($item eq 'Qstart') {
                   4396:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4397:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4398:                                 }
                   4399:                             }
                   4400:                             $record .= $found{$mapstart{$item}};
                   4401:                         }
                   4402:                     }
                   4403:                     $output .= "$record\n";
                   4404:                 }
                   4405:                 close($fh);
                   4406:                 if ($output) {
                   4407:                     if (open(my $fh,'>',$fullpath)) {
                   4408:                         print $fh $output;
                   4409:                         close($fh);
                   4410:                     }
                   4411:                 }
                   4412:             }
                   4413:         }
                   4414:         return;
                   4415:     }
                   4416: }
                   4417: 
                   4418: sub letter_to_digits {
                   4419:     my %lettdig = (
                   4420:                     A => 1,
                   4421:                     B => 2,
                   4422:                     C => 3,
                   4423:                     D => 4,
                   4424:                     E => 5,
                   4425:                     F => 6,
                   4426:                     G => 7,
                   4427:                     H => 8,
                   4428:                     I => 9,
                   4429:                     J => 0,
                   4430:                   );
                   4431:     return %lettdig;
                   4432: }
                   4433: 
                   4434: sub get_scantron_config {
                   4435:     my ($which,$cdom) = @_;
                   4436:     my @lines = &get_scantronformat_file($cdom);
                   4437:     my %config;
                   4438:     #FIXME probably should move to XML it has already gotten a bit much now
                   4439:     foreach my $line (@lines) {
                   4440:         my ($name,$descrip)=split(/:/,$line);
                   4441:         if ($name ne $which ) { next; }
                   4442:         chomp($line);
                   4443:         my @config=split(/:/,$line);
                   4444:         $config{'name'}=$config[0];
                   4445:         $config{'description'}=$config[1];
                   4446:         $config{'CODElocation'}=$config[2];
                   4447:         $config{'CODEstart'}=$config[3];
                   4448:         $config{'CODElength'}=$config[4];
                   4449:         $config{'IDstart'}=$config[5];
                   4450:         $config{'IDlength'}=$config[6];
                   4451:         $config{'Qstart'}=$config[7];
                   4452:         $config{'Qlength'}=$config[8];
                   4453:         $config{'Qoff'}=$config[9];
                   4454:         $config{'Qon'}=$config[10];
                   4455:         $config{'PaperID'}=$config[11];
                   4456:         $config{'PaperIDlength'}=$config[12];
                   4457:         $config{'FirstName'}=$config[13];
                   4458:         $config{'FirstNamelength'}=$config[14];
                   4459:         $config{'LastName'}=$config[15];
                   4460:         $config{'LastNamelength'}=$config[16];
                   4461:         $config{'BubblesPerRow'}=$config[17];
                   4462:         last;
                   4463:     }
                   4464:     return %config;
                   4465: }
                   4466: 
                   4467: sub get_scantronformat_file {
                   4468:     my ($cdom) = @_;
                   4469:     if ($cdom eq '') {
                   4470:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4471:     }
                   4472:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4473:     my $gottab = 0;
                   4474:     my @lines;
                   4475:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4476:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4477:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4478:             if ($formatfile ne '-1') {
                   4479:                 @lines = split("\n",$formatfile,-1);
                   4480:                 $gottab = 1;
                   4481:             }
                   4482:         }
                   4483:     }
                   4484:     if (!$gottab) {
                   4485:         my $confname = $cdom.'-domainconfig';
                   4486:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4487:         my $formatfile = &getfile($default);
                   4488:         if ($formatfile ne '-1') {
                   4489:             @lines = split("\n",$formatfile,-1);
                   4490:             $gottab = 1;
                   4491:         }
                   4492:     }
                   4493:     if (!$gottab) {
                   4494:         my @domains = &current_machine_domains();
                   4495:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4496:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4497:                 @lines = <$fh>;
                   4498:                 close($fh);
                   4499:             }
                   4500:         } else {
                   4501:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4502:                 @lines = <$fh>;
                   4503:                 close($fh);
                   4504:             }
                   4505:         }
                   4506:     }
                   4507:     return @lines;
                   4508: }
                   4509: 
1.493     albertel 4510: sub removeuploadedurl {
1.984     neumanie 4511:     my ($url)=@_;	
                   4512:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4513:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4514: }
                   4515: 
                   4516: sub removeuserfile {
                   4517:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4518:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4519:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4520:     if ($result eq 'ok') {	
1.798     raeburn  4521:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4522:             my $metafile = $fname.'.meta';
                   4523:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4524: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4525:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4526:             my $sqlresult = 
1.823     albertel 4527:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4528:                                         'portfolio_metadata',$group,
                   4529:                                         'delete');
1.798     raeburn  4530:         }
                   4531:     }
                   4532:     return $result;
1.257     www      4533: }
1.15      www      4534: 
1.530     albertel 4535: sub mkdiruserfile {
                   4536:     my ($docuname,$docudom,$dir)=@_;
                   4537:     my $home=&homeserver($docuname,$docudom);
                   4538:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4539: }
                   4540: 
1.531     albertel 4541: sub renameuserfile {
                   4542:     my ($docuname,$docudom,$old,$new)=@_;
                   4543:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4544:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4545:                         &escape("$old").':'.&escape("$new"),$home);
                   4546:     if ($result eq 'ok') {
                   4547:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4548:             my $oldmeta = $old.'.meta';
                   4549:             my $newmeta = $new.'.meta';
                   4550:             my $metaresult = 
                   4551:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4552: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4553:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4554:             my $sqlresult = 
1.823     albertel 4555:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4556:                                         'portfolio_metadata',$group,
                   4557:                                         'delete');
1.798     raeburn  4558:         }
                   4559:     }
                   4560:     return $result;
1.531     albertel 4561: }
                   4562: 
1.14      www      4563: # ------------------------------------------------------------------------- Log
                   4564: 
                   4565: sub log {
                   4566:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4567:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4568: }
                   4569: 
                   4570: # ------------------------------------------------------------------ Course Log
1.352     www      4571: #
                   4572: # This routine flushes several buffers of non-mission-critical nature
                   4573: #
1.157     www      4574: 
                   4575: sub flushcourselogs {
1.352     www      4576:     &logthis('Flushing log buffers');
                   4577: #
                   4578: # course logs
                   4579: # This is a log of all transactions in a course, which can be used
                   4580: # for data mining purposes
                   4581: #
                   4582: # It also collects the courseid database, which lists last transaction
                   4583: # times and course titles for all courseids
                   4584: #
                   4585:     my %courseidbuffer=();
1.921     raeburn  4586:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4587:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4588: 		          &escape($courselogs{$crsid}),
                   4589: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4590: 	    delete $courselogs{$crsid};
                   4591:         } else {
                   4592:             &logthis('Failed to flush log buffer for '.$crsid);
                   4593:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4594:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4595:                         " exceeded maximum size, deleting.</font>");
                   4596:                delete $courselogs{$crsid};
                   4597:             }
1.352     www      4598:         }
1.920     raeburn  4599:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4600:             'description' => $coursedescrbuf{$crsid},
                   4601:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4602:             'type'        => $coursetypebuf{$crsid},
                   4603:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4604:         };
1.191     harris41 4605:     }
1.352     www      4606: #
                   4607: # Write course id database (reverse lookup) to homeserver of courses 
                   4608: # Is used in pickcourse
                   4609: #
1.840     albertel 4610:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4611:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4612:                                     $courseidbuffer{$crs_home},
                   4613:                                     $crs_home,'timeonly');
1.352     www      4614:     }
                   4615: #
                   4616: # File accesses
                   4617: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4618: #
1.449     matthew  4619:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4620:         if ($entry =~ /___count$/) {
                   4621:             my ($dom,$name);
1.807     albertel 4622:             ($dom,$name,undef)=
1.811     albertel 4623: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4624:             if (! defined($dom) || $dom eq '' || 
                   4625:                 ! defined($name) || $name eq '') {
1.620     albertel 4626:                 my $cid = $env{'request.course.id'};
                   4627:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4628:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4629:             }
1.450     matthew  4630:             my $value = $accesshash{$entry};
                   4631:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4632:             my %temphash=($url => $value);
1.449     matthew  4633:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4634:             if ($result eq 'ok') {
                   4635:                 delete $accesshash{$entry};
                   4636:             }
                   4637:         } else {
1.811     albertel 4638:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4639:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4640:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4641:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4642:                 delete $accesshash{$entry};
                   4643:             }
1.185     www      4644:         }
1.191     harris41 4645:     }
1.352     www      4646: #
                   4647: # Roles
                   4648: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4649: #
1.800     albertel 4650:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4651:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4652: 	    split(/\:/,$entry);
                   4653:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4654:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4655:                 $rudom,$runame) eq 'ok') {
                   4656: 	    delete $userrolehash{$entry};
                   4657:         }
                   4658:     }
1.662     raeburn  4659: #
1.1172.2.90  raeburn  4660: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4661: #
                   4662:     my %domrolebuffer = ();
1.1000    raeburn  4663:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4664:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4665:         if ($domrolebuffer{$rudom}) {
                   4666:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4667:                       '='.&escape($domainrolehash{$entry});
                   4668:         } else {
                   4669:             $domrolebuffer{$rudom}.=&escape($entry).
                   4670:                       '='.&escape($domainrolehash{$entry});
                   4671:         }
                   4672:         delete $domainrolehash{$entry};
                   4673:     }
                   4674:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4675:         my %servers;
                   4676:         if (defined(&domain($dom,'primary'))) {
                   4677:             my $primary=&domain($dom,'primary');
                   4678:             my $hostname=&hostname($primary);
                   4679:             $servers{$primary} = $hostname;
                   4680:         } else {
                   4681:             %servers = &get_servers($dom,'library');
                   4682:         }
1.841     albertel 4683: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4684: 	    if (&reply('domroleput:'.$dom.':'.
                   4685: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4686: 	        last;
                   4687: 	    } else {
1.841     albertel 4688: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4689: 	    }
1.662     raeburn  4690:         }
                   4691:     }
1.186     www      4692:     $dumpcount++;
1.157     www      4693: }
                   4694: 
                   4695: sub courselog {
                   4696:     my $what=shift;
1.158     www      4697:     $what=time.':'.$what;
1.620     albertel 4698:     unless ($env{'request.course.id'}) { return ''; }
                   4699:     $coursedombuf{$env{'request.course.id'}}=
                   4700:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4701:     $coursenumbuf{$env{'request.course.id'}}=
                   4702:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4703:     $coursehombuf{$env{'request.course.id'}}=
                   4704:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4705:     $coursedescrbuf{$env{'request.course.id'}}=
                   4706:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4707:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4708:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4709:     $courseownerbuf{$env{'request.course.id'}}=
                   4710:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4711:     $coursetypebuf{$env{'request.course.id'}}=
                   4712:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4713:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4714: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4715:     } else {
1.620     albertel 4716: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4717:     }
1.620     albertel 4718:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4719: 	&flushcourselogs();
                   4720:     }
1.158     www      4721: }
                   4722: 
                   4723: sub courseacclog {
                   4724:     my $fnsymb=shift;
1.620     albertel 4725:     unless ($env{'request.course.id'}) { return ''; }
                   4726:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4727:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4728:         $what.=':POST';
1.583     matthew  4729:         # FIXME: Probably ought to escape things....
1.800     albertel 4730: 	foreach my $key (keys(%env)) {
                   4731:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4732:                 my $formitem = $1;
                   4733:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4734:                     $what.=':'.$formitem.'='.$env{$key};
                   4735:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.118.  .12(raeb 4736:-20):                     if ($formitem eq 'proctorpassword') {
                   4737:-20):                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
                   4738:-20):                     } else {
                   4739:-20):                         $what.=':'.$formitem.'='.$env{$key};
                   4740:-20):                     }
1.975     raeburn  4741:                 }
1.158     www      4742:             }
1.191     harris41 4743:         }
1.583     matthew  4744:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4745:         # FIXME: We should not be depending on a form parameter that someone
                   4746:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4747:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4748:             $what.= ':POST';
                   4749:             # FIXME: Probably ought to escape things....
                   4750:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4751:                                  'crsdiscuss') {
1.620     albertel 4752:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4753:             }
                   4754:         }
1.158     www      4755:     }
                   4756:     &courselog($what);
1.149     www      4757: }
                   4758: 
1.185     www      4759: sub countacc {
                   4760:     my $url=&declutter(shift);
1.458     matthew  4761:     return if (! defined($url) || $url eq '');
1.620     albertel 4762:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4763: #
                   4764: # Mark that this url was used in this course
                   4765: #
1.620     albertel 4766:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4767: #
                   4768: # Increase the access count for this resource in this child process
                   4769: #
1.281     www      4770:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4771:     $accesshash{$key}++;
1.185     www      4772: }
1.349     www      4773: 
1.361     www      4774: sub linklog {
                   4775:     my ($from,$to)=@_;
                   4776:     $from=&declutter($from);
                   4777:     $to=&declutter($to);
                   4778:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4779:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4780: }
1.1160    www      4781: 
                   4782: sub statslog {
                   4783:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4784:     if ($users<2) { return; }
                   4785:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4786:             'course'       => $env{'request.course.id'},
                   4787:             'sections'     => '"all"',
                   4788:             'num_students' => $users,
                   4789:             'part'         => $part,
                   4790:             'symb'         => $symb,
                   4791:             'mean_tries'   => $av_attempts,
                   4792:             'deg_of_diff'  => $degdiff});
                   4793:     foreach my $key (keys(%dynstore)) {
                   4794:         $accesshash{$key}=$dynstore{$key};
                   4795:     }
                   4796: }
1.361     www      4797:   
1.349     www      4798: sub userrolelog {
                   4799:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4800:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4801:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4802:        $userrolehash
                   4803:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4804:                     =$tend.':'.$tstart;
1.662     raeburn  4805:     }
1.1169    droeschl 4806:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4807:        $userrolehash
                   4808:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4809:                     =$tend.':'.$tstart;
                   4810:     }
1.1172.2.90  raeburn  4811:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4812:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4813:        $domainrolehash
                   4814:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4815:                     = $tend.':'.$tstart;
                   4816:     }
1.351     www      4817: }
                   4818: 
1.957     raeburn  4819: sub courserolelog {
                   4820:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4821:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4822:         my $cdom = $1;
                   4823:         my $cnum = $2;
                   4824:         my $sec = $3;
                   4825:         my $namespace = 'rolelog';
                   4826:         my %storehash = (
                   4827:                            role    => $trole,
                   4828:                            start   => $tstart,
                   4829:                            end     => $tend,
                   4830:                            selfenroll => $selfenroll,
                   4831:                            context    => $context,
                   4832:                         );
                   4833:         if ($trole eq 'gr') {
                   4834:             $namespace = 'groupslog';
                   4835:             $storehash{'group'} = $sec;
                   4836:         } else {
                   4837:             $storehash{'section'} = $sec;
                   4838:         }
                   4839:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4840:                    $domain,$cnum,$cdom);
                   4841:         if (($trole ne 'st') || ($sec ne '')) {
                   4842:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4843:         }
                   4844:     }
                   4845:     return;
                   4846: }
                   4847: 
1.1172.2.9  raeburn  4848: sub domainrolelog {
                   4849:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4850:     if ($area =~ m{^/($match_domain)/$}) {
                   4851:         my $cdom = $1;
                   4852:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4853:         my $namespace = 'rolelog';
                   4854:         my %storehash = (
                   4855:                            role    => $trole,
                   4856:                            start   => $tstart,
                   4857:                            end     => $tend,
                   4858:                            context => $context,
                   4859:                         );
                   4860:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4861:                    $domain,$domconfiguser,$cdom);
                   4862:     }
                   4863:     return;
                   4864: 
                   4865: }
                   4866: 
                   4867: sub coauthorrolelog {
                   4868:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4869:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4870:         my $audom = $1;
                   4871:         my $auname = $2;
                   4872:         my $namespace = 'rolelog';
                   4873:         my %storehash = (
                   4874:                            role    => $trole,
                   4875:                            start   => $tstart,
                   4876:                            end     => $tend,
                   4877:                            context => $context,
                   4878:                         );
                   4879:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4880:                    $domain,$auname,$audom);
                   4881:     }
                   4882:     return;
                   4883: }
                   4884: 
1.351     www      4885: sub get_course_adv_roles {
1.948     raeburn  4886:     my ($cid,$codes) = @_;
1.620     albertel 4887:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4888:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4889:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4890:     my %nothide=();
1.800     albertel 4891:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4892:         if ($user !~ /:/) {
                   4893: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4894:         } else {
                   4895:             $nothide{$user}=1;
                   4896:         }
1.470     www      4897:     }
1.1172.2.23  raeburn  4898:     my @possdoms = ($coursehash{'domain'});
                   4899:     if ($coursehash{'checkforpriv'}) {
                   4900:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4901:     }
1.351     www      4902:     my %returnhash=();
                   4903:     my %dumphash=
                   4904:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4905:     my $now=time;
1.997     raeburn  4906:     my %privileged;
1.1000    raeburn  4907:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4908: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4909:         if (($tstart) && ($tstart<0)) { next; }
                   4910:         if (($tend) && ($tend<$now)) { next; }
                   4911:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4912:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4913: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4914:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4915:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4916: 	if ($role eq 'cr') { next; }
1.948     raeburn  4917:         if ($codes) {
                   4918:             if ($section) { $role .= ':'.$section; }
                   4919:             if ($returnhash{$role}) {
                   4920:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4921:             } else {
                   4922:                 $returnhash{$role}=$username.':'.$domain;
                   4923:             }
1.351     www      4924:         } else {
1.988     raeburn  4925:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4926:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4927:             if ($returnhash{$key}) {
                   4928: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4929:             } else {
                   4930:                 $returnhash{$key}=$username.':'.$domain;
                   4931:             }
1.351     www      4932:         }
1.948     raeburn  4933:     }
1.400     www      4934:     return %returnhash;
                   4935: }
                   4936: 
                   4937: sub get_my_roles {
1.937     raeburn  4938:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4939:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4940:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4941:     my (%dumphash,%nothide);
1.1086    raeburn  4942:     if ($context eq 'userroles') {
1.1166    raeburn  4943:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4944:     } else {
1.1172.2.23  raeburn  4945:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4946:         if ($hidepriv) {
                   4947:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4948:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4949:                 if ($user !~ /:/) {
                   4950:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4951:                 } else {
                   4952:                     $nothide{$user} = 1;
                   4953:                 }
                   4954:             }
                   4955:         }
1.858     raeburn  4956:     }
1.400     www      4957:     my %returnhash=();
                   4958:     my $now=time;
1.999     raeburn  4959:     my %privileged;
1.800     albertel 4960:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4961:         my ($role,$tend,$tstart);
                   4962:         if ($context eq 'userroles') {
1.1149    raeburn  4963:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4964: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4965:         } else {
                   4966:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4967:         }
1.400     www      4968:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4969:         my $status = 'active';
1.939     raeburn  4970:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4971:             $status = 'previous';
                   4972:         } 
                   4973:         if (($tstart) && ($now<$tstart)) {
                   4974:             $status = 'future';
                   4975:         }
                   4976:         if (ref($types) eq 'ARRAY') {
                   4977:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4978:                 next;
                   4979:             } 
                   4980:         } else {
                   4981:             if ($status ne 'active') {
                   4982:                 next;
                   4983:             }
                   4984:         }
1.867     raeburn  4985:         my ($rolecode,$username,$domain,$section,$area);
                   4986:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  4987:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4988:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4989:         } else {
                   4990:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4991:         }
1.832     raeburn  4992:         if (ref($roledoms) eq 'ARRAY') {
                   4993:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4994:                 next;
                   4995:             }
                   4996:         }
                   4997:         if (ref($roles) eq 'ARRAY') {
                   4998:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4999:                 if ($role =~ /^cr\//) {
                   5000:                     if (!grep(/^cr$/,@{$roles})) {
                   5001:                         next;
                   5002:                     }
1.1104    raeburn  5003:                 } elsif ($role =~ /^gr\//) {
                   5004:                     if (!grep(/^gr$/,@{$roles})) {
                   5005:                         next;
                   5006:                     }
1.922     raeburn  5007:                 } else {
                   5008:                     next;
                   5009:                 }
1.832     raeburn  5010:             }
1.867     raeburn  5011:         }
1.937     raeburn  5012:         if ($hidepriv) {
1.1172.2.23  raeburn  5013:             my @privroles = ('dc','su');
1.999     raeburn  5014:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  5015:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5016:             } else {
1.1172.2.23  raeburn  5017:                 my $possdoms = [$domain];
                   5018:                 if (ref($roledoms) eq 'ARRAY') {
                   5019:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  5020:                 }
1.1172.2.23  raeburn  5021:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5022:                     if (!$nothide{$username.':'.$domain}) {
                   5023:                         next;
                   5024:                     }
                   5025:                 }
1.937     raeburn  5026:             }
                   5027:         }
1.933     raeburn  5028:         if ($withsec) {
                   5029:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5030:                 $tstart.':'.$tend;
                   5031:         } else {
                   5032:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5033:         }
1.832     raeburn  5034:     }
1.373     www      5035:     return %returnhash;
1.399     www      5036: }
                   5037: 
1.1172.2.89  raeburn  5038: sub get_all_adhocroles {
                   5039:     my ($dom) = @_;
                   5040:     my @roles_by_num = ();
                   5041:     my %domdefaults = &get_domain_defaults($dom);
                   5042:     my (%description,%access_in_dom,%access_info);
                   5043:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5044:         my $count = 0;
                   5045:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5046:         my %ordered;
                   5047:         foreach my $role (sort(keys(%domcurrent))) {
                   5048:             my ($order,$desc,$access_in_dom);
                   5049:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5050:                 $order = $domcurrent{$role}{'order'};
                   5051:                 $desc = $domcurrent{$role}{'desc'};
                   5052:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5053:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5054:             }
                   5055:             if ($order eq '') {
                   5056:                 $order = $count;
                   5057:             }
                   5058:             $ordered{$order} = $role;
                   5059:             if ($desc ne '') {
                   5060:                 $description{$role} = $desc;
                   5061:             } else {
                   5062:                 $description{$role}= $role;
                   5063:             }
                   5064:             $count++;
                   5065:         }
                   5066:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5067:             push(@roles_by_num,$ordered{$item});
                   5068:         }
                   5069:     }
                   5070:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5071: }
                   5072: 
                   5073: sub get_my_adhocroles {
                   5074:     my ($cid,$checkreg) = @_;
                   5075:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5076:     if ($env{'request.course.id'} eq $cid) {
                   5077:         $cdom = $env{'course.'.$cid.'.domain'};
                   5078:         $cnum = $env{'course.'.$cid.'.num'};
                   5079:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5080:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5081:         $cdom = $1;
                   5082:         $cnum = $2;
                   5083:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5084:                                      $cdom,$cnum);
                   5085:     }
                   5086:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5087:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5088:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5089:         if ($rosterhash{$user} ne '') {
                   5090:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5091:             return ([],{}) if ($type eq 'auto');
                   5092:         }
                   5093:     }
                   5094:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5095:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5096:             my $then=$env{'user.login.time'};
                   5097:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5098:             if (!$update) {
                   5099:                 $update = $then;
                   5100:             }
                   5101:             my @liveroles;
                   5102:             foreach my $role ('dh','da') {
                   5103:                 if ($env{"user.role.$role./$cdom/"}) {
                   5104:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5105:                     my $limit = $update;
                   5106:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5107:                         $limit = $then;
                   5108:                     }
                   5109:                     my $activerole = 1;
                   5110:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5111:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5112:                     if ($activerole) {
                   5113:                         push(@liveroles,$role);
                   5114:                     }
                   5115:                 }
                   5116:             }
                   5117:             if (@liveroles) {
1.1172.2.89  raeburn  5118:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5119:                     my ($accessref,$accessinfo,%access_in_dom);
                   5120:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5121:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5122:                         if (@{$roles_by_num}) {
                   5123:                             my %settings;
                   5124:                             if ($env{'request.course.id'} eq $cid) {
                   5125:                                 foreach my $envkey (keys(%env)) {
                   5126:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5127:                                         $settings{$1} = $env{$envkey};
                   5128:                                     }
                   5129:                                 }
                   5130:                             } else {
                   5131:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5132:                             }
                   5133:                             my %setincrs;
                   5134:                             if ($settings{'internal.adhocaccess'}) {
                   5135:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5136:                             }
                   5137:                             my @statuses;
                   5138:                             if ($env{'environment.inststatus'}) {
                   5139:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5140:                             }
                   5141:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5142:                             if (ref($accessref) eq 'HASH') {
                   5143:                                 %access_in_dom = %{$accessref};
                   5144:                             }
                   5145:                             foreach my $role (@{$roles_by_num}) {
                   5146:                                 my ($curraccess,@okstatus,@personnel);
                   5147:                                 if ($setincrs{$role}) {
                   5148:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5149:                                     if ($curraccess eq 'status') {
                   5150:                                         @okstatus = split(/\&/,$rest);
                   5151:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5152:                                         @personnel = split(/\&/,$rest);
                   5153:                                     }
                   5154:                                 } else {
                   5155:                                     $curraccess = $access_in_dom{$role};
                   5156:                                     if (ref($accessinfo) eq 'HASH') {
                   5157:                                         if ($curraccess eq 'status') {
                   5158:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5159:                                                 @okstatus = @{$accessinfo->{$role}};
                   5160:                                             }
                   5161:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5162:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5163:                                                 @personnel = @{$accessinfo->{$role}};
                   5164:                                             }
                   5165:                                         }
                   5166:                                     }
                   5167:                                 }
                   5168:                                 if ($curraccess eq 'none') {
                   5169:                                     next;
                   5170:                                 } elsif ($curraccess eq 'all') {
                   5171:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5172:                                 } elsif ($curraccess eq 'dh') {
                   5173:                                     if (grep(/^dh$/,@liveroles)) {
                   5174:                                         push(@possroles,$role);
                   5175:                                     } else {
                   5176:                                         next;
                   5177:                                     }
                   5178:                                 } elsif ($curraccess eq 'da') {
                   5179:                                     if (grep(/^da$/,@liveroles)) {
                   5180:                                         push(@possroles,$role);
                   5181:                                     } else {
                   5182:                                         next;
                   5183:                                     }
1.1172.2.89  raeburn  5184:                                 } elsif ($curraccess eq 'status') {
                   5185:                                     if (@okstatus) {
                   5186:                                         if (!@statuses) {
                   5187:                                             if (grep(/^default$/,@okstatus)) {
                   5188:                                                 push(@possroles,$role);
                   5189:                                             }
                   5190:                                         } else {
                   5191:                                             foreach my $status (@okstatus) {
                   5192:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5193:                                                     push(@possroles,$role);
                   5194:                                                     last;
                   5195:                                                 }
                   5196:                                             }
                   5197:                                         }
                   5198:                                     }
                   5199:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5200:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5201:                                         if ($curraccess eq 'exc') {
                   5202:                                             push(@possroles,$role);
                   5203:                                         }
                   5204:                                     } elsif ($curraccess eq 'inc') {
                   5205:                                         push(@possroles,$role);
                   5206:                                     }
                   5207:                                 }
                   5208:                             }
                   5209:                         }
                   5210:                     }
                   5211:                 }
                   5212:             }
                   5213:         }
                   5214:     }
                   5215:     unless (ref($description) eq 'HASH') {
                   5216:         if (ref($roles_by_num) eq 'ARRAY') {
                   5217:             my %desc;
                   5218:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5219:             $description = \%desc;
                   5220:         } else {
                   5221:             $description = {};
                   5222:         }
                   5223:     }
                   5224:     return (\@possroles,$description);
                   5225: }
                   5226: 
1.399     www      5227: # ----------------------------------------------------- Frontpage Announcements
                   5228: #
                   5229: #
                   5230: 
                   5231: sub postannounce {
                   5232:     my ($server,$text)=@_;
1.844     albertel 5233:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5234:     unless ($text=~/\w/) { $text=''; }
                   5235:     return &reply('setannounce:'.&escape($text),$server);
                   5236: }
                   5237: 
                   5238: sub getannounce {
1.448     albertel 5239: 
1.1172.2.96  raeburn  5240:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5241: 	my $announcement='';
1.800     albertel 5242: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5243: 	close($fh);
1.399     www      5244: 	if ($announcement=~/\w/) { 
                   5245: 	    return 
                   5246:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5247:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5248: 	} else {
                   5249: 	    return '';
                   5250: 	}
                   5251:     } else {
                   5252: 	return '';
                   5253:     }
1.351     www      5254: }
1.353     www      5255: 
                   5256: # ---------------------------------------------------------- Course ID routines
                   5257: # Deal with domain's nohist_courseid.db files
                   5258: #
                   5259: 
                   5260: sub courseidput {
1.921     raeburn  5261:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5262:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5263:     my $outcome;
                   5264:     if ($caller eq 'timeonly') {
                   5265:         my $cids = '';
                   5266:         foreach my $item (keys(%$storehash)) {
                   5267:             $cids.=&escape($item).'&';
                   5268:         }
                   5269:         $cids=~s/\&$//;
                   5270:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5271:                           $coursehome);       
                   5272:     } else {
                   5273:         my $items = '';
                   5274:         foreach my $item (keys(%$storehash)) {
                   5275:             $items.= &escape($item).'='.
                   5276:                      &freeze_escape($$storehash{$item}).'&';
                   5277:         }
                   5278:         $items=~s/\&$//;
                   5279:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5280:                           $coursehome);
1.918     raeburn  5281:     }
                   5282:     if ($outcome eq 'unknown_cmd') {
                   5283:         my $what;
                   5284:         foreach my $cid (keys(%$storehash)) {
                   5285:             $what .= &escape($cid).'=';
1.921     raeburn  5286:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5287:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5288:             }
                   5289:             $what =~ s/\:$/&/;
                   5290:         }
                   5291:         $what =~ s/\&$//;  
                   5292:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5293:     } else {
                   5294:         return $outcome;
                   5295:     }
1.353     www      5296: }
                   5297: 
                   5298: sub courseiddump {
1.921     raeburn  5299:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5300:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5301:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5302:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5303:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5304:     my $as_hash = 1;
                   5305:     my %returnhash;
                   5306:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5307:     my %libserv = &all_library();
                   5308:     foreach my $tryserver (keys(%libserv)) {
                   5309:         if ( (  $hostidflag == 1 
                   5310: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5311: 	     || (!defined($hostidflag)) ) {
                   5312: 
1.918     raeburn  5313: 	    if (($domfilter eq '') ||
                   5314: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5315:                 my $rep;
                   5316:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5317:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5318:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5319:                                 &escape($descfilter), &escape($instcodefilter),
                   5320:                                 &escape($ownerfilter), &escape($coursefilter),
                   5321:                                 &escape($typefilter), &escape($regexp_ok),
                   5322:                                 $as_hash, &escape($selfenrollonly),
                   5323:                                 &escape($catfilter), $showhidden, $caller,
                   5324:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5325:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5326:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5327:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5328:                 } else {
                   5329:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5330:                              $sincefilter.':'.&escape($descfilter).':'.
                   5331:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5332:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5333:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5334:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5335:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5336:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5337:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5338:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5339:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5340:                 }
                   5341: 
1.918     raeburn  5342:                 my @pairs=split(/\&/,$rep);
                   5343:                 foreach my $item (@pairs) {
                   5344:                     my ($key,$value)=split(/\=/,$item,2);
                   5345:                     $key = &unescape($key);
                   5346:                     next if ($key =~ /^error: 2 /);
                   5347:                     my $result = &thaw_unescape($value);
                   5348:                     if (ref($result) eq 'HASH') {
                   5349:                         $returnhash{$key}=$result;
                   5350:                     } else {
1.921     raeburn  5351:                         my @responses = split(/:/,$value);
                   5352:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5353:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5354:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5355:                         }
1.1008    raeburn  5356:                     }
1.353     www      5357:                 }
                   5358:             }
                   5359:         }
                   5360:     }
                   5361:     return %returnhash;
                   5362: }
                   5363: 
1.1055    raeburn  5364: sub courselastaccess {
                   5365:     my ($cdom,$cnum,$hostidref) = @_;
                   5366:     my %returnhash;
                   5367:     if ($cdom && $cnum) {
                   5368:         my $chome = &homeserver($cnum,$cdom);
                   5369:         if ($chome ne 'no_host') {
                   5370:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5371:             &extract_lastaccess(\%returnhash,$rep);
                   5372:         }
                   5373:     } else {
                   5374:         if (!$cdom) { $cdom=''; }
                   5375:         my %libserv = &all_library();
                   5376:         foreach my $tryserver (keys(%libserv)) {
                   5377:             if (ref($hostidref) eq 'ARRAY') {
                   5378:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5379:             } 
                   5380:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5381:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5382:                 &extract_lastaccess(\%returnhash,$rep);
                   5383:             }
                   5384:         }
                   5385:     }
                   5386:     return %returnhash;
                   5387: }
                   5388: 
                   5389: sub extract_lastaccess {
                   5390:     my ($returnhash,$rep) = @_;
                   5391:     if (ref($returnhash) eq 'HASH') {
                   5392:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5393:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5394:                  $rep eq '') {
                   5395:             my @pairs=split(/\&/,$rep);
                   5396:             foreach my $item (@pairs) {
                   5397:                 my ($key,$value)=split(/\=/,$item,2);
                   5398:                 $key = &unescape($key);
                   5399:                 next if ($key =~ /^error: 2 /);
                   5400:                 $returnhash->{$key} = &thaw_unescape($value);
                   5401:             }
                   5402:         }
                   5403:     }
                   5404:     return;
                   5405: }
                   5406: 
1.658     raeburn  5407: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5408: 
                   5409: sub dcmailput {
1.685     raeburn  5410:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5411:     my $status = &Apache::lonnet::critical(
1.740     www      5412:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5413:        &escape($message),$server);
1.662     raeburn  5414:     return $status;
                   5415: }
                   5416: 
1.658     raeburn  5417: sub dcmaildump {
                   5418:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5419:     my %returnhash=();
1.846     albertel 5420: 
                   5421:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5422:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5423:                                                          &escape($enddate).':';
                   5424: 	my @esc_senders=map { &escape($_)} @$senders;
                   5425: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5426: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5427:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5428:             if (($key) && ($value)) {
                   5429:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5430:             }
                   5431:         }
                   5432:     }
                   5433:     return %returnhash;
                   5434: }
1.662     raeburn  5435: # ---------------------------------------------------------- Domain roles
                   5436: 
                   5437: sub get_domain_roles {
                   5438:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5439:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5440:         $startdate = '.';
                   5441:     }
1.1018    raeburn  5442:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5443:         $enddate = '.';
                   5444:     }
1.922     raeburn  5445:     my $rolelist;
                   5446:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5447:         $rolelist = join('&',@{$roles});
1.922     raeburn  5448:     }
1.662     raeburn  5449:     my %personnel = ();
1.841     albertel 5450: 
                   5451:     my %servers = &get_servers($dom,'library');
                   5452:     foreach my $tryserver (keys(%servers)) {
                   5453: 	%{$personnel{$tryserver}}=();
                   5454: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5455: 					    &escape($startdate).':'.
                   5456: 					    &escape($enddate).':'.
                   5457: 					    &escape($rolelist), $tryserver))) {
                   5458: 	    my ($key,$value) = split(/\=/,$line,2);
                   5459: 	    if (($key) && ($value)) {
                   5460: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5461: 	    }
                   5462: 	}
1.662     raeburn  5463:     }
                   5464:     return %personnel;
                   5465: }
1.658     raeburn  5466: 
1.1172.2.89  raeburn  5467: sub get_active_domroles {
                   5468:     my ($dom,$roles) = @_;
                   5469:     return () unless (ref($roles) eq 'ARRAY');
                   5470:     my $now = time;
                   5471:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5472:     my %domroles;
                   5473:     foreach my $server (keys(%dompersonnel)) {
                   5474:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5475:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5476:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5477:         }
                   5478:     }
                   5479:     return %domroles;
                   5480: }
                   5481: 
1.1057    www      5482: # ----------------------------------------------------------- Interval timing 
1.149     www      5483: 
1.1153    www      5484: {
                   5485: # Caches needed for speedup of navmaps
                   5486: # We don't want to cache this for very long at all (5 seconds at most)
                   5487: # 
                   5488: # The user for whom we cache
                   5489: my $cachedkey='';
                   5490: # The cached times for this user
                   5491: my %cachedtimes=();
                   5492: # When this was last done
1.1172.2.66  raeburn  5493: my $cachedtime='';
1.1153    www      5494: 
                   5495: sub load_all_first_access {
1.1172.2.118.  .1(raebu 5496:20):     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5497:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.118.  .1(raebu 5498:20):         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5499:20):         (!$ignorecache)) {
1.1154    raeburn  5500:         return;
                   5501:     }
                   5502:     $cachedtime=time;
                   5503:     $cachedkey=$uname.':'.$udom;
                   5504:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5505: }
                   5506: 
1.504     albertel 5507: sub get_first_access {
1.1172.2.118.  .1(raebu 5508:20):     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5509:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5510:     if ($argsymb) { $symb=$argsymb; }
                   5511:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5512:     if ($argmap) { $map = $argmap; }
1.926     albertel 5513:     if ($type eq 'course') {
                   5514: 	$res='course';
                   5515:     } elsif ($type eq 'map') {
1.588     albertel 5516: 	$res=&symbread($map);
                   5517:     } else {
                   5518: 	$res=$symb;
                   5519:     }
1.1172.2.118.  .1(raebu 5520:20):     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5521:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5522: }
                   5523: 
                   5524: sub set_first_access {
1.1162    raeburn  5525:     my ($type,$interval)=@_;
1.790     albertel 5526:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5527:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5528:     if ($type eq 'course') {
                   5529: 	$res='course';
                   5530:     } elsif ($type eq 'map') {
1.588     albertel 5531: 	$res=&symbread($map);
                   5532:     } else {
                   5533: 	$res=$symb;
                   5534:     }
1.1153    www      5535:     $cachedkey='';
1.1162    raeburn  5536:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5537:     if ($firstaccess) {
                   5538:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5539:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5540:                  "in $courseid");
                   5541:         return 'already_set';
                   5542:     } else {
1.1162    raeburn  5543:         my $start = time;
                   5544: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5545:                           $udom,$uname);
                   5546:         if ($putres eq 'ok') {
                   5547:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5548:                  $udom,$uname); 
                   5549:             &appenv(
                   5550:                      {
                   5551:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5552:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5553:                      }
                   5554:                   );
1.1172.2.97  raeburn  5555:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5556:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5557:             }
1.1172.2.102  raeburn  5558:         } elsif ($putres ne 'refused') {
                   5559:             &logthis("Result: $putres when attempting to set first access time ".
                   5560:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5561:         }
                   5562:         return $putres;
1.505     albertel 5563:     }
                   5564:     return 'already_set';
1.504     albertel 5565: }
1.1153    www      5566: }
1.1172.2.32  raeburn  5567: 
                   5568: sub checkout {
                   5569:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5570:     my $now=time;
                   5571:     my $lonhost=$perlvar{'lonHostID'};
                   5572:     my $infostr=&escape(
                   5573:                  'CHECKOUTTOKEN&'.
                   5574:                  $tuname.'&'.
                   5575:                  $tudom.'&'.
                   5576:                  $tcrsid.'&'.
                   5577:                  $symb.'&'.
                   5578:                  $now.'&'.$ENV{'REMOTE_ADDR'});
                   5579:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5580:     if ($token=~/^error\:/) {
                   5581:         &logthis("<font color=\"blue\">WARNING: ".
                   5582:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5583:                  "</font>");
                   5584:         return '';
                   5585:     }
                   5586: 
                   5587:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5588:     $token=~tr/a-z/A-Z/;
                   5589: 
                   5590:     my %infohash=('resource.0.outtoken' => $token,
                   5591:                   'resource.0.checkouttime' => $now,
                   5592:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
                   5593: 
                   5594:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5595:        return '';
                   5596:     } else {
                   5597:         &logthis("<font color=\"blue\">WARNING: ".
                   5598:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5599:                  "</font>");
                   5600:     }
                   5601: 
                   5602:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5603:                          &escape('Checkout '.$infostr.' - '.
                   5604:                                                  $token)) ne 'ok') {
                   5605:         return '';
                   5606:     } else {
                   5607:         &logthis("<font color=\"blue\">WARNING: ".
                   5608:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5609:                  "</font>");
                   5610:     }
                   5611:     return $token;
                   5612: }
                   5613: 
                   5614: # ------------------------------------------------------------ Check in an item
                   5615: 
                   5616: sub checkin {
                   5617:     my $token=shift;
                   5618:     my $now=time;
                   5619:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5620:     $lonhost=~tr/A-Z/a-z/;
                   5621:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5622:     $dtoken=~s/\W/\_/g;
                   5623:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5624:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5625: 
                   5626:     unless (($tuname) && ($tudom)) {
                   5627:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5628:         return '';
                   5629:     }
                   5630: 
                   5631:     unless (&allowed('mgr',$tcrsid)) {
                   5632:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5633:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5634:         return '';
                   5635:     }
                   5636: 
                   5637:     my %infohash=('resource.0.intoken' => $token,
                   5638:                   'resource.0.checkintime' => $now,
                   5639:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
                   5640: 
                   5641:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5642:        return '';
                   5643:     }
                   5644: 
                   5645:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5646:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5647:         return '';
                   5648:     }
                   5649: 
                   5650:     return ($symb,$tuname,$tudom,$tcrsid);
                   5651: }
                   5652: 
1.110     www      5653: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5654: 
                   5655: sub expirespread {
                   5656:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5657:     my $cid=$env{'request.course.id'}; 
1.110     www      5658:     if ($cid) {
                   5659:        my $now=time;
                   5660:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5661:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5662:                             $env{'course.'.$cid.'.num'}.
1.110     www      5663: 	        	    ':nohist_expirationdates:'.
                   5664:                             &escape($key).'='.$now,
1.620     albertel 5665:                             $env{'course.'.$cid.'.home'})
1.110     www      5666:     }
                   5667:     return 'ok';
1.14      www      5668: }
                   5669: 
1.109     www      5670: # ----------------------------------------------------- Devalidate Spreadsheets
                   5671: 
                   5672: sub devalidate {
1.325     www      5673:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5674:     my $cid=$env{'request.course.id'}; 
1.109     www      5675:     if ($cid) {
1.391     matthew  5676:         # delete the stored spreadsheets for
                   5677:         # - the student level sheet of this user in course's homespace
                   5678:         # - the assessment level sheet for this resource 
                   5679:         #   for this user in user's homespace
1.553     albertel 5680: 	# - current conditional state info
1.325     www      5681: 	my $key=$uname.':'.$udom.':';
1.109     www      5682:         my $status=
1.299     matthew  5683: 	    &del('nohist_calculatedsheets',
1.391     matthew  5684: 		 [$key.'studentcalc:'],
1.620     albertel 5685: 		 $env{'course.'.$cid.'.domain'},
                   5686: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5687: 		.' '.
                   5688: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5689: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5690:         unless ($status eq 'ok ok') {
                   5691:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5692:                     $uname.' at '.$udom.' for '.
1.109     www      5693: 		    $symb.': '.$status);
1.133     albertel 5694:         }
1.553     albertel 5695: 	&delenv('user.state.'.$cid);
1.109     www      5696:     }
                   5697: }
                   5698: 
1.265     albertel 5699: sub get_scalar {
                   5700:     my ($string,$end) = @_;
                   5701:     my $value;
                   5702:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5703: 	$value = $1;
                   5704:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5705: 	$value = $1;
                   5706:     }
                   5707:     return &unescape($value);
                   5708: }
                   5709: 
                   5710: sub array2str {
                   5711:   my (@array) = @_;
                   5712:   my $result=&arrayref2str(\@array);
                   5713:   $result=~s/^__ARRAY_REF__//;
                   5714:   $result=~s/__END_ARRAY_REF__$//;
                   5715:   return $result;
                   5716: }
                   5717: 
1.204     albertel 5718: sub arrayref2str {
                   5719:   my ($arrayref) = @_;
1.265     albertel 5720:   my $result='__ARRAY_REF__';
1.204     albertel 5721:   foreach my $elem (@$arrayref) {
1.265     albertel 5722:     if(ref($elem) eq 'ARRAY') {
                   5723:       $result.=&arrayref2str($elem).'&';
                   5724:     } elsif(ref($elem) eq 'HASH') {
                   5725:       $result.=&hashref2str($elem).'&';
                   5726:     } elsif(ref($elem)) {
                   5727:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5728:     } else {
                   5729:       $result.=&escape($elem).'&';
                   5730:     }
                   5731:   }
                   5732:   $result=~s/\&$//;
1.265     albertel 5733:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5734:   return $result;
                   5735: }
                   5736: 
1.168     albertel 5737: sub hash2str {
1.204     albertel 5738:   my (%hash) = @_;
                   5739:   my $result=&hashref2str(\%hash);
1.265     albertel 5740:   $result=~s/^__HASH_REF__//;
                   5741:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5742:   return $result;
                   5743: }
                   5744: 
                   5745: sub hashref2str {
                   5746:   my ($hashref)=@_;
1.265     albertel 5747:   my $result='__HASH_REF__';
1.800     albertel 5748:   foreach my $key (sort(keys(%$hashref))) {
                   5749:     if (ref($key) eq 'ARRAY') {
                   5750:       $result.=&arrayref2str($key).'=';
                   5751:     } elsif (ref($key) eq 'HASH') {
                   5752:       $result.=&hashref2str($key).'=';
                   5753:     } elsif (ref($key)) {
1.265     albertel 5754:       $result.='=';
1.800     albertel 5755:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5756:     } else {
1.1132    raeburn  5757: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5758:     }
                   5759: 
1.800     albertel 5760:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5761:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5762:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5763:       $result.=&hashref2str($hashref->{$key}).'&';
                   5764:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5765:        $result.='&';
1.800     albertel 5766:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5767:     } else {
1.800     albertel 5768:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5769:     }
                   5770:   }
1.168     albertel 5771:   $result=~s/\&$//;
1.265     albertel 5772:   $result .= '__END_HASH_REF__';
1.168     albertel 5773:   return $result;
                   5774: }
                   5775: 
                   5776: sub str2hash {
1.265     albertel 5777:     my ($string)=@_;
                   5778:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5779:     return %$hash;
                   5780: }
                   5781: 
                   5782: sub str2hashref {
1.168     albertel 5783:   my ($string) = @_;
1.265     albertel 5784: 
                   5785:   my %hash;
                   5786: 
                   5787:   if($string !~ /^__HASH_REF__/) {
                   5788:       if (! ($string eq '' || !defined($string))) {
                   5789: 	  $hash{'error'}='Not hash reference';
                   5790:       }
                   5791:       return (\%hash, $string);
                   5792:   }
                   5793: 
                   5794:   $string =~ s/^__HASH_REF__//;
                   5795: 
                   5796:   while($string !~ /^__END_HASH_REF__/) {
                   5797:       #key
                   5798:       my $key='';
                   5799:       if($string =~ /^__HASH_REF__/) {
                   5800:           ($key, $string)=&str2hashref($string);
                   5801:           if(defined($key->{'error'})) {
                   5802:               $hash{'error'}='Bad data';
                   5803:               return (\%hash, $string);
                   5804:           }
                   5805:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5806:           ($key, $string)=&str2arrayref($string);
                   5807:           if($key->[0] eq 'Array reference error') {
                   5808:               $hash{'error'}='Bad data';
                   5809:               return (\%hash, $string);
                   5810:           }
                   5811:       } else {
                   5812:           $string =~ s/^(.*?)=//;
1.267     albertel 5813: 	  $key=&unescape($1);
1.265     albertel 5814:       }
                   5815:       $string =~ s/^=//;
                   5816: 
                   5817:       #value
                   5818:       my $value='';
                   5819:       if($string =~ /^__HASH_REF__/) {
                   5820:           ($value, $string)=&str2hashref($string);
                   5821:           if(defined($value->{'error'})) {
                   5822:               $hash{'error'}='Bad data';
                   5823:               return (\%hash, $string);
                   5824:           }
                   5825:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5826:           ($value, $string)=&str2arrayref($string);
                   5827:           if($value->[0] eq 'Array reference error') {
                   5828:               $hash{'error'}='Bad data';
                   5829:               return (\%hash, $string);
                   5830:           }
                   5831:       } else {
                   5832: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5833:       }
                   5834:       $string =~ s/^&//;
                   5835: 
                   5836:       $hash{$key}=$value;
1.204     albertel 5837:   }
1.265     albertel 5838: 
                   5839:   $string =~ s/^__END_HASH_REF__//;
                   5840: 
                   5841:   return (\%hash, $string);
1.204     albertel 5842: }
                   5843: 
                   5844: sub str2array {
1.265     albertel 5845:     my ($string)=@_;
                   5846:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5847:     return @$array;
                   5848: }
                   5849: 
                   5850: sub str2arrayref {
1.204     albertel 5851:   my ($string) = @_;
1.265     albertel 5852:   my @array;
                   5853: 
                   5854:   if($string !~ /^__ARRAY_REF__/) {
                   5855:       if (! ($string eq '' || !defined($string))) {
                   5856: 	  $array[0]='Array reference error';
                   5857:       }
                   5858:       return (\@array, $string);
                   5859:   }
                   5860: 
                   5861:   $string =~ s/^__ARRAY_REF__//;
                   5862: 
                   5863:   while($string !~ /^__END_ARRAY_REF__/) {
                   5864:       my $value='';
                   5865:       if($string =~ /^__HASH_REF__/) {
                   5866:           ($value, $string)=&str2hashref($string);
                   5867:           if(defined($value->{'error'})) {
                   5868:               $array[0] ='Array reference error';
                   5869:               return (\@array, $string);
                   5870:           }
                   5871:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5872:           ($value, $string)=&str2arrayref($string);
                   5873:           if($value->[0] eq 'Array reference error') {
                   5874:               $array[0] ='Array reference error';
                   5875:               return (\@array, $string);
                   5876:           }
                   5877:       } else {
                   5878: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5879:       }
                   5880:       $string =~ s/^&//;
                   5881: 
                   5882:       push(@array, $value);
1.191     harris41 5883:   }
1.265     albertel 5884: 
                   5885:   $string =~ s/^__END_ARRAY_REF__//;
                   5886: 
                   5887:   return (\@array, $string);
1.168     albertel 5888: }
                   5889: 
1.167     albertel 5890: # -------------------------------------------------------------------Temp Store
                   5891: 
1.168     albertel 5892: sub tmpreset {
                   5893:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5894:   if (!$symb) {
                   5895:     $symb=&symbread();
1.620     albertel 5896:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5897:   }
                   5898:   $symb=escape($symb);
                   5899: 
1.620     albertel 5900:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5901:   $namespace=~s/\//\_/g;
                   5902:   $namespace=~s/\W//g;
                   5903: 
1.620     albertel 5904:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5905:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5906:   if ($domain eq 'public' && $stuname eq 'public') {
                   5907:       $stuname=$ENV{'REMOTE_ADDR'};
                   5908:   }
1.1117    foxr     5909:   my $path=LONCAPA::tempdir();
1.168     albertel 5910:   my %hash;
                   5911:   if (tie(%hash,'GDBM_File',
                   5912: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5913: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5914:     foreach my $key (keys(%hash)) {
1.180     albertel 5915:       if ($key=~ /:$symb/) {
1.168     albertel 5916: 	delete($hash{$key});
                   5917:       }
                   5918:     }
                   5919:   }
                   5920: }
                   5921: 
1.167     albertel 5922: sub tmpstore {
1.168     albertel 5923:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5924: 
                   5925:   if (!$symb) {
                   5926:     $symb=&symbread();
1.620     albertel 5927:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5928:   }
                   5929:   $symb=escape($symb);
                   5930: 
                   5931:   if (!$namespace) {
                   5932:     # I don't think we would ever want to store this for a course.
                   5933:     # it seems this will only be used if we don't have a course.
1.620     albertel 5934:     #$namespace=$env{'request.course.id'};
1.168     albertel 5935:     #if (!$namespace) {
1.620     albertel 5936:       $namespace=$env{'request.state'};
1.168     albertel 5937:     #}
                   5938:   }
                   5939:   $namespace=~s/\//\_/g;
                   5940:   $namespace=~s/\W//g;
1.620     albertel 5941:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5942:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5943:   if ($domain eq 'public' && $stuname eq 'public') {
                   5944:       $stuname=$ENV{'REMOTE_ADDR'};
                   5945:   }
1.168     albertel 5946:   my $now=time;
                   5947:   my %hash;
1.1117    foxr     5948:   my $path=LONCAPA::tempdir();
1.168     albertel 5949:   if (tie(%hash,'GDBM_File',
                   5950: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5951: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5952:     $hash{"version:$symb"}++;
                   5953:     my $version=$hash{"version:$symb"};
                   5954:     my $allkeys=''; 
                   5955:     foreach my $key (keys(%$storehash)) {
                   5956:       $allkeys.=$key.':';
1.591     albertel 5957:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5958:     }
                   5959:     $hash{"$version:$symb:timestamp"}=$now;
                   5960:     $allkeys.='timestamp';
                   5961:     $hash{"$version:keys:$symb"}=$allkeys;
                   5962:     if (untie(%hash)) {
                   5963:       return 'ok';
                   5964:     } else {
                   5965:       return "error:$!";
                   5966:     }
                   5967:   } else {
                   5968:     return "error:$!";
                   5969:   }
                   5970: }
1.167     albertel 5971: 
1.168     albertel 5972: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5973: 
1.168     albertel 5974: sub tmprestore {
                   5975:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5976: 
1.168     albertel 5977:   if (!$symb) {
                   5978:     $symb=&symbread();
1.620     albertel 5979:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5980:   }
                   5981:   $symb=escape($symb);
                   5982: 
1.620     albertel 5983:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5984: 
1.620     albertel 5985:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5986:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5987:   if ($domain eq 'public' && $stuname eq 'public') {
                   5988:       $stuname=$ENV{'REMOTE_ADDR'};
                   5989:   }
1.168     albertel 5990:   my %returnhash;
                   5991:   $namespace=~s/\//\_/g;
                   5992:   $namespace=~s/\W//g;
                   5993:   my %hash;
1.1117    foxr     5994:   my $path=LONCAPA::tempdir();
1.168     albertel 5995:   if (tie(%hash,'GDBM_File',
                   5996: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5997: 	  &GDBM_READER(),0640)) {
1.168     albertel 5998:     my $version=$hash{"version:$symb"};
                   5999:     $returnhash{'version'}=$version;
                   6000:     my $scope;
                   6001:     for ($scope=1;$scope<=$version;$scope++) {
                   6002:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6003:       my @keys=split(/:/,$vkeys);
                   6004:       my $key;
                   6005:       $returnhash{"$scope:keys"}=$vkeys;
                   6006:       foreach $key (@keys) {
1.591     albertel 6007: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6008: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6009:       }
                   6010:     }
1.168     albertel 6011:     if (!(untie(%hash))) {
                   6012:       return "error:$!";
                   6013:     }
                   6014:   } else {
                   6015:     return "error:$!";
                   6016:   }
                   6017:   return %returnhash;
1.167     albertel 6018: }
                   6019: 
1.9       www      6020: # ----------------------------------------------------------------------- Store
                   6021: 
                   6022: sub store {
1.1172.2.64  raeburn  6023:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6024:     my $home='';
                   6025: 
1.168     albertel 6026:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6027: 
1.213     www      6028:     $symb=&symbclean($symb);
1.122     albertel 6029:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6030: 
1.620     albertel 6031:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6032:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6033: 
                   6034:     &devalidate($symb,$stuname,$domain);
1.109     www      6035: 
                   6036:     $symb=escape($symb);
1.187     www      6037:     if (!$namespace) { 
1.620     albertel 6038:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6039:           return ''; 
                   6040:        } 
                   6041:     }
1.620     albertel 6042:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6043: 
                   6044:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   6045:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6046: 
1.12      www      6047:     my $namevalue='';
1.800     albertel 6048:     foreach my $key (keys(%$storehash)) {
                   6049:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6050:     }
1.12      www      6051:     $namevalue=~s/\&$//;
1.187     www      6052:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  6053:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6054: }
                   6055: 
1.47      www      6056: # -------------------------------------------------------------- Critical Store
                   6057: 
                   6058: sub cstore {
1.1172.2.64  raeburn  6059:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6060:     my $home='';
                   6061: 
1.168     albertel 6062:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6063: 
1.213     www      6064:     $symb=&symbclean($symb);
1.122     albertel 6065:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6066: 
1.620     albertel 6067:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6068:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6069: 
                   6070:     &devalidate($symb,$stuname,$domain);
1.109     www      6071: 
                   6072:     $symb=escape($symb);
1.187     www      6073:     if (!$namespace) { 
1.620     albertel 6074:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6075:           return ''; 
                   6076:        } 
                   6077:     }
1.620     albertel 6078:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6079: 
                   6080:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   6081:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6082: 
1.47      www      6083:     my $namevalue='';
1.800     albertel 6084:     foreach my $key (keys(%$storehash)) {
                   6085:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6086:     }
1.47      www      6087:     $namevalue=~s/\&$//;
1.187     www      6088:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6089:     return critical
1.1172.2.64  raeburn  6090:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6091: }
                   6092: 
1.9       www      6093: # --------------------------------------------------------------------- Restore
                   6094: 
                   6095: sub restore {
1.124     www      6096:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6097:     my $home='';
                   6098: 
1.168     albertel 6099:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6100: 
1.122     albertel 6101:     if (!$symb) {
1.1172.2.26  raeburn  6102:         return if ($namespace eq 'courserequests');
                   6103:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6104:     } else {
1.1172.2.26  raeburn  6105:         unless ($namespace eq 'courserequests') {
                   6106:             $symb=&escape(&symbclean($symb));
                   6107:         }
1.122     albertel 6108:     }
1.188     www      6109:     if (!$namespace) { 
1.620     albertel 6110:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6111:           return ''; 
                   6112:        } 
                   6113:     }
1.620     albertel 6114:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6115:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6116:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6117:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6118: 
1.12      www      6119:     my %returnhash=();
1.800     albertel 6120:     foreach my $line (split(/\&/,$answer)) {
                   6121: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6122:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6123:     }
1.75      www      6124:     my $version;
                   6125:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6126:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6127:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6128:        }
1.75      www      6129:     }
1.13      www      6130:     return %returnhash;
1.34      www      6131: }
                   6132: 
                   6133: # ---------------------------------------------------------- Course Description
1.1118    foxr     6134: #
                   6135: #  
1.34      www      6136: 
                   6137: sub coursedescription {
1.731     albertel 6138:     my ($courseid,$args)=@_;
1.34      www      6139:     $courseid=~s/^\///;
1.49      www      6140:     $courseid=~s/\_/\//g;
1.34      www      6141:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6142:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6143:     my $normalid=$cdomain.'_'.$cnum;
                   6144:     # need to always cache even if we get errors otherwise we keep 
                   6145:     # trying and trying and trying to get the course description.
                   6146:     my %envhash=();
                   6147:     my %returnhash=();
1.731     albertel 6148:     
                   6149:     my $expiretime=600;
                   6150:     if ($env{'request.course.id'} eq $normalid) {
                   6151: 	$expiretime=120;
                   6152:     }
                   6153: 
                   6154:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6155:     if (!$args->{'freshen_cache'}
                   6156: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6157: 	foreach my $key (keys(%env)) {
                   6158: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6159: 	    my ($setting) = $1;
                   6160: 	    $returnhash{$setting} = $env{$key};
                   6161: 	}
                   6162: 	return %returnhash;
                   6163:     }
                   6164: 
1.1118    foxr     6165:     # get the data again
                   6166: 
1.731     albertel 6167:     if (!$args->{'one_time'}) {
                   6168: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6169:     }
1.811     albertel 6170: 
1.34      www      6171:     if ($chome ne 'no_host') {
1.302     albertel 6172:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6173:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6174: 	   my $username = $env{'user.name'}; # Defult username
                   6175: 	   if(defined $args->{'user'}) {
                   6176: 	       $username = $args->{'user'};
                   6177: 	   }
1.129     albertel 6178:            $returnhash{'home'}= $chome;
                   6179: 	   $returnhash{'domain'} = $cdomain;
                   6180: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6181:            if (!defined($returnhash{'type'})) {
                   6182:                $returnhash{'type'} = 'Course';
                   6183:            }
1.130     albertel 6184:            while (my ($name,$value) = each %returnhash) {
1.53      www      6185:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6186:            }
1.270     www      6187:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6188:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6189: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6190:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6191:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6192:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6193:        }
                   6194:     }
1.731     albertel 6195:     if (!$args->{'one_time'}) {
1.949     raeburn  6196: 	&appenv(\%envhash);
1.731     albertel 6197:     }
1.302     albertel 6198:     return %returnhash;
1.461     www      6199: }
                   6200: 
1.1080    raeburn  6201: sub update_released_required {
                   6202:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6203:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6204:         $cid = $env{'request.course.id'};
                   6205:         $cdom = $env{'course.'.$cid.'.domain'};
                   6206:         $cnum = $env{'course.'.$cid.'.num'};
                   6207:         $chome = $env{'course.'.$cid.'.home'};
                   6208:     }
                   6209:     if ($needsrelease) {
                   6210:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6211:         my $needsupdate;
                   6212:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6213:             $needsupdate = 1;
                   6214:         } else {
                   6215:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6216:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6217:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6218:                 $needsupdate = 1;
                   6219:             }
                   6220:         }
                   6221:         if ($needsupdate) {
                   6222:             my %needshash = (
                   6223:                              'internal.releaserequired' => $needsrelease,
                   6224:                             );
                   6225:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6226:             if ($putresult eq 'ok') {
                   6227:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6228:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6229:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6230:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6231:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6232:                 }
                   6233:             }
                   6234:         }
                   6235:     }
                   6236:     return;
                   6237: }
                   6238: 
1.461     www      6239: # -------------------------------------------------See if a user is privileged
                   6240: 
                   6241: sub privileged {
1.1172.2.23  raeburn  6242:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6243:     my $now = time;
1.1172.2.23  raeburn  6244:     my $roles;
                   6245:     if (ref($possroles) eq 'ARRAY') {
                   6246:         $roles = $possroles;
                   6247:     } else {
                   6248:         $roles = ['dc','su'];
                   6249:     }
                   6250:     if (ref($possdomains) eq 'ARRAY') {
                   6251:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6252:         foreach my $dom (@{$possdomains}) {
                   6253:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6254:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6255:                 foreach my $role (@{$roles}) {
                   6256:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6257:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6258:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6259:                             return 1 unless (($end && $end < $now) ||
                   6260:                                              ($start && $start > $now));
                   6261:                         }
                   6262:                     }
                   6263:                 }
                   6264:             }
                   6265:         }
                   6266:     } else {
                   6267:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6268:         my $now = time;
1.1170    droeschl 6269: 
1.1172.2.58  raeburn  6270:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6271:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6272:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6273:                 return 1 unless ($tend && $tend < $now)
                   6274:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6275:             }
1.1172.2.23  raeburn  6276:         }
                   6277:     }
1.461     www      6278:     return 0;
1.9       www      6279: }
1.1       albertel 6280: 
1.1172.2.23  raeburn  6281: sub privileged_by_domain {
                   6282:     my ($domains,$roles) = @_;
                   6283:     my %privileged = ();
                   6284:     my $cachetime = 60*60*24;
                   6285:     my $now = time;
                   6286:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6287:         return %privileged;
                   6288:     }
                   6289:     foreach my $dom (@{$domains}) {
                   6290:         next if (ref($privileged{$dom}) eq 'HASH');
                   6291:         my $needroles;
                   6292:         foreach my $role (@{$roles}) {
                   6293:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6294:             if (defined($cached)) {
                   6295:                 if (ref($result) eq 'HASH') {
                   6296:                     $privileged{$dom}{$role} = $result;
                   6297:                 }
                   6298:             } else {
                   6299:                 $needroles = 1;
                   6300:             }
                   6301:         }
                   6302:         if ($needroles) {
                   6303:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6304:             $privileged{$dom} = {};
                   6305:             foreach my $server (keys(%dompersonnel)) {
                   6306:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6307:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6308:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6309:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6310:                         next if ($end && $end < $now);
                   6311:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6312:                             $dompersonnel{$server}{$item};
                   6313:                     }
                   6314:                 }
                   6315:             }
                   6316:             if (ref($privileged{$dom}) eq 'HASH') {
                   6317:                 foreach my $role (@{$roles}) {
                   6318:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6319:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6320:                     } else {
                   6321:                         my %hash = ();
                   6322:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6323:                     }
                   6324:                 }
                   6325:             }
                   6326:         }
                   6327:     }
                   6328:     return %privileged;
                   6329: }
                   6330: 
1.103     harris41 6331: # -------------------------------------------------------- Get user privileges
1.11      www      6332: 
                   6333: sub rolesinit {
1.1169    droeschl 6334:     my ($domain, $username) = @_;
                   6335:     my %userroles = ('user.login.time' => time);
                   6336:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6337: 
                   6338:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6339:     # also, blocking can be triggered by an activating timer
                   6340:     # it's saved in the user's %env.
                   6341:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6342:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6343:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6344:         %timerintchk, %timerintenv);
                   6345: 
1.1162    raeburn  6346:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6347:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6348:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6349:     }
1.1169    droeschl 6350: 
1.1162    raeburn  6351:     foreach my $key (keys(%timerinterval)) {
                   6352:         my ($cid,$rest) = split(/\0/,$key);
                   6353:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6354:     }
1.1169    droeschl 6355: 
1.11      www      6356:     my %allroles=();
1.1162    raeburn  6357:     my %allgroups=();
1.11      www      6358: 
1.1172.2.58  raeburn  6359:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6360:         my $role = $rolesdump{$area};
                   6361:         $area =~ s/\_\w\w$//;
                   6362: 
                   6363:         my ($trole, $tend, $tstart, $group_privs);
                   6364: 
                   6365:         if ($role =~ /^cr/) {
                   6366:         # Custom role, defined by a user 
                   6367:         # e.g., user.role.cr/msu/smith/mynewrole
                   6368:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6369:                 $trole = $1;
                   6370:                 ($tend, $tstart) = split('_', $2);
                   6371:             } else {
                   6372:                 $trole = $role;
                   6373:             }
                   6374:         } elsif ($role =~ m|^gr/|) {
                   6375:         # Role of member in a group, defined within a course/community
                   6376:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6377:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6378:             next if $tstart eq '-1';
                   6379:             ($trole, $group_privs) = split(/\//, $trole);
                   6380:             $group_privs = &unescape($group_privs);
                   6381:         } else {
                   6382:         # Just a normal role, defined in roles.tab
                   6383:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6384:         }
                   6385: 
                   6386:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6387:                  $username);
                   6388:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6389: 
                   6390:         # role expired or not available yet?
                   6391:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6392:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6393: 
                   6394:         next if $area eq '' or $trole eq '';
                   6395: 
                   6396:         my $spec = "$trole.$area";
                   6397:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6398: 
                   6399:         if ($trole =~ /^cr\//) {
                   6400:         # Custom role, defined by a user
                   6401:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6402:         } elsif ($trole eq 'gr') {
                   6403:         # Role of a member in a group, defined within a course/community
                   6404:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6405:             next;
                   6406:         } else {
                   6407:         # Normal role, defined in roles.tab
                   6408:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6409:         }
                   6410: 
                   6411:         my $cid = $tdomain.'_'.$trest;
                   6412:         unless ($firstaccchk{$cid}) {
                   6413:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6414:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6415:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6416:                         $coursetimerstarts{$cid}{$item}; 
                   6417:                 }
                   6418:             }
                   6419:             $firstaccchk{$cid} = 1;
                   6420:         }
                   6421:         unless ($timerintchk{$cid}) {
                   6422:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6423:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6424:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6425:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6426:                 }
1.12      www      6427:             }
1.1169    droeschl 6428:             $timerintchk{$cid} = 1;
1.191     harris41 6429:         }
1.11      www      6430:     }
1.1169    droeschl 6431: 
1.1172.2.91  raeburn  6432:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6433:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6434:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6435:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6436: 
1.1162    raeburn  6437:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6438: }
                   6439: 
1.567     raeburn  6440: sub set_arearole {
1.1172.2.19  raeburn  6441:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6442:     unless ($nolog) {
1.567     raeburn  6443: # log the associated role with the area
1.1172.2.19  raeburn  6444:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6445:     }
1.743     albertel 6446:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6447: }
                   6448: 
                   6449: sub custom_roleprivs {
                   6450:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6451:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6452:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6453:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6454:         my ($rdummy,$roledef)=
                   6455:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6456:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6457:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6458:             if (defined($syspriv)) {
1.1043    raeburn  6459:                 if ($trest =~ /^$match_community$/) {
                   6460:                     $syspriv =~ s/bre\&S//; 
                   6461:                 }
1.567     raeburn  6462:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6463:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6464:             }
                   6465:             if ($tdomain ne '') {
                   6466:                 if (defined($dompriv)) {
                   6467:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6468:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6469:                 }
                   6470:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6471:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6472:                         my $rolename = $1;
                   6473:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6474:                     }
1.567     raeburn  6475:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6476:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6477:                 }
                   6478:             }
                   6479:         }
                   6480:     }
                   6481: }
                   6482: 
1.1172.2.89  raeburn  6483: sub course_adhocrole_privs {
                   6484:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6485:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6486:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6487:         my (%currprivs,%storeprivs);
                   6488:         foreach my $item (split(/:/,$coursepriv)) {
                   6489:             my ($priv,$restrict) = split(/\&/,$item);
                   6490:             $currprivs{$priv} = $restrict;
                   6491:         }
                   6492:         my (%possadd,%possremove,%full);
                   6493:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6494:             my ($priv,$restrict)=split(/\&/,$item);
                   6495:             $full{$priv} = $restrict;
                   6496:         }
                   6497:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6498:              next if ($item eq '');
                   6499:              my ($rule,$rest) = split(/=/,$item);
                   6500:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6501:              foreach my $priv (split(/:/,$rest)) {
                   6502:                  if ($priv ne '') {
                   6503:                      if ($rule eq 'off') {
                   6504:                          $possremove{$priv} = 1;
                   6505:                      } else {
                   6506:                          $possadd{$priv} = 1;
                   6507:                      }
                   6508:                  }
                   6509:              }
                   6510:          }
                   6511:          foreach my $priv (sort(keys(%full))) {
                   6512:              if (exists($currprivs{$priv})) {
                   6513:                  unless (exists($possremove{$priv})) {
                   6514:                      $storeprivs{$priv} = $currprivs{$priv};
                   6515:                  }
                   6516:              } elsif (exists($possadd{$priv})) {
                   6517:                  $storeprivs{$priv} = $full{$priv};
                   6518:              }
                   6519:          }
                   6520:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6521:      }
                   6522:      return $coursepriv;
                   6523: }
                   6524: 
1.678     raeburn  6525: sub group_roleprivs {
                   6526:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6527:     my $access = 1;
                   6528:     my $now = time;
                   6529:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6530:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6531:     if ($access) {
1.811     albertel 6532:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6533:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6534:     }
                   6535: }
1.567     raeburn  6536: 
                   6537: sub standard_roleprivs {
                   6538:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6539:     if (defined($pr{$trole.':s'})) {
                   6540:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6541:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6542:     }
                   6543:     if ($tdomain ne '') {
                   6544:         if (defined($pr{$trole.':d'})) {
                   6545:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6546:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6547:         }
                   6548:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6549:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6550:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6551:         }
                   6552:     }
                   6553: }
                   6554: 
                   6555: sub set_userprivs {
1.1064    raeburn  6556:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6557:     my $author=0;
                   6558:     my $adv=0;
1.1172.2.91  raeburn  6559:     my $rar=0;
1.678     raeburn  6560:     my %grouproles = ();
                   6561:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6562:         my @groupkeys; 
1.1000    raeburn  6563:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6564:             push(@groupkeys,$role);
                   6565:         }
                   6566:         if (ref($groups_roles) eq 'HASH') {
                   6567:             foreach my $key (keys(%{$groups_roles})) {
                   6568:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6569:                     push(@groupkeys,$key);
                   6570:                 }
                   6571:             }
                   6572:         }
                   6573:         if (@groupkeys > 0) {
                   6574:             foreach my $role (@groupkeys) {
                   6575:                 my ($trole,$area,$sec,$extendedarea);
                   6576:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6577:                     $trole = $1;
                   6578:                     $area = $2;
                   6579:                     $sec = $3;
                   6580:                     $extendedarea = $area.$sec;
                   6581:                     if (exists($$allgroups{$area})) {
                   6582:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6583:                             my $spec = $trole.'.'.$extendedarea;
                   6584:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6585:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6586:                         }
1.678     raeburn  6587:                     }
                   6588:                 }
                   6589:             }
                   6590:         }
                   6591:     }
1.800     albertel 6592:     foreach my $group (keys(%grouproles)) {
                   6593:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6594:     }
1.800     albertel 6595:     foreach my $role (keys(%{$allroles})) {
                   6596:         my %thesepriv;
1.941     raeburn  6597:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6598:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6599:             if ($item ne '') {
                   6600:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6601:                 if ($restrictions eq '') {
                   6602:                     $thesepriv{$privilege}='F';
                   6603:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6604:                     $thesepriv{$privilege}.=$restrictions;
                   6605:                 }
                   6606:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6607:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6608:             }
                   6609:         }
                   6610:         my $thesestr='';
1.1104    raeburn  6611:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6612: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6613: 	}
                   6614:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6615:     }
1.1172.2.91  raeburn  6616:     return ($author,$adv,$rar);
1.567     raeburn  6617: }
                   6618: 
1.994     raeburn  6619: sub role_status {
1.1104    raeburn  6620:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6621:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6622:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6623:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6624:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6625:             $$where = '/'.$two;
1.994     raeburn  6626:             $$trolecode=$$role.'.'.$$where;
                   6627:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6628:             $$tstatus='is';
1.1104    raeburn  6629:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6630:                 $$tstatus='future';
1.1034    raeburn  6631:                 if ($$tstart<$now) {
                   6632:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6633:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6634:                             my (%allroles,%allgroups,$group_privs,
                   6635:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6636:                             my %userroles = (
                   6637:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6638:                             );
1.1064    raeburn  6639:                             @rolecodes = ('cm'); 
1.1002    raeburn  6640:                             my $spec=$$role.'.'.$$where;
                   6641:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6642:                             if ($$role =~ /^cr\//) {
                   6643:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6644:                                 push(@rolecodes,'cr');
1.1002    raeburn  6645:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6646:                                 push(@rolecodes,$$role);
1.1002    raeburn  6647:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6648:                                                     $env{'user.name'});
1.1064    raeburn  6649:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6650:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6651:                                 $group_privs = &unescape($group_privs);
                   6652:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6653:                                 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  6654:                                 &get_groups_roles($tdomain,$trest,
                   6655:                                                   \%course_roles,\@rolecodes,
                   6656:                                                   \%groups_roles);
1.1002    raeburn  6657:                             } else {
1.1064    raeburn  6658:                                 push(@rolecodes,$$role);
1.1002    raeburn  6659:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6660:                             }
1.1172.2.91  raeburn  6661:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6662:                                                                    \%groups_roles);
1.1064    raeburn  6663:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6664:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6665:                         }
                   6666:                     }
1.1034    raeburn  6667:                     $$tstatus = 'is';
1.1002    raeburn  6668:                 }
1.994     raeburn  6669:             }
                   6670:             if ($$tend) {
1.1104    raeburn  6671:                 if ($$tend<$update) {
1.994     raeburn  6672:                     $$tstatus='expired';
                   6673:                 } elsif ($$tend<$now) {
                   6674:                     $$tstatus='will_not';
                   6675:                 }
                   6676:             }
                   6677:         }
                   6678:     }
                   6679: }
                   6680: 
1.1104    raeburn  6681: sub get_groups_roles {
                   6682:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6683:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6684:                   (ref($rolecodes) eq 'ARRAY') && 
                   6685:                   (ref($groups_roles) eq 'HASH')); 
                   6686:     if (keys(%{$cdom_courseroles}) > 0) {
                   6687:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6688:         if ($cdom ne '' && $cnum ne '') {
                   6689:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6690:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6691:                     my $crsrole = $1;
                   6692:                     my $crssec = $2;
                   6693:                     if ($crsrole =~ /^cr/) {
                   6694:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6695:                             push(@{$rolecodes},'cr');
                   6696:                         }
                   6697:                     } else {
                   6698:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6699:                             push(@{$rolecodes},$crsrole);
                   6700:                         }
                   6701:                     }
                   6702:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6703:                     if ($crssec ne '') {
                   6704:                         $rolekey .= "/$crssec";
                   6705:                     }
                   6706:                     $rolekey .= './';
                   6707:                     $groups_roles->{$rolekey} = $rolecodes;
                   6708:                 }
                   6709:             }
                   6710:         }
                   6711:     }
                   6712:     return;
                   6713: }
                   6714: 
                   6715: sub delete_env_groupprivs {
                   6716:     my ($where,$courseroles,$possroles) = @_;
                   6717:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6718:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6719:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6720:         %{$courseroles->{$udom}} =
                   6721:             &get_my_roles('','','userroles',['active'],
                   6722:                           $possroles,[$udom],1);
                   6723:     }
                   6724:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6725:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6726:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6727:             my $area = '/'.$cdom.'/'.$cnum;
                   6728:             my $privkey = "user.priv.$crsrole.$area";
                   6729:             if ($crssec ne '') {
                   6730:                 $privkey .= '/'.$crssec;
                   6731:             }
                   6732:             $privkey .= ".$area/$group";
                   6733:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6734:         }
                   6735:     }
                   6736:     return;
                   6737: }
                   6738: 
1.994     raeburn  6739: sub check_adhoc_privs {
1.1172.2.86  raeburn  6740:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6741:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6742:     if ($sec) {
                   6743:         $cckey .= '/'.$sec;
                   6744:     }
1.1172.2.9  raeburn  6745:     my $setprivs;
1.994     raeburn  6746:     if ($env{$cckey}) {
                   6747:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6748:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6749:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6750:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6751:             $setprivs = 1;
1.994     raeburn  6752:         }
                   6753:     } else {
1.1172.2.87  raeburn  6754:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6755:         $setprivs = 1;
1.994     raeburn  6756:     }
1.1172.2.9  raeburn  6757:     return $setprivs;
1.994     raeburn  6758: }
                   6759: 
                   6760: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6761: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6762:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6763:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6764:     if ($sec ne '') {
                   6765:         $area .= '/'.$sec;
                   6766:     }
1.994     raeburn  6767:     my $spec = $role.'.'.$area;
                   6768:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6769:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6770:     my %rolehash = ();
1.1172.2.89  raeburn  6771:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6772:         my $rolename = $1;
1.1172.2.84  raeburn  6773:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6774:         my %domdef = &get_domain_defaults($dcdom);
                   6775:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6776:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6777:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6778:             }
                   6779:         }
1.1172.2.84  raeburn  6780:     } else {
                   6781:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6782:     }
1.1172.2.91  raeburn  6783:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6784:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6785:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6786:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6787:         &appenv( {'request.role'        => $spec,
                   6788:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6789:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6790:                  }
                   6791:                );
                   6792:         my $tadv=0;
                   6793:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6794:         &appenv({'request.role.adv'    => $tadv});
                   6795:     }
1.994     raeburn  6796: }
                   6797: 
1.12      www      6798: # --------------------------------------------------------------- get interface
                   6799: 
                   6800: sub get {
1.131     albertel 6801:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6802:    my $items='';
1.800     albertel 6803:    foreach my $item (@$storearr) {
                   6804:        $items.=&escape($item).'&';
1.191     harris41 6805:    }
1.12      www      6806:    $items=~s/\&$//;
1.620     albertel 6807:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6808:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6809:    my $uhome=&homeserver($uname,$udomain);
                   6810: 
1.133     albertel 6811:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6812:    my @pairs=split(/\&/,$rep);
1.273     albertel 6813:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6814:      return @pairs;
                   6815:    }
1.15      www      6816:    my %returnhash=();
1.42      www      6817:    my $i=0;
1.800     albertel 6818:    foreach my $item (@$storearr) {
                   6819:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6820:       $i++;
1.191     harris41 6821:    }
1.15      www      6822:    return %returnhash;
1.27      www      6823: }
                   6824: 
                   6825: # --------------------------------------------------------------- del interface
                   6826: 
                   6827: sub del {
1.133     albertel 6828:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6829:    my $items='';
1.800     albertel 6830:    foreach my $item (@$storearr) {
                   6831:        $items.=&escape($item).'&';
1.191     harris41 6832:    }
1.984     neumanie 6833: 
1.27      www      6834:    $items=~s/\&$//;
1.620     albertel 6835:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6836:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6837:    my $uhome=&homeserver($uname,$udomain);
                   6838:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6839: }
                   6840: 
                   6841: # -------------------------------------------------------------- dump interface
                   6842: 
1.1172.2.22  raeburn  6843: sub unserialize {
                   6844:     my ($rep, $escapedkeys) = @_;
                   6845: 
                   6846:     return {} if $rep =~ /^error/;
                   6847: 
                   6848:     my %returnhash=();
                   6849:     foreach my $item (split(/\&/,$rep)) {
                   6850:         my ($key, $value) = split(/=/, $item, 2);
                   6851:         $key = unescape($key) unless $escapedkeys;
                   6852:         next if $key =~ /^error: 2 /;
                   6853:         $returnhash{$key} = &thaw_unescape($value);
                   6854:     }
                   6855:     return \%returnhash;
                   6856: }
                   6857: 
                   6858: # see Lond::dump_with_regexp
                   6859: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6860: sub dump {
1.1172.2.22  raeburn  6861:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6862:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6863:     if (!$uname) { $uname=$env{'user.name'}; }
                   6864:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6865: 
1.1172.2.55  raeburn  6866:     if ($regexp) {
                   6867:         $regexp=&escape($regexp);
                   6868:     } else {
                   6869:         $regexp='.';
                   6870:     }
1.1172.2.22  raeburn  6871:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6872:         # user is hosted on this machine
1.1172.2.55  raeburn  6873:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6874:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6875:         return %{&unserialize($reply, $escapedkeys)};
                   6876:     }
1.1166    raeburn  6877:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6878:     my @pairs=split(/\&/,$rep);
                   6879:     my %returnhash=();
1.1098    foxr     6880:     if (!($rep =~ /^error/ )) {
                   6881: 	foreach my $item (@pairs) {
                   6882: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6883:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6884: 	    next if ($key =~ /^error: 2 /);
                   6885: 	    $returnhash{$key}=&thaw_unescape($value);
                   6886: 	}
1.755     albertel 6887:     }
                   6888:     return %returnhash;
1.407     www      6889: }
                   6890: 
1.1098    foxr     6891: 
1.717     albertel 6892: # --------------------------------------------------------- dumpstore interface
                   6893: 
                   6894: sub dumpstore {
                   6895:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6896:    # same as dump but keys must be escaped. They may contain colon separated
                   6897:    # lists of values that may themself contain colons (e.g. symbs).
                   6898:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6899: }
                   6900: 
1.407     www      6901: # -------------------------------------------------------------- keys interface
                   6902: 
                   6903: sub getkeys {
                   6904:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6905:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6906:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6907:    my $uhome=&homeserver($uname,$udomain);
                   6908:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6909:    my @keyarray=();
1.800     albertel 6910:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6911:       next if ($key =~ /^error: 2 /);
1.800     albertel 6912:       push(@keyarray,&unescape($key));
1.407     www      6913:    }
                   6914:    return @keyarray;
1.318     matthew  6915: }
                   6916: 
1.319     matthew  6917: # --------------------------------------------------------------- currentdump
                   6918: sub currentdump {
1.328     matthew  6919:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6920:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6921:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6922:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6923:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6924:    my $rep;
                   6925: 
                   6926:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6927:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6928:                    $courseid)));
                   6929:    } else {
                   6930:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6931:    }
                   6932: 
1.318     matthew  6933:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6934:    #
1.318     matthew  6935:    my %returnhash=();
1.319     matthew  6936:    #
1.1172.2.118.  .1(raebu 6937:20):    if ($rep eq 'unknown_cmd') {
1.319     matthew  6938:        # an old lond will not know currentdump
                   6939:        # Do a dump and make it look like a currentdump
1.822     albertel 6940:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6941:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6942:        my %hash = @tmp;
                   6943:        @tmp=();
1.424     matthew  6944:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6945:    } else {
                   6946:        my @pairs=split(/\&/,$rep);
1.800     albertel 6947:        foreach my $pair (@pairs) {
                   6948:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6949:            my ($symb,$param) = split(/:/,$key);
                   6950:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6951:                                                         &thaw_unescape($value);
1.319     matthew  6952:        }
1.191     harris41 6953:    }
1.12      www      6954:    return %returnhash;
1.424     matthew  6955: }
                   6956: 
                   6957: sub convert_dump_to_currentdump{
                   6958:     my %hash = %{shift()};
                   6959:     my %returnhash;
                   6960:     # Code ripped from lond, essentially.  The only difference
                   6961:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6962:     # we might run in to problems with parameter names =~ /^v\./
                   6963:     while (my ($key,$value) = each(%hash)) {
                   6964:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6965: 	$symb  = &unescape($symb);
                   6966: 	$param = &unescape($param);
1.424     matthew  6967:         next if ($v eq 'version' || $symb eq 'keys');
                   6968:         next if (exists($returnhash{$symb}) &&
                   6969:                  exists($returnhash{$symb}->{$param}) &&
                   6970:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6971:         $returnhash{$symb}->{$param}=$value;
                   6972:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6973:     }
                   6974:     #
                   6975:     # Remove all of the keys in the hashes which keep track of
                   6976:     # the version of the parameter.
                   6977:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6978:         # use a foreach because we are going to delete from the hash.
                   6979:         foreach my $key (keys(%$param_hash)) {
                   6980:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6981:         }
                   6982:     }
                   6983:     return \%returnhash;
1.12      www      6984: }
                   6985: 
1.627     albertel 6986: # ------------------------------------------------------ critical inc interface
                   6987: 
                   6988: sub cinc {
                   6989:     return &inc(@_,'critical');
                   6990: }
                   6991: 
1.449     matthew  6992: # --------------------------------------------------------------- inc interface
                   6993: 
                   6994: sub inc {
1.627     albertel 6995:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6996:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6997:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6998:     my $uhome=&homeserver($uname,$udomain);
                   6999:     my $items='';
                   7000:     if (! ref($store)) {
                   7001:         # got a single value, so use that instead
                   7002:         $items = &escape($store).'=&';
                   7003:     } elsif (ref($store) eq 'SCALAR') {
                   7004:         $items = &escape($$store).'=&';        
                   7005:     } elsif (ref($store) eq 'ARRAY') {
                   7006:         $items = join('=&',map {&escape($_);} @{$store});
                   7007:     } elsif (ref($store) eq 'HASH') {
                   7008:         while (my($key,$value) = each(%{$store})) {
                   7009:             $items.= &escape($key).'='.&escape($value).'&';
                   7010:         }
                   7011:     }
                   7012:     $items=~s/\&$//;
1.627     albertel 7013:     if ($critical) {
                   7014: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7015:     } else {
                   7016: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7017:     }
1.449     matthew  7018: }
                   7019: 
1.12      www      7020: # --------------------------------------------------------------- put interface
                   7021: 
                   7022: sub put {
1.134     albertel 7023:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7024:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7025:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7026:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7027:    my $items='';
1.800     albertel 7028:    foreach my $item (keys(%$storehash)) {
                   7029:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7030:    }
1.12      www      7031:    $items=~s/\&$//;
1.134     albertel 7032:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      7033: }
                   7034: 
1.631     albertel 7035: # ------------------------------------------------------------ newput interface
                   7036: 
                   7037: sub newput {
                   7038:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7039:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7040:    if (!$uname) { $uname=$env{'user.name'}; }
                   7041:    my $uhome=&homeserver($uname,$udomain);
                   7042:    my $items='';
                   7043:    foreach my $key (keys(%$storehash)) {
                   7044:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7045:    }
                   7046:    $items=~s/\&$//;
                   7047:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7048: }
                   7049: 
                   7050: # ---------------------------------------------------------  putstore interface
                   7051: 
1.524     raeburn  7052: sub putstore {
1.1172.2.59  raeburn  7053:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7054:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7055:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7056:    my $uhome=&homeserver($uname,$udomain);
                   7057:    my $items='';
1.715     albertel 7058:    foreach my $key (keys(%$storehash)) {
                   7059:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7060:    }
1.715     albertel 7061:    $items=~s/\&$//;
1.716     albertel 7062:    my $esc_symb=&escape($symb);
                   7063:    my $esc_v=&escape($version);
1.715     albertel 7064:    my $reply =
1.716     albertel 7065:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7066: 	      $uhome);
1.1172.2.59  raeburn  7067:    if (($tolog) && ($reply eq 'ok')) {
                   7068:        my $namevalue='';
                   7069:        foreach my $key (keys(%{$storehash})) {
                   7070:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7071:        }
                   7072:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   7073:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7074:                      '&version='.$esc_v.
                   7075:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7076:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7077:    }
1.715     albertel 7078:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7079:        # gfall back to way things use to be done
1.715     albertel 7080:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7081: 			    $uname);
1.524     raeburn  7082:    }
1.715     albertel 7083:    return $reply;
                   7084: }
                   7085: 
                   7086: sub old_putstore {
1.716     albertel 7087:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7088:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7089:     if (!$uname) { $uname=$env{'user.name'}; }
                   7090:     my $uhome=&homeserver($uname,$udomain);
                   7091:     my %newstorehash;
1.800     albertel 7092:     foreach my $item (keys(%$storehash)) {
                   7093: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7094: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7095:     }
                   7096:     my $items='';
                   7097:     my %allitems = ();
1.800     albertel 7098:     foreach my $item (keys(%newstorehash)) {
                   7099: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7100: 	    my $key = $1.':keys:'.$2;
                   7101: 	    $allitems{$key} .= $3.':';
                   7102: 	}
1.800     albertel 7103: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7104:     }
1.800     albertel 7105:     foreach my $item (keys(%allitems)) {
                   7106: 	$allitems{$item} =~ s/\:$//;
                   7107: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7108:     }
                   7109:     $items=~s/\&$//;
                   7110:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7111: }
                   7112: 
1.47      www      7113: # ------------------------------------------------------ critical put interface
                   7114: 
                   7115: sub cput {
1.134     albertel 7116:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7117:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7118:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7119:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7120:    my $items='';
1.800     albertel 7121:    foreach my $item (keys(%$storehash)) {
                   7122:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7123:    }
1.47      www      7124:    $items=~s/\&$//;
1.134     albertel 7125:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7126: }
                   7127: 
                   7128: # -------------------------------------------------------------- eget interface
                   7129: 
                   7130: sub eget {
1.133     albertel 7131:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7132:    my $items='';
1.800     albertel 7133:    foreach my $item (@$storearr) {
                   7134:        $items.=&escape($item).'&';
1.191     harris41 7135:    }
1.12      www      7136:    $items=~s/\&$//;
1.620     albertel 7137:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7138:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7139:    my $uhome=&homeserver($uname,$udomain);
                   7140:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7141:    my @pairs=split(/\&/,$rep);
                   7142:    my %returnhash=();
1.42      www      7143:    my $i=0;
1.800     albertel 7144:    foreach my $item (@$storearr) {
                   7145:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7146:       $i++;
1.191     harris41 7147:    }
1.12      www      7148:    return %returnhash;
                   7149: }
                   7150: 
1.667     albertel 7151: # ------------------------------------------------------------ tmpput interface
                   7152: sub tmpput {
1.802     raeburn  7153:     my ($storehash,$server,$context)=@_;
1.667     albertel 7154:     my $items='';
1.800     albertel 7155:     foreach my $item (keys(%$storehash)) {
                   7156: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7157:     }
                   7158:     $items=~s/\&$//;
1.802     raeburn  7159:     if (defined($context)) {
                   7160:         $items .= ':'.&escape($context);
                   7161:     }
1.667     albertel 7162:     return &reply("tmpput:$items",$server);
                   7163: }
                   7164: 
                   7165: # ------------------------------------------------------------ tmpget interface
                   7166: sub tmpget {
1.688     albertel 7167:     my ($token,$server)=@_;
                   7168:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7169:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7170:     my %returnhash;
1.1172.2.85  raeburn  7171:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7172:         return %returnhash;
                   7173:     }
1.667     albertel 7174:     foreach my $item (split(/\&/,$rep)) {
                   7175: 	my ($key,$value)=split(/=/,$item);
                   7176: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7177:     }
                   7178:     return %returnhash;
                   7179: }
                   7180: 
1.1113    raeburn  7181: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7182: sub tmpdel {
                   7183:     my ($token,$server)=@_;
                   7184:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7185:     return &reply("tmpdel:$token",$server);
                   7186: }
                   7187: 
1.1172.2.13  raeburn  7188: # ------------------------------------------------------------ get_timebased_id
                   7189: 
                   7190: sub get_timebased_id {
                   7191:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7192:         $maxtries) = @_;
                   7193:     my ($newid,$error,$dellock);
                   7194:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7195:         return ('','ok','invalid call to get suffix');
                   7196:     }
                   7197: 
                   7198: # set defaults for any optional args for which values were not supplied
                   7199:     if ($who eq '') {
                   7200:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7201:     }
                   7202:     if (!$locktries) {
                   7203:         $locktries = 3;
                   7204:     }
                   7205:     if (!$maxtries) {
                   7206:         $maxtries = 10;
                   7207:     }
                   7208: 
                   7209:     if (($cdom eq '') || ($cnum eq '')) {
                   7210:         if ($env{'request.course.id'}) {
                   7211:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7212:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7213:         }
                   7214:         if (($cdom eq '') || ($cnum eq '')) {
                   7215:             return ('','ok','call to get suffix not in course context');
                   7216:         }
                   7217:     }
                   7218: 
                   7219: # construct locking item
                   7220:     my $lockhash = {
                   7221:                       $prefix."\0".'locked_'.$keyid => $who,
                   7222:                    };
                   7223:     my $tries = 0;
                   7224: 
                   7225: # attempt to get lock on nohist_$namespace file
                   7226:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7227:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7228:         $tries ++;
                   7229:         sleep 1;
                   7230:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7231:     }
                   7232: 
                   7233: # attempt to get unique identifier, based on current timestamp
                   7234:     if ($gotlock eq 'ok') {
                   7235:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7236:         my $id = time;
                   7237:         $newid = $id;
1.1172.2.56  raeburn  7238:         if ($idtype eq 'addcode') {
                   7239:             $newid .= &sixnum_code();
                   7240:         }
1.1172.2.13  raeburn  7241:         my $idtries = 0;
                   7242:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7243:             if ($idtype eq 'concat') {
                   7244:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7245:             } elsif ($idtype eq 'addcode') {
                   7246:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7247:             } else {
                   7248:                 $newid ++;
                   7249:             }
                   7250:             $idtries ++;
                   7251:         }
                   7252:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7253:             my %new_item =  (
                   7254:                               $prefix."\0".$newid => $who,
                   7255:                             );
                   7256:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7257:                                                  $cdom,$cnum);
                   7258:             if ($putresult ne 'ok') {
                   7259:                 undef($newid);
                   7260:                 $error = 'error saving new item: '.$putresult;
                   7261:             }
                   7262:         } else {
1.1172.2.56  raeburn  7263:              undef($newid);
1.1172.2.13  raeburn  7264:              $error = ('error: no unique suffix available for the new item ');
                   7265:         }
                   7266: #  remove lock
                   7267:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7268:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7269:     } else {
                   7270:         $error = "error: could not obtain lockfile\n";
                   7271:         $dellock = 'ok';
1.1172.2.58  raeburn  7272:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7273:             $dellock = 'nolock';
                   7274:         }
1.1172.2.13  raeburn  7275:     }
                   7276:     return ($newid,$dellock,$error);
                   7277: }
                   7278: 
1.1172.2.56  raeburn  7279: sub sixnum_code {
                   7280:     my $code;
                   7281:     for (0..6) {
                   7282:         $code .= int( rand(9) );
                   7283:     }
                   7284:     return $code;
                   7285: }
                   7286: 
1.765     albertel 7287: # -------------------------------------------------- portfolio access checking
                   7288: 
                   7289: sub portfolio_access {
1.1172.2.77  raeburn  7290:     my ($requrl,$clientip) = @_;
1.765     albertel 7291:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7292:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7293:     if ($result) {
                   7294:         my %setters;
                   7295:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7296:             my ($startblock,$endblock) =
                   7297:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7298:             if ($startblock && $endblock) {
                   7299:                 return 'B';
                   7300:             }
                   7301:         } else {
                   7302:             my ($startblock,$endblock) =
                   7303:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7304:             if ($startblock && $endblock) {
                   7305:                 return 'B';
                   7306:             }
                   7307:         }
                   7308:     }
1.765     albertel 7309:     if ($result eq 'ok') {
1.766     albertel 7310:        return 'F';
1.765     albertel 7311:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7312:        return 'A';
1.765     albertel 7313:     }
1.766     albertel 7314:     return '';
1.765     albertel 7315: }
                   7316: 
                   7317: sub get_portfolio_access {
1.1172.2.77  raeburn  7318:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7319: 
                   7320:     if (!ref($access_hash)) {
                   7321: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7322: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7323: 						   $file_name);
                   7324: 	$access_hash = $access_controls{$file_name};
                   7325:     }
                   7326: 
1.1172.2.77  raeburn  7327:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7328:     my $now = time;
                   7329:     if (ref($access_hash) eq 'HASH') {
                   7330:         foreach my $key (keys(%{$access_hash})) {
                   7331:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7332:             if ($start > $now) {
                   7333:                 next;
                   7334:             }
                   7335:             if ($end && $end<$now) {
                   7336:                 next;
                   7337:             }
                   7338:             if ($scope eq 'public') {
                   7339:                 $public = $key;
                   7340:                 last;
                   7341:             } elsif ($scope eq 'guest') {
                   7342:                 $guest = $key;
                   7343:             } elsif ($scope eq 'domains') {
                   7344:                 push(@domains,$key);
                   7345:             } elsif ($scope eq 'users') {
                   7346:                 push(@users,$key);
                   7347:             } elsif ($scope eq 'course') {
                   7348:                 push(@courses,$key);
                   7349:             } elsif ($scope eq 'group') {
                   7350:                 push(@groups,$key);
1.1172.2.77  raeburn  7351:             } elsif ($scope eq 'ip') {
                   7352:                 push(@ips,$key);
1.765     albertel 7353:             }
                   7354:         }
                   7355:         if ($public) {
                   7356:             return 'ok';
1.1172.2.77  raeburn  7357:         } elsif (@ips > 0) {
                   7358:             my $allowed;
                   7359:             foreach my $ipkey (@ips) {
                   7360:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7361:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7362:                         $allowed = 1;
                   7363:                         last;
                   7364:                     }
                   7365:                 }
                   7366:             }
                   7367:             if ($allowed) {
                   7368:                 return 'ok';
                   7369:             }
1.765     albertel 7370:         }
                   7371:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7372:             if ($guest) {
                   7373:                 return $guest;
                   7374:             }
                   7375:         } else {
                   7376:             if (@domains > 0) {
                   7377:                 foreach my $domkey (@domains) {
                   7378:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7379:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7380:                             return 'ok';
                   7381:                         }
                   7382:                     }
                   7383:                 }
                   7384:             }
                   7385:             if (@users > 0) {
                   7386:                 foreach my $userkey (@users) {
1.865     raeburn  7387:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7388:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7389:                             if (ref($item) eq 'HASH') {
                   7390:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7391:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7392:                                     return 'ok';
                   7393:                                 }
                   7394:                             }
                   7395:                         }
                   7396:                     } 
1.765     albertel 7397:                 }
                   7398:             }
                   7399:             my %roleshash;
                   7400:             my @courses_and_groups = @courses;
                   7401:             push(@courses_and_groups,@groups); 
                   7402:             if (@courses_and_groups > 0) {
                   7403:                 my (%allgroups,%allroles); 
                   7404:                 my ($start,$end,$role,$sec,$group);
                   7405:                 foreach my $envkey (%env) {
1.1060    raeburn  7406:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7407:                         my $cid = $2.'_'.$3; 
                   7408:                         if ($1 eq 'gr') {
                   7409:                             $group = $4;
                   7410:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7411:                         } else {
                   7412:                             if ($4 eq '') {
                   7413:                                 $sec = 'none';
                   7414:                             } else {
                   7415:                                 $sec = $4;
                   7416:                             }
                   7417:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7418:                         }
1.811     albertel 7419:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7420:                         my $cid = $2.'_'.$3;
                   7421:                         if ($4 eq '') {
                   7422:                             $sec = 'none';
                   7423:                         } else {
                   7424:                             $sec = $4;
                   7425:                         }
                   7426:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7427:                     }
                   7428:                 }
                   7429:                 if (keys(%allroles) == 0) {
                   7430:                     return;
                   7431:                 }
                   7432:                 foreach my $key (@courses_and_groups) {
                   7433:                     my %content = %{$$access_hash{$key}};
                   7434:                     my $cnum = $content{'number'};
                   7435:                     my $cdom = $content{'domain'};
                   7436:                     my $cid = $cdom.'_'.$cnum;
                   7437:                     if (!exists($allroles{$cid})) {
                   7438:                         next;
                   7439:                     }    
                   7440:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7441:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7442:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7443:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7444:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7445:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7446:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7447:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7448:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7449:                                         if (grep/^all$/,@sections) {
                   7450:                                             return 'ok';
                   7451:                                         } else {
                   7452:                                             if (grep/^$sec$/,@sections) {
                   7453:                                                 return 'ok';
                   7454:                                             }
                   7455:                                         }
                   7456:                                     }
                   7457:                                 }
                   7458:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7459:                                     if (grep/^none$/,@groups) {
                   7460:                                         return 'ok';
                   7461:                                     }
                   7462:                                 } else {
                   7463:                                     if (grep/^all$/,@groups) {
                   7464:                                         return 'ok';
                   7465:                                     } 
                   7466:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7467:                                         if (grep/^$group$/,@groups) {
                   7468:                                             return 'ok';
                   7469:                                         }
                   7470:                                     }
                   7471:                                 } 
                   7472:                             }
                   7473:                         }
                   7474:                     }
                   7475:                 }
                   7476:             }
                   7477:             if ($guest) {
                   7478:                 return $guest;
                   7479:             }
                   7480:         }
                   7481:     }
                   7482:     return;
                   7483: }
                   7484: 
                   7485: sub course_group_datechecker {
                   7486:     my ($dates,$now,$status) = @_;
                   7487:     my ($start,$end) = split(/\./,$dates);
                   7488:     if (!$start && !$end) {
                   7489:         return 'ok';
                   7490:     }
                   7491:     if (grep/^active$/,@{$status}) {
                   7492:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7493:             return 'ok';
                   7494:         }
                   7495:     }
                   7496:     if (grep/^previous$/,@{$status}) {
                   7497:         if ($end > $now ) {
                   7498:             return 'ok';
                   7499:         }
                   7500:     }
                   7501:     if (grep/^future$/,@{$status}) {
                   7502:         if ($start > $now) {
                   7503:             return 'ok';
                   7504:         }
                   7505:     }
                   7506:     return; 
                   7507: }
                   7508: 
                   7509: sub parse_portfolio_url {
                   7510:     my ($url) = @_;
                   7511: 
                   7512:     my ($type,$udom,$unum,$group,$file_name);
                   7513:     
1.823     albertel 7514:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7515: 	$type = 1;
                   7516:         $udom = $1;
                   7517:         $unum = $2;
                   7518:         $file_name = $3;
1.823     albertel 7519:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7520: 	$type = 2;
                   7521:         $udom = $1;
                   7522:         $unum = $2;
                   7523:         $group = $3;
                   7524:         $file_name = $3.'/'.$4;
                   7525:     }
                   7526:     if (wantarray) {
                   7527: 	return ($type,$udom,$unum,$file_name,$group);
                   7528:     }
                   7529:     return $type;
                   7530: }
                   7531: 
                   7532: sub is_portfolio_url {
                   7533:     my ($url) = @_;
                   7534:     return scalar(&parse_portfolio_url($url));
                   7535: }
                   7536: 
1.798     raeburn  7537: sub is_portfolio_file {
                   7538:     my ($file) = @_;
1.820     raeburn  7539:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7540:         return 1;
                   7541:     }
                   7542:     return;
                   7543: }
                   7544: 
1.976     raeburn  7545: sub usertools_access {
1.1084    raeburn  7546:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7547:     my ($access,%tools);
                   7548:     if ($context eq '') {
                   7549:         $context = 'tools';
                   7550:     }
                   7551:     if ($context eq 'requestcourses') {
                   7552:         %tools = (
                   7553:                       official   => 1,
                   7554:                       unofficial => 1,
1.1006    raeburn  7555:                       community  => 1,
1.1172.2.37  raeburn  7556:                       textbook   => 1,
1.985     raeburn  7557:                  );
1.1172.2.9  raeburn  7558:     } elsif ($context eq 'requestauthor') {
                   7559:         %tools = (
                   7560:                       requestauthor => 1,
                   7561:                  );
1.985     raeburn  7562:     } else {
                   7563:         %tools = (
                   7564:                       aboutme   => 1,
                   7565:                       blog      => 1,
1.1172.2.6  raeburn  7566:                       webdav    => 1,
1.985     raeburn  7567:                       portfolio => 1,
                   7568:                  );
                   7569:     }
1.976     raeburn  7570:     return if (!defined($tools{$tool}));
                   7571: 
1.1172.2.35  raeburn  7572:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7573:         $udom = $env{'user.domain'};
                   7574:         $uname = $env{'user.name'};
                   7575:     }
                   7576: 
1.978     raeburn  7577:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7578:         if ($action ne 'reload') {
1.985     raeburn  7579:             if ($context eq 'requestcourses') {
                   7580:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7581:             } elsif ($context eq 'requestauthor') {
                   7582:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7583:             } else {
                   7584:                 return $env{'environment.availabletools.'.$tool};
                   7585:             }
                   7586:         }
1.976     raeburn  7587:     }
                   7588: 
1.1172.2.9  raeburn  7589:     my ($toolstatus,$inststatus,$envkey);
                   7590:     if ($context eq 'requestauthor') {
                   7591:         $envkey = $context;
                   7592:     } else {
                   7593:         $envkey = $context.'.'.$tool;
                   7594:     }
1.976     raeburn  7595: 
1.985     raeburn  7596:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7597:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7598:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7599:         $inststatus = $env{'environment.inststatus'};
                   7600:     } else {
1.1084    raeburn  7601:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7602:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7603:             $inststatus = $userenvref->{'inststatus'};
                   7604:         } else {
1.1172.2.9  raeburn  7605:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7606:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7607:             $inststatus = $userenv{'inststatus'};
                   7608:         }
1.976     raeburn  7609:     }
                   7610: 
                   7611:     if ($toolstatus ne '') {
                   7612:         if ($toolstatus) {
                   7613:             $access = 1;
                   7614:         } else {
                   7615:             $access = 0;
                   7616:         }
                   7617:         return $access;
                   7618:     }
                   7619: 
1.1084    raeburn  7620:     my ($is_adv,%domdef);
                   7621:     if (ref($is_advref) eq 'HASH') {
                   7622:         $is_adv = $is_advref->{'is_adv'};
                   7623:     } else {
                   7624:         $is_adv = &is_advanced_user($udom,$uname);
                   7625:     }
                   7626:     if (ref($domdefref) eq 'HASH') {
                   7627:         %domdef = %{$domdefref};
                   7628:     } else {
                   7629:         %domdef = &get_domain_defaults($udom);
                   7630:     }
1.976     raeburn  7631:     if (ref($domdef{$tool}) eq 'HASH') {
                   7632:         if ($is_adv) {
                   7633:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7634:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7635:                     $access = 1;
                   7636:                 } else {
                   7637:                     $access = 0;
                   7638:                 }
                   7639:                 return $access;
                   7640:             }
                   7641:         }
                   7642:         if ($inststatus ne '') {
                   7643:             my ($hasaccess,$hasnoaccess);
                   7644:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7645:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7646:                     if ($domdef{$tool}{$affiliation}) {
                   7647:                         $hasaccess = 1;
                   7648:                     } else {
                   7649:                         $hasnoaccess = 1;
                   7650:                     }
                   7651:                 }
                   7652:             }
                   7653:             if ($hasaccess || $hasnoaccess) {
                   7654:                 if ($hasaccess) {
                   7655:                     $access = 1;
                   7656:                 } elsif ($hasnoaccess) {
                   7657:                     $access = 0; 
                   7658:                 }
                   7659:                 return $access;
                   7660:             }
                   7661:         } else {
                   7662:             if ($domdef{$tool}{'default'} ne '') {
                   7663:                 if ($domdef{$tool}{'default'}) {
                   7664:                     $access = 1;
                   7665:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7666:                     $access = 0;
                   7667:                 }
                   7668:                 return $access;
                   7669:             }
                   7670:         }
                   7671:     } else {
1.1172.2.6  raeburn  7672:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7673:             $access = 1;
                   7674:         } else {
                   7675:             $access = 0;
                   7676:         }
1.976     raeburn  7677:         return $access;
                   7678:     }
                   7679: }
                   7680: 
1.1050    raeburn  7681: sub is_course_owner {
                   7682:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7683:     if (($udom eq '') || ($uname eq '')) {
                   7684:         $udom = $env{'user.domain'};
                   7685:         $uname = $env{'user.name'};
                   7686:     }
                   7687:     unless (($udom eq '') || ($uname eq '')) {
                   7688:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7689:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7690:                 return 1;
                   7691:             } else {
                   7692:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7693:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7694:                     return 1;
                   7695:                 }
                   7696:             }
                   7697:         }
                   7698:     }
                   7699:     return;
                   7700: }
                   7701: 
1.976     raeburn  7702: sub is_advanced_user {
                   7703:     my ($udom,$uname) = @_;
1.1085    raeburn  7704:     if ($udom ne '' && $uname ne '') {
                   7705:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7706:             if (wantarray) {
                   7707:                 return ($env{'user.adv'},$env{'user.author'});
                   7708:             } else {
                   7709:                 return $env{'user.adv'};
                   7710:             }
1.1085    raeburn  7711:         }
                   7712:     }
1.976     raeburn  7713:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7714:     my %allroles;
1.1128    raeburn  7715:     my ($is_adv,$is_author);
1.976     raeburn  7716:     foreach my $role (keys(%roleshash)) {
                   7717:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7718:         my $area = '/'.$tdomain.'/'.$trest;
                   7719:         if ($sec ne '') {
                   7720:             $area .= '/'.$sec;
                   7721:         }
                   7722:         if (($area ne '') && ($trole ne '')) {
                   7723:             my $spec=$trole.'.'.$area;
                   7724:             if ($trole =~ /^cr\//) {
                   7725:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7726:             } elsif ($trole ne 'gr') {
                   7727:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7728:             }
1.1128    raeburn  7729:             if ($trole eq 'au') {
                   7730:                 $is_author = 1;
                   7731:             }
1.976     raeburn  7732:         }
                   7733:     }
                   7734:     foreach my $role (keys(%allroles)) {
                   7735:         last if ($is_adv);
                   7736:         foreach my $item (split(/:/,$allroles{$role})) {
                   7737:             if ($item ne '') {
                   7738:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7739:                 if ($privilege eq 'adv') {
                   7740:                     $is_adv = 1;
                   7741:                     last;
                   7742:                 }
                   7743:             }
                   7744:         }
                   7745:     }
1.1128    raeburn  7746:     if (wantarray) {
                   7747:         return ($is_adv,$is_author);
                   7748:     }
1.976     raeburn  7749:     return $is_adv;
                   7750: }
1.798     raeburn  7751: 
1.1035    raeburn  7752: sub check_can_request {
1.1036    raeburn  7753:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7754:     my $canreq = 0;
                   7755:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7756:     my @options = ('approval','validate','autolimit');
                   7757:     my $optregex = join('|',@options);
                   7758:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7759:         foreach my $type (@{$types}) {
                   7760:             if (&usertools_access($env{'user.name'},
                   7761:                                   $env{'user.domain'},
                   7762:                                   $type,undef,'requestcourses')) {
                   7763:                 $canreq ++;
1.1036    raeburn  7764:                 if (ref($request_domains) eq 'HASH') {
                   7765:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7766:                 }
1.1035    raeburn  7767:                 if ($dom eq $env{'user.domain'}) {
                   7768:                     $can_request->{$type} = 1;
                   7769:                 }
                   7770:             }
                   7771:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7772:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7773:                 if (@curr > 0) {
1.1036    raeburn  7774:                     foreach my $item (@curr) {
                   7775:                         if (ref($request_domains) eq 'HASH') {
                   7776:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7777:                             if ($otherdom ne '') {
                   7778:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7779:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7780:                                         push(@{$request_domains->{$type}},$otherdom);
                   7781:                                     }
                   7782:                                 } else {
                   7783:                                     push(@{$request_domains->{$type}},$otherdom);
                   7784:                                 }
                   7785:                             }
                   7786:                         }
                   7787:                     }
                   7788:                     unless($dom eq $env{'user.domain'}) {
                   7789:                         $canreq ++;
1.1035    raeburn  7790:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7791:                             $can_request->{$type} = 1;
                   7792:                         }
                   7793:                     }
                   7794:                 }
                   7795:             }
                   7796:         }
                   7797:     }
                   7798:     return $canreq;
                   7799: }
                   7800: 
1.341     www      7801: # ---------------------------------------------- Custom access rule evaluation
                   7802: 
                   7803: sub customaccess {
                   7804:     my ($priv,$uri)=@_;
1.807     albertel 7805:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7806:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7807:     $udom = &LONCAPA::clean_domain($udom);
                   7808:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7809:     my $access=0;
1.800     albertel 7810:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7811: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7812: 	if ($type eq 'user') {
                   7813: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7814: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7815: 		if ($tdom) {
                   7816: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7817: 		}
1.896     albertel 7818: 		if ($tuname) {
                   7819: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7820: 		}
                   7821: 		$access=($effect eq 'allow');
                   7822: 		last;
                   7823: 	    }
                   7824: 	} else {
                   7825: 	    if ($role) {
                   7826: 		if ($role ne $urole) { next; }
                   7827: 	    }
                   7828: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7829: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7830: 		if ($tdom) {
                   7831: 		    if ($tdom ne $udom) { next; }
                   7832: 		}
                   7833: 		if ($tcrs) {
                   7834: 		    if ($tcrs ne $ucrs) { next; }
                   7835: 		}
                   7836: 		if ($tsec) {
                   7837: 		    if ($tsec ne $usec) { next; }
                   7838: 		}
                   7839: 		$access=($effect eq 'allow');
                   7840: 		last;
                   7841: 	    }
                   7842: 	    if ($realm eq '' && $role eq '') {
                   7843: 		$access=($effect eq 'allow');
                   7844: 	    }
1.402     bowersj2 7845: 	}
1.341     www      7846:     }
                   7847:     return $access;
                   7848: }
                   7849: 
1.103     harris41 7850: # ------------------------------------------------- Check for a user privilege
1.12      www      7851: 
                   7852: sub allowed {
1.1172.2.118.  .8(raebu 7853:20):     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
1.705     albertel 7854:     my $ver_orguri=$uri;
1.439     www      7855:     $uri=&deversion($uri);
1.152     www      7856:     my $orguri=$uri;
1.52      www      7857:     $uri=&declutter($uri);
1.809     raeburn  7858: 
1.810     raeburn  7859:     if ($priv eq 'evb') {
                   7860: # Evade communication block restrictions for specified role in a course
                   7861:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7862:             return $1;
                   7863:         } else {
                   7864:             return;
                   7865:         }
                   7866:     }
                   7867: 
1.620     albertel 7868:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7869: # Free bre access to adm and meta resources
1.1172.2.118.  .1(raebu 7870:20):     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
1.769     albertel 7871: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7872: 	&& ($priv eq 'bre')) {
1.14      www      7873: 	return 'F';
1.159     www      7874:     }
                   7875: 
1.545     banghart 7876: # Free bre access to user's own portfolio contents
1.714     raeburn  7877:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7878:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7879: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7880:         my %setters;
                   7881:         my ($startblock,$endblock) = 
                   7882:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7883:         if ($startblock && $endblock) {
                   7884:             return 'B';
                   7885:         } else {
                   7886:             return 'F';
                   7887:         }
1.545     banghart 7888:     }
                   7889: 
1.762     raeburn  7890: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7891:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7892:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7893:         if (exists($env{'request.course.id'})) {
                   7894:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7895:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7896:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7897:                 my $courseprivid=$env{'request.course.id'};
                   7898:                 $courseprivid=~s/\_/\//;
                   7899:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7900:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7901:                     return $1; 
1.762     raeburn  7902:                 } else {
                   7903:                     if ($env{'request.course.sec'}) {
                   7904:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7905:                     }
                   7906:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7907:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7908:                         return $2;
                   7909:                     }
1.714     raeburn  7910:                 }
                   7911:             }
                   7912:         }
                   7913:     }
                   7914: 
1.159     www      7915: # Free bre to public access
                   7916: 
                   7917:     if ($priv eq 'bre') {
1.238     www      7918:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7919: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7920:            return 'F'; 
                   7921:         }
1.238     www      7922:         if ($copyright eq 'priv') {
                   7923:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7924: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7925: 		return '';
                   7926:             }
                   7927:         }
                   7928:         if ($copyright eq 'domain') {
                   7929:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7930: 	    unless (($env{'user.domain'} eq $1) ||
                   7931:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7932: 		return '';
                   7933:             }
1.262     matthew  7934:         }
1.620     albertel 7935:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7936:             # Library role, so allow browsing of resources in this domain.
                   7937:             return 'F';
1.238     www      7938:         }
1.341     www      7939:         if ($copyright eq 'custom') {
                   7940: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7941:         }
1.14      www      7942:     }
1.264     matthew  7943:     # Domain coordinator is trying to create a course
1.620     albertel 7944:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7945:         # uri is the requested domain in this case.
                   7946:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7947:         # a role of dc for the domain in question.
1.620     albertel 7948:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7949:     }
1.29      www      7950: 
1.52      www      7951:     my $thisallowed='';
                   7952:     my $statecond=0;
                   7953:     my $courseprivid='';
                   7954: 
1.1039    raeburn  7955:     my $ownaccess;
1.1043    raeburn  7956:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7957:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7958:         if ($uri eq '') {
                   7959:             $ownaccess = 1;
                   7960:         } else {
                   7961:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7962:                 my $udom = $env{'user.domain'};
                   7963:                 my $uname = $env{'user.name'};
                   7964:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7965:                     $ownaccess = 1;
1.1040    raeburn  7966:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7967:                     unless ($uri =~ m{\.\./}) {
                   7968:                         $ownaccess = 1;
                   7969:                     }
                   7970:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7971:                     my $now = time;
                   7972:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7973:                         my $adom = $1;
                   7974:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7975:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7976:                                 my ($start,$end) = split('.',$env{$key});
                   7977:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7978:                                     $ownaccess = 1;
                   7979:                                     last;
                   7980:                                 }
                   7981:                             }
                   7982:                         }
                   7983:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7984:                         my $adom = $1;
                   7985:                         my $aname = $2;
1.1042    raeburn  7986:                         foreach my $role ('ca','aa') { 
                   7987:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7988:                                 my ($start,$end) =
                   7989:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7990:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7991:                                     $ownaccess = 1;
                   7992:                                     last;
                   7993:                                 }
1.1039    raeburn  7994:                             }
                   7995:                         }
                   7996:                     }
                   7997:                 }
                   7998:             }
                   7999:         }
                   8000:     }
                   8001: 
1.52      www      8002: # Course
                   8003: 
1.620     albertel 8004:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8005:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8006:             $thisallowed.=$1;
                   8007:         }
1.52      www      8008:     }
1.29      www      8009: 
1.52      www      8010: # Domain
                   8011: 
1.620     albertel 8012:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8013:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8014:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8015:             $thisallowed.=$1;
                   8016:         }
1.12      www      8017:     }
1.52      www      8018: 
1.1141    raeburn  8019: # User who is not author or co-author might still be able to edit
                   8020: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8021:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8022:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8023:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8024:             $thisallowed.=$1;
                   8025:         }
                   8026:     }
                   8027: 
1.52      www      8028: # Course: uri itself is a course
1.66      www      8029:     my $courseuri=$uri;
                   8030:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8031:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8032: 
1.620     albertel 8033:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8034:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  8035:         if ($priv eq 'mip') {
                   8036:             my $rem = $1;
                   8037:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8038:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8039:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8040:                 if ($cdom ne '') {
                   8041:                     my %passwdconf = &get_passwdconf($cdom);
                   8042:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8043:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8044:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8045:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8046:                                 unless (@inststatuses) {
                   8047:                                     @inststatuses = ('default');
                   8048:                                 }
                   8049:                                 foreach my $status (@inststatuses) {
                   8050:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8051:                                         $thisallowed.=$rem;
                   8052:                                     }
                   8053:                                 }
                   8054:                             }
                   8055:                         }
                   8056:                     }
                   8057:                 }
                   8058:             }
                   8059:         } else {
                   8060:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8061:                 $thisallowed.=$1;
                   8062:             }
1.1039    raeburn  8063:         }
1.12      www      8064:     }
1.29      www      8065: 
1.665     albertel 8066: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8067: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8068:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8069: 	$thisallowed='';
1.671     raeburn  8070:         my ($match)=&is_on_map($uri);
                   8071:         if ($match) {
                   8072:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8073:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  8074:                 my $value = $1;
                   8075:                 if ($noblockcheck) {
                   8076:                     $thisallowed.=$value;
1.1162    raeburn  8077:                 } else {
1.1172.2.118.  .8(raebu 8078:20):                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8079:                     if (@blockers > 0) {
                   8080:                         $thisallowed = 'B';
                   8081:                     } else {
                   8082:                         $thisallowed.=$value;
                   8083:                     }
1.1162    raeburn  8084:                 }
1.671     raeburn  8085:             }
                   8086:         } else {
1.705     albertel 8087:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8088:             if ($refuri) {
                   8089:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8090:                     $thisallowed='F';
1.671     raeburn  8091:                 } else {
                   8092:                     $refuri=&declutter($refuri);
                   8093:                     my ($match) = &is_on_map($refuri);
                   8094:                     if ($match) {
1.1172.2.65  raeburn  8095:                         if ($noblockcheck) {
1.1162    raeburn  8096:                             $thisallowed='F';
1.1172.2.65  raeburn  8097:                         } else {
1.1172.2.118.  .8(raebu 8098:20):                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8099:                             if (@blockers > 0) {
                   8100:                                 $thisallowed = 'B';
                   8101:                             } else {
                   8102:                                 $thisallowed='F';
                   8103:                             }
1.1162    raeburn  8104:                         }
1.671     raeburn  8105:                     }
1.669     raeburn  8106:                 }
1.671     raeburn  8107:             }
                   8108:         }
1.314     www      8109:     }
1.492     albertel 8110: 
1.766     albertel 8111:     if ($priv eq 'bre'
                   8112: 	&& $thisallowed ne 'F' 
                   8113: 	&& $thisallowed ne '2'
                   8114: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8115: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8116:     }
1.1172.2.118.  .8(raebu 8117:20): 
1.52      www      8118: # Full access at system, domain or course-wide level? Exit.
1.29      www      8119:     if ($thisallowed=~/F/) {
                   8120: 	return 'F';
                   8121:     }
                   8122: 
1.52      www      8123: # If this is generating or modifying users, exit with special codes
1.29      www      8124: 
1.643     www      8125:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8126: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8127: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8128: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8129: 	    unless ($auname) { return $thisallowed; }
                   8130: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8131: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8132: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8133: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8134: 	}
1.52      www      8135: 	return $thisallowed;
                   8136:     }
                   8137: #
1.103     harris41 8138: # Gathered so far: system, domain and course wide privileges
1.52      www      8139: #
                   8140: # Course: See if uri or referer is an individual resource that is part of 
                   8141: # the course
                   8142: 
1.620     albertel 8143:     if ($env{'request.course.id'}) {
1.232     www      8144: 
1.1172.2.115  raeburn  8145: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8146: 
                   8147:         if ($priv eq 'mip') {
                   8148:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8149:                 return $thisallowed;
                   8150:             } else {
                   8151:                 return '';
                   8152:             }
                   8153:         }
                   8154: 
1.620     albertel 8155:        $courseprivid=$env{'request.course.id'};
                   8156:        if ($env{'request.course.sec'}) {
                   8157:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8158:        }
                   8159:        $courseprivid=~s/\_/\//;
                   8160:        my $checkreferer=1;
1.232     www      8161:        my ($match,$cond)=&is_on_map($uri);
                   8162:        if ($match) {
                   8163:            $statecond=$cond;
1.620     albertel 8164:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8165:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8166:                my $value = $1;
                   8167:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  8168:                    if ($noblockcheck) {
1.1162    raeburn  8169:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8170:                    } else {
1.1172.2.118.  .8(raebu 8171:20):                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8172:                        if (@blockers > 0) {
                   8173:                            $thisallowed = 'B';
                   8174:                        } else {
                   8175:                            $thisallowed.=$value;
                   8176:                        }
1.1162    raeburn  8177:                    }
                   8178:                } else {
                   8179:                    $thisallowed.=$value;
                   8180:                }
1.52      www      8181:                $checkreferer=0;
                   8182:            }
1.29      www      8183:        }
1.1172.2.118.  .8(raebu 8184:20): 
1.148     www      8185:        if ($checkreferer) {
1.620     albertel 8186: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8187:             unless ($refuri) {
1.800     albertel 8188:                 foreach my $key (keys(%env)) {
                   8189: 		    if ($key=~/^httpref\..*\*/) {
                   8190: 			my $pattern=$key;
1.156     www      8191:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8192:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8193:                         $pattern=~s/\//\\\//g;
1.152     www      8194:                         if ($orguri=~/$pattern/) {
1.800     albertel 8195: 			    $refuri=$env{$key};
1.148     www      8196:                         }
                   8197:                     }
1.191     harris41 8198:                 }
1.148     www      8199:             }
1.232     www      8200: 
1.148     www      8201:          if ($refuri) { 
1.152     www      8202: 	  $refuri=&declutter($refuri);
1.232     www      8203:           my ($match,$cond)=&is_on_map($refuri);
                   8204:             if ($match) {
                   8205:               my $refstatecond=$cond;
1.620     albertel 8206:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8207:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8208:                   my $value = $1;
                   8209:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  8210:                       if ($noblockcheck) {
1.1162    raeburn  8211:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8212:                       } else {
1.1172.2.118.  .8(raebu 8213:20):                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8214:                           if (@blockers > 0) {
                   8215:                               $thisallowed = 'B';
                   8216:                           } else {
                   8217:                               $thisallowed.=$value;
                   8218:                           }
1.1162    raeburn  8219:                       }
                   8220:                   } else {
                   8221:                       $thisallowed.=$value;
                   8222:                   }
1.53      www      8223:                   $uri=$refuri;
                   8224:                   $statecond=$refstatecond;
1.52      www      8225:               }
                   8226:           }
1.148     www      8227:         }
1.29      www      8228:        }
1.52      www      8229:    }
1.29      www      8230: 
1.52      www      8231: #
1.103     harris41 8232: # Gathered now: all privileges that could apply, and condition number
1.52      www      8233: # 
                   8234: #
                   8235: # Full or no access?
                   8236: #
1.29      www      8237: 
1.52      www      8238:     if ($thisallowed=~/F/) {
                   8239: 	return 'F';
                   8240:     }
1.29      www      8241: 
1.52      www      8242:     unless ($thisallowed) {
                   8243:         return '';
                   8244:     }
1.29      www      8245: 
1.52      www      8246: # Restrictions exist, deal with them
                   8247: #
                   8248: #   C:according to course preferences
                   8249: #   R:according to resource settings
                   8250: #   L:unless locked
                   8251: #   X:according to user session state
                   8252: #
                   8253: 
                   8254: # Possibly locked functionality, check all courses
1.54      www      8255: # Locks might take effect only after 10 minutes cache expiration for other
                   8256: # courses, and 2 minutes for current course
1.52      www      8257: 
                   8258:     my $envkey;
                   8259:     if ($thisallowed=~/L/) {
1.1000    raeburn  8260:         foreach $envkey (keys(%env)) {
1.54      www      8261:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8262:                my $courseid=$2;
                   8263:                my $roleid=$1.'.'.$2;
1.92      www      8264:                $courseid=~s/^\///;
1.54      www      8265:                my $expiretime=600;
1.620     albertel 8266:                if ($env{'request.role'} eq $roleid) {
1.54      www      8267: 		  $expiretime=120;
                   8268:                }
                   8269: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8270:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8271:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8272: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8273:                }
1.620     albertel 8274:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8275:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8276: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8277:                        &log($env{'user.domain'},$env{'user.name'},
                   8278:                             $env{'user.home'},
1.57      www      8279:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8280:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8281:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8282: 		       return '';
                   8283:                    }
                   8284:                }
1.620     albertel 8285:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8286:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   8287: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   8288:                        &log($env{'user.domain'},$env{'user.name'},
                   8289:                             $env{'user.home'},
1.57      www      8290:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8291:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8292:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8293: 		       return '';
                   8294:                    }
                   8295:                }
                   8296: 	   }
1.29      www      8297:        }
1.52      www      8298:     }
1.1172.2.118.  .8(raebu 8299:20): 
1.52      www      8300: #
                   8301: # Rest of the restrictions depend on selected course
                   8302: #
                   8303: 
1.620     albertel 8304:     unless ($env{'request.course.id'}) {
1.766     albertel 8305: 	if ($thisallowed eq 'A') {
                   8306: 	    return 'A';
1.814     raeburn  8307:         } elsif ($thisallowed eq 'B') {
                   8308:             return 'B';
1.766     albertel 8309: 	} else {
                   8310: 	    return '1';
                   8311: 	}
1.52      www      8312:     }
1.29      www      8313: 
1.52      www      8314: #
                   8315: # Now user is definitely in a course
                   8316: #
1.53      www      8317: 
                   8318: 
                   8319: # Course preferences
                   8320: 
                   8321:    if ($thisallowed=~/C/) {
1.620     albertel 8322:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8323:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8324:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8325: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8326: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8327: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8328: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8329: 			$env{'request.course.id'});
                   8330: 	   }
1.237     www      8331:            return '';
                   8332:        }
                   8333: 
1.620     albertel 8334:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8335: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8336: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8337: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8338: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8339: 			$env{'request.course.id'});
                   8340: 	   }
1.54      www      8341:            return '';
                   8342:        }
1.53      www      8343:    }
                   8344: 
                   8345: # Resource preferences
                   8346: 
                   8347:    if ($thisallowed=~/R/) {
1.620     albertel 8348:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8349:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8350: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8351: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8352: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8353: 	   }
                   8354: 	   return '';
1.54      www      8355:        }
1.53      www      8356:    }
1.30      www      8357: 
1.246     www      8358: # Restricted by state or randomout?
1.30      www      8359: 
1.52      www      8360:    if ($thisallowed=~/X/) {
1.620     albertel 8361:       if ($env{'acc.randomout'}) {
1.579     albertel 8362: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8363:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8364:             return ''; 
                   8365:          }
1.247     www      8366:       }
                   8367:       if (&condval($statecond)) {
1.52      www      8368: 	 return '2';
                   8369:       } else {
                   8370:          return '';
                   8371:       }
                   8372:    }
1.30      www      8373: 
1.766     albertel 8374:     if ($thisallowed eq 'A') {
                   8375: 	return 'A';
1.814     raeburn  8376:     } elsif ($thisallowed eq 'B') {
                   8377:         return 'B';
1.766     albertel 8378:     }
1.52      www      8379:    return 'F';
1.232     www      8380: }
1.1162    raeburn  8381: 
1.1172.2.13  raeburn  8382: # ------------------------------------------- Check construction space access
                   8383: 
                   8384: sub constructaccess {
                   8385:     my ($url,$setpriv)=@_;
                   8386: 
                   8387: # We do not allow editing of previous versions of files
                   8388:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8389: 
                   8390: # Get username and domain from URL
                   8391:     my ($ownername,$ownerdomain,$ownerhome);
                   8392: 
                   8393:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8394:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8395: 
                   8396: # The URL does not really point to any authorspace, forget it
                   8397:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8398: 
                   8399: # Now we need to see if the user has access to the authorspace of
                   8400: # $ownername at $ownerdomain
                   8401: 
                   8402:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8403: # Real author for this?
                   8404:        $ownerhome = $env{'user.home'};
                   8405:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8406:           return ($ownername,$ownerdomain,$ownerhome);
                   8407:        }
                   8408:     } else {
                   8409: # Co-author for this?
                   8410:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8411:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8412:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8413:             return ($ownername,$ownerdomain,$ownerhome);
                   8414:         }
                   8415:     }
                   8416: 
                   8417: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8418: # we might as well leave
                   8419:    unless ($setpriv) { return ''; }
                   8420: 
                   8421: # Backdoor access?
                   8422:     my $allowed=&allowed('eco',$ownerdomain);
                   8423: # Nope
                   8424:     unless ($allowed) { return ''; }
                   8425: # Looks like we may have access, but could be locked by the owner of the construction space
                   8426:     if ($allowed eq 'U') {
                   8427:         my %blocked=&get('environment',['domcoord.author'],
                   8428:                          $ownerdomain,$ownername);
                   8429: # Is blocked by owner
                   8430:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8431:     }
                   8432:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8433: # Grant temporary access
                   8434:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8435:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8436:         if (!$update) { $update = $then; }
                   8437:         my $refresh=$env{'user.refresh.time'};
                   8438:         if (!$refresh) { $refresh = $update; }
                   8439:         my $now = time;
                   8440:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8441:                            $now,'ca','constructaccess');
                   8442:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8443:         return($ownername,$ownerdomain,$ownerhome);
                   8444:     }
                   8445: # No business here
                   8446:     return '';
                   8447: }
                   8448: 
1.1172.2.66  raeburn  8449: # ----------------------------------------------------------- Content Blocking
                   8450: 
                   8451: {
                   8452: # Caches for faster Course Contents display where content blocking
                   8453: # is in operation (i.e., interval param set) for timed quiz.
                   8454: #
                   8455: # User for whom data are being temporarily cached.
                   8456: my $cacheduser='';
1.1172.2.118.  .8(raebu 8457:20): # Course for which data are being temporarily cached.
                   8458:20): my $cachedcid='';
1.1172.2.66  raeburn  8459: # Cached blockers for this user (a hash of blocking items).
                   8460: my %cachedblockers=();
                   8461: # When the data were last cached.
                   8462: my $cachedlast='';
                   8463: 
                   8464: sub load_all_blockers {
1.1172.2.118.  .9(raebu 8465:20):     my ($uname,$udom)=@_;
1.1172.2.66  raeburn  8466:     if (($uname ne '') && ($udom ne '')) {
                   8467:         if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.118.  .8(raebu 8468:20):             ($cachedcid eq $env{'request.course.id'}) &&
          .9(raebu 8469:20):             (abs($cachedlast-time)<5)) {
1.1172.2.66  raeburn  8470:             return;
                   8471:         }
                   8472:     }
                   8473:     $cachedlast=time;
                   8474:     $cacheduser=$uname.':'.$udom;
1.1172.2.118.  .8(raebu 8475:20):     $cachedcid=$env{'request.course.id'};
          .9(raebu 8476:20):     %cachedblockers = &get_commblock_resources();
          .8(raebu 8477:20):     return;
1.1172.2.66  raeburn  8478: }
                   8479: 
1.1162    raeburn  8480: sub get_comm_blocks {
                   8481:     my ($cdom,$cnum) = @_;
                   8482:     if ($cdom eq '' || $cnum eq '') {
                   8483:         return unless ($env{'request.course.id'});
                   8484:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8485:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8486:     }
                   8487:     my %commblocks;
                   8488:     my $hashid=$cdom.'_'.$cnum;
                   8489:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8490:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8491:         %commblocks = %{$blocksref};
                   8492:     } else {
                   8493:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8494:         my $cachetime = 600;
                   8495:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8496:     }
                   8497:     return %commblocks;
                   8498: }
                   8499: 
1.1172.2.66  raeburn  8500: sub get_commblock_resources {
                   8501:     my ($blocks) = @_;
                   8502:     my %blockers = ();
                   8503:     return %blockers unless ($env{'request.course.id'});
                   8504:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8505:     my %commblocks;
                   8506:     if (ref($blocks) eq 'HASH') {
                   8507:         %commblocks = %{$blocks};
                   8508:     } else {
                   8509:         %commblocks = &get_comm_blocks();
                   8510:     }
1.1172.2.66  raeburn  8511:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8512:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8513:     return %blockers unless (ref($navmap));
                   8514:     my $now = time;
1.1162    raeburn  8515:     foreach my $block (keys(%commblocks)) {
                   8516:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8517:             my ($start,$end) = ($1,$2);
                   8518:             if ($start <= $now && $end >= $now) {
                   8519:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8520:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8521:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8522:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8523:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8524:                             }
                   8525:                         }
                   8526:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8527:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8528:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8529:                             }
                   8530:                         }
                   8531:                     }
                   8532:                 }
                   8533:             }
                   8534:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8535:             my $item = $1;
1.1163    raeburn  8536:             my @to_test;
1.1162    raeburn  8537:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8538:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  8539:                     my @interval;
                   8540:                     my $type = 'map';
                   8541:                     if ($item eq 'course') {
                   8542:                         $type = 'course';
                   8543:                         @interval=&EXT("resource.0.interval");
                   8544:                     } else {
                   8545:                         if ($item =~ /___\d+___/) {
                   8546:                             $type = 'resource';
                   8547:                             @interval=&EXT("resource.0.interval",$item);
                   8548:                             if (ref($navmap)) {
                   8549:                                 my $res = $navmap->getBySymb($item);
                   8550:                                 push(@to_test,$res);
                   8551:                             }
1.1162    raeburn  8552:                         } else {
1.1172.2.66  raeburn  8553:                             my $mapsymb = &symbread($item,1);
                   8554:                             if ($mapsymb) {
                   8555:                                 if (ref($navmap)) {
                   8556:                                     my $mapres = $navmap->getBySymb($mapsymb);
1.1172.2.118.  .11(raeb 8557:-20):                                     if (ref($mapres)) {
                   8558:-20):                                         my $first = $mapres->map_start();
                   8559:-20):                                         my $finish = $mapres->map_finish();
                   8560:-20):                                         my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   8561:-20):                                         if (ref($it)) {
                   8562:-20):                                             my $res;
                   8563:-20):                                             while ($res = $it->next(undef,1)) {
                   8564:-20):                                                 next unless (ref($res));
                   8565:-20):                                                 my $symb = $res->symb();
                   8566:-20):                                                 next if (($symb eq $mapsymb) || ($symb eq ''));
                   8567:-20):                                                 @interval=&EXT("resource.0.interval",$symb);
                   8568:-20):                                                 if ($interval[1] eq 'map') {
                   8569:-20):                                                     if ($res->answerable()) {
                   8570:-20):                                                         push(@to_test,$res);
                   8571:-20):                                                         last;
                   8572:-20):                                                     }
                   8573:-20):                                                 }
1.1162    raeburn  8574:                                             }
                   8575:                                         }
                   8576:                                     }
                   8577:                                 }
                   8578:                             }
                   8579:                         }
1.1172.2.66  raeburn  8580:                     }
1.1172.2.118.  .1(raebu 8581:20):                     if ($interval[0] =~ /^(\d+)/) {
                   8582:20):                         my $timelimit = $1; 
1.1172.2.66  raeburn  8583:                         my $first_access;
                   8584:                         if ($type eq 'resource') {
                   8585:                             $first_access=&get_first_access($interval[1],$item);
                   8586:                         } elsif ($type eq 'map') {
                   8587:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8588:                         } else {
                   8589:                             $first_access=&get_first_access($interval[1]);
                   8590:                         }
                   8591:                         if ($first_access) {
1.1172.2.118.  .1(raebu 8592:20):                             my $timesup = $first_access+$timelimit;
1.1172.2.66  raeburn  8593:                             if ($timesup > $now) {
                   8594:                                 my $activeblock;
                   8595:                                 foreach my $res (@to_test) {
                   8596:                                     if ($res->answerable()) {
                   8597:                                         $activeblock = 1;
                   8598:                                         last;
                   8599:                                     }
                   8600:                                 }
                   8601:                                 if ($activeblock) {
                   8602:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8603:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8604:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8605:                                          }
                   8606:                                     }
                   8607:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8608:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8609:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8610:                                         }
1.1162    raeburn  8611:                                     }
                   8612:                                 }
                   8613:                             }
                   8614:                         }
                   8615:                     }
                   8616:                 }
                   8617:             }
                   8618:         }
                   8619:     }
1.1172.2.66  raeburn  8620:     return %blockers;
1.1162    raeburn  8621: }
                   8622: 
1.1172.2.66  raeburn  8623: sub has_comm_blocking {
1.1172.2.118.  .9(raebu 8624:20):     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66  raeburn  8625:     my @blockers;
                   8626:     return unless ($env{'request.course.id'});
                   8627:     return unless ($priv eq 'bre');
                   8628:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8629:     return if ($env{'request.state'} eq 'construct');
1.1172.2.118.  .9(raebu 8630:20):     my %blockinfo;
                   8631:20):     if (ref($blocks) eq 'HASH') {
                   8632:20):         %blockinfo = &get_commblock_resources($blocks);
                   8633:20):     } else {
                   8634:20):         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   8635:20):         %blockinfo = %cachedblockers;
                   8636:20):     }
                   8637:20):     return unless (keys(%blockinfo) > 0);
1.1172.2.66  raeburn  8638:     my (%possibles,@symbs);
                   8639:     if (!$symb) {
1.1172.2.118.  .9(raebu 8640:20):         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  8641:     }
1.1172.2.66  raeburn  8642:     if ($symb) {
                   8643:         @symbs = ($symb);
                   8644:     } elsif (keys(%possibles)) {
                   8645:         @symbs = keys(%possibles);
                   8646:     }
                   8647:     my $noblock;
                   8648:     foreach my $symb (@symbs) {
                   8649:         last if ($noblock);
                   8650:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.118.  .9(raebu 8651:20):         foreach my $block (keys(%blockinfo)) {
1.1172.2.66  raeburn  8652:             if ($block =~ /^firstaccess____(.+)$/) {
                   8653:                 my $item = $1;
1.1172.2.118.  .8(raebu 8654:20):                 unless ($blocked) {
                   8655:20):                     if (($item eq $map) || ($item eq $symb)) {
                   8656:20):                         $noblock = 1;
                   8657:20):                         last;
                   8658:20):                     }
1.1172.2.66  raeburn  8659:                 }
1.1162    raeburn  8660:             }
1.1172.2.118.  .9(raebu 8661:20):             if (ref($blockinfo{$block}) eq 'HASH') {
                   8662:20):                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   8663:20):                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66  raeburn  8664:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8665:                             push(@blockers,$block);
                   8666:                         }
                   8667:                     }
                   8668:                 }
1.1172.2.118.  .9(raebu 8669:20):                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   8670:20):                     if ($blockinfo{$block}{'maps'}{$map}) {
          .8(raebu 8671:20):                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8672:20):                             push(@blockers,$block);
                   8673:20):                         }
1.1172.2.66  raeburn  8674:                     }
                   8675:                 }
1.1162    raeburn  8676:             }
                   8677:         }
                   8678:     }
1.1172.2.118.  .8(raebu 8679:20):     unless ($noblock) {
                   8680:20):         return @blockers;
                   8681:20):     }
                   8682:20):     return;
1.1172.2.66  raeburn  8683: }
1.1162    raeburn  8684: }
                   8685: 
1.1172.2.66  raeburn  8686: # -------------------------------- Deversion and split uri into path an filename
                   8687: 
1.1133    foxr     8688: #
1.1172.2.66  raeburn  8689: #   Removes the version from a URI and
1.1133    foxr     8690: #   splits it in to its filename and path to the filename.
                   8691: #   Seems like File::Basename could have done this more clearly.
                   8692: #   Parameters:
                   8693: #      $uri   - input URI
                   8694: #   Returns:
                   8695: #     Two element list consisting of 
                   8696: #     $pathname  - the URI up to and excluding the trailing /
                   8697: #     $filename  - The part of the URI following the last /
                   8698: #  NOTE:
                   8699: #    Another realization of this is simply:
                   8700: #    use File::Basename;
                   8701: #    ...
                   8702: #    $uri = shift;
                   8703: #    $filename = basename($uri);
                   8704: #    $path     = dirname($uri);
                   8705: #    return ($filename, $path);
                   8706: #
                   8707: #     The implementation below is probably faster however.
                   8708: #
1.710     albertel 8709: sub split_uri_for_cond {
                   8710:     my $uri=&deversion(&declutter(shift));
                   8711:     my @uriparts=split(/\//,$uri);
                   8712:     my $filename=pop(@uriparts);
                   8713:     my $pathname=join('/',@uriparts);
                   8714:     return ($pathname,$filename);
                   8715: }
1.232     www      8716: # --------------------------------------------------- Is a resource on the map?
                   8717: 
                   8718: sub is_on_map {
1.710     albertel 8719:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8720:     #Trying to find the conditional for the file
1.620     albertel 8721:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8722: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8723:     if ($match) {
1.289     bowersj2 8724: 	return (1,$1);
                   8725:     } else {
1.434     www      8726: 	return (0,0);
1.289     bowersj2 8727:     }
1.12      www      8728: }
                   8729: 
1.427     www      8730: # --------------------------------------------------------- Get symb from alias
                   8731: 
                   8732: sub get_symb_from_alias {
                   8733:     my $symb=shift;
                   8734:     my ($map,$resid,$url)=&decode_symb($symb);
                   8735: # Already is a symb
                   8736:     if ($url) { return $symb; }
                   8737: # Must be an alias
                   8738:     my $aliassymb='';
                   8739:     my %bighash;
1.620     albertel 8740:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8741:                             &GDBM_READER(),0640)) {
                   8742:         my $rid=$bighash{'mapalias_'.$symb};
                   8743: 	if ($rid) {
                   8744: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8745: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8746: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8747: 	}
                   8748:         untie %bighash;
                   8749:     }
                   8750:     return $aliassymb;
                   8751: }
                   8752: 
1.12      www      8753: # ----------------------------------------------------------------- Define Role
                   8754: 
                   8755: sub definerole {
                   8756:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8757:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8758:     foreach my $role (split(':',$sysrole)) {
                   8759: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8760:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8761:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8762: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8763:                return "refused:s:$crole&$cqual"; 
                   8764:             }
                   8765:         }
1.191     harris41 8766:     }
1.800     albertel 8767:     foreach my $role (split(':',$domrole)) {
                   8768: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8769:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8770:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8771: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8772:                return "refused:d:$crole&$cqual"; 
                   8773:             }
                   8774:         }
1.191     harris41 8775:     }
1.800     albertel 8776:     foreach my $role (split(':',$courole)) {
                   8777: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8778:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8779:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8780: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8781:                return "refused:c:$crole&$cqual"; 
                   8782:             }
                   8783:         }
1.191     harris41 8784:     }
1.1172.2.84  raeburn  8785:     my $uhome;
                   8786:     if (($uname ne '') && ($udom ne '')) {
                   8787:         $uhome = &homeserver($uname,$udom);
                   8788:         return $uhome if ($uhome eq 'no_host');
                   8789:     } else {
                   8790:         $uname = $env{'user.name'};
                   8791:         $udom = $env{'user.domain'};
                   8792:         $uhome = $env{'user.home'};
                   8793:     }
1.620     albertel 8794:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8795:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8796:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8797:     return reply($command,$uhome);
1.12      www      8798:   } else {
                   8799:     return 'refused';
                   8800:   }
1.105     harris41 8801: }
                   8802: 
                   8803: # ---------------- Make a metadata query against the network of library servers
                   8804: 
                   8805: sub metadata_query {
1.1172.2.33  raeburn  8806:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8807:     my %rhash;
1.845     albertel 8808:     my %libserv = &all_library();
1.244     matthew  8809:     my @server_list = (defined($server_array) ? @$server_array
                   8810:                                               : keys(%libserv) );
                   8811:     for my $server (@server_list) {
1.1172.2.33  raeburn  8812:         my $domains = '';
                   8813:         if (ref($domains_hash) eq 'HASH') {
                   8814:             $domains = $domains_hash->{$server};    
                   8815:         }
1.118     harris41 8816: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8817: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8818: 	    $rhash{$server}=$reply;
                   8819: 	}
                   8820: 	else {
                   8821: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8822: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8823: 			     $server);
                   8824: 	    $rhash{$server}=$reply;
                   8825: 	}
1.112     harris41 8826:     }
1.118     harris41 8827:     return \%rhash;
1.240     www      8828: }
                   8829: 
                   8830: # ----------------------------------------- Send log queries and wait for reply
                   8831: 
                   8832: sub log_query {
                   8833:     my ($uname,$udom,$query,%filters)=@_;
                   8834:     my $uhome=&homeserver($uname,$udom);
                   8835:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8836:     my $uhost=&hostname($uhome);
1.800     albertel 8837:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8838:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8839:                        $uhome);
1.479     albertel 8840:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8841:     return get_query_reply($queryid);
                   8842: }
                   8843: 
1.818     raeburn  8844: # -------------------------- Update MySQL table for portfolio file
                   8845: 
                   8846: sub update_portfolio_table {
1.821     raeburn  8847:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8848:     if ($group ne '') {
                   8849:         $file_name =~s /^\Q$group\E//;
                   8850:     }
1.818     raeburn  8851:     my $homeserver = &homeserver($uname,$udom);
                   8852:     my $queryid=
1.821     raeburn  8853:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8854:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8855:     my $reply = &get_query_reply($queryid);
                   8856:     return $reply;
                   8857: }
                   8858: 
1.899     raeburn  8859: # -------------------------- Update MySQL allusers table
                   8860: 
                   8861: sub update_allusers_table {
                   8862:     my ($uname,$udom,$names) = @_;
                   8863:     my $homeserver = &homeserver($uname,$udom);
                   8864:     my $queryid=
                   8865:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8866:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8867:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8868:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8869:                'generation='.&escape($names->{'generation'}).'%%'.
                   8870:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8871:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8872:     return;
1.899     raeburn  8873: }
                   8874: 
1.508     raeburn  8875: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8876: 
                   8877: sub fetch_enrollment_query {
1.511     raeburn  8878:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8879:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8880:     my $maxtries = 1;
1.508     raeburn  8881:     if ($context eq 'automated') {
                   8882:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8883:         $sleep = 2;
                   8884:         $loopmax = 100;
1.547     raeburn  8885:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8886:     } else {
                   8887:         $homeserver = &homeserver($cnum,$dom);
                   8888:     }
1.838     albertel 8889:     my $host=&hostname($homeserver);
1.506     raeburn  8890:     my $cmd = '';
1.1000    raeburn  8891:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8892:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8893:     }
                   8894:     $cmd =~ s/%%$//;
                   8895:     $cmd = &escape($cmd);
                   8896:     my $query = 'fetchenrollment';
1.620     albertel 8897:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8898:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8899:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8900:         return 'error: '.$queryid;
                   8901:     }
1.1172.2.93  raeburn  8902:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8903:     my $tries = 1;
                   8904:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8905:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8906:         $tries ++;
                   8907:     }
1.526     raeburn  8908:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8909:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8910:     } else {
1.901     albertel 8911:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8912:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8913:             foreach my $line (@responses) {
                   8914:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8915:                 $$replyref{$key} = $value;
                   8916:             }
                   8917:         } else {
1.1117    foxr     8918:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8919:             foreach my $line (@responses) {
                   8920:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8921:                 $$replyref{$key} = $value;
                   8922:                 if ($value > 0) {
1.800     albertel 8923:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8924:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8925:                         my $destname = $pathname.'/'.$filename;
                   8926:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8927:                         if ($xml_classlist =~ /^error/) {
                   8928:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8929:                         } else {
1.1172.2.96  raeburn  8930:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8931:                                 print FILE &unescape($xml_classlist);
                   8932:                                 close(FILE);
1.526     raeburn  8933:                             } else {
                   8934:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8935:                             }
                   8936:                         }
                   8937:                     }
                   8938:                 }
                   8939:             }
                   8940:         }
                   8941:         return 'ok';
                   8942:     }
                   8943:     return 'error';
                   8944: }
                   8945: 
1.242     www      8946: sub get_query_reply {
1.1172.2.79  raeburn  8947:     my ($queryid,$sleep,$loopmax) = @_;
                   8948:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8949:         $sleep = 0.2;
                   8950:     }
                   8951:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8952:         $loopmax = 100;
                   8953:     }
1.1117    foxr     8954:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8955:     my $reply='';
1.1172.2.79  raeburn  8956:     for (1..$loopmax) {
                   8957: 	sleep($sleep);
1.240     www      8958:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  8959: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8960: 		$reply = join('',<$fh>);
                   8961: 		close($fh);
1.240     www      8962: 	   } else { return 'error: reply_file_error'; }
1.242     www      8963:            return &unescape($reply);
                   8964: 	}
1.240     www      8965:     }
1.242     www      8966:     return 'timeout:'.$queryid;
1.240     www      8967: }
                   8968: 
                   8969: sub courselog_query {
1.241     www      8970: #
                   8971: # possible filters:
                   8972: # url: url or symb
                   8973: # username
                   8974: # domain
                   8975: # action: view, submit, grade
                   8976: # start: timestamp
                   8977: # end: timestamp
                   8978: #
1.240     www      8979:     my (%filters)=@_;
1.620     albertel 8980:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8981:     if ($filters{'url'}) {
                   8982: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8983:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8984:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8985:     }
1.620     albertel 8986:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8987:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8988:     return &log_query($cname,$cdom,'courselog',%filters);
                   8989: }
                   8990: 
                   8991: sub userlog_query {
1.858     raeburn  8992: #
                   8993: # possible filters:
                   8994: # action: log check role
                   8995: # start: timestamp
                   8996: # end: timestamp
                   8997: #
1.240     www      8998:     my ($uname,$udom,%filters)=@_;
                   8999:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9000: }
                   9001: 
1.506     raeburn  9002: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9003: 
                   9004: sub auto_run {
1.508     raeburn  9005:     my ($cnum,$cdom) = @_;
1.876     raeburn  9006:     my $response = 0;
                   9007:     my $settings;
                   9008:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9009:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9010:         $settings = $domconfig{'autoenroll'};
                   9011:         if ($settings->{'run'} eq '1') {
                   9012:             $response = 1;
                   9013:         }
                   9014:     } else {
1.934     raeburn  9015:         my $homeserver;
                   9016:         if (&is_course($cdom,$cnum)) {
                   9017:             $homeserver = &homeserver($cnum,$cdom);
                   9018:         } else {
                   9019:             $homeserver = &domain($cdom,'primary');
                   9020:         }
                   9021:         if ($homeserver ne 'no_host') {
                   9022:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9023:         }
1.876     raeburn  9024:     }
1.506     raeburn  9025:     return $response;
                   9026: }
1.776     albertel 9027: 
1.506     raeburn  9028: sub auto_get_sections {
1.508     raeburn  9029:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9030:     my $homeserver;
                   9031:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9032:         $homeserver = &homeserver($cnum,$cdom);
                   9033:     }
                   9034:     if (!defined($homeserver)) { 
                   9035:         if ($cdom =~ /^$match_domain$/) {
                   9036:             $homeserver = &domain($cdom,'primary');
                   9037:         }
                   9038:     }
                   9039:     my @secs;
                   9040:     if (defined($homeserver)) {
                   9041:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9042:         unless ($response eq 'refused') {
                   9043:             @secs = split(/:/,$response);
                   9044:         }
1.506     raeburn  9045:     }
                   9046:     return @secs;
                   9047: }
1.776     albertel 9048: 
1.506     raeburn  9049: sub auto_new_course {
1.1099    raeburn  9050:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9051:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9052:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9053:     return $response;
                   9054: }
1.776     albertel 9055: 
1.506     raeburn  9056: sub auto_validate_courseID {
1.508     raeburn  9057:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9058:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9059:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9060:     return $response;
                   9061: }
1.776     albertel 9062: 
1.1007    raeburn  9063: sub auto_validate_instcode {
1.1020    raeburn  9064:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9065:     my ($homeserver,$response);
                   9066:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9067:         $homeserver = &homeserver($cnum,$cdom);
                   9068:     }
                   9069:     if (!defined($homeserver)) {
                   9070:         if ($cdom =~ /^$match_domain$/) {
                   9071:             $homeserver = &domain($cdom,'primary');
                   9072:         }
                   9073:     }
1.1065    raeburn  9074:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9075:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  9076:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9077:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9078: }
                   9079: 
1.506     raeburn  9080: sub auto_create_password {
1.873     raeburn  9081:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9082:     my ($homeserver,$response);
1.506     raeburn  9083:     my $create_passwd = 0;
                   9084:     my $authchk = '';
1.873     raeburn  9085:     if ($udom =~ /^$match_domain$/) {
                   9086:         $homeserver = &domain($udom,'primary');
                   9087:     }
                   9088:     if ($homeserver eq '') {
                   9089:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9090:             $homeserver = &homeserver($cnum,$cdom);
                   9091:         }
                   9092:     }
                   9093:     if ($homeserver eq '') {
                   9094:         $authchk = 'nodomain';
1.506     raeburn  9095:     } else {
1.873     raeburn  9096:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9097:         if ($response eq 'refused') {
                   9098:             $authchk = 'refused';
                   9099:         } else {
1.901     albertel 9100:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9101:         }
1.506     raeburn  9102:     }
                   9103:     return ($authparam,$create_passwd,$authchk);
                   9104: }
                   9105: 
1.706     raeburn  9106: sub auto_photo_permission {
                   9107:     my ($cnum,$cdom,$students) = @_;
                   9108:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9109:     my ($outcome,$perm_reqd,$conditions) = 
                   9110: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9111:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9112: 	return (undef,undef);
                   9113:     }
1.706     raeburn  9114:     return ($outcome,$perm_reqd,$conditions);
                   9115: }
                   9116: 
                   9117: sub auto_checkphotos {
                   9118:     my ($uname,$udom,$pid) = @_;
                   9119:     my $homeserver = &homeserver($uname,$udom);
                   9120:     my ($result,$resulttype);
                   9121:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9122: 				   &escape($uname).':'.&escape($pid),
                   9123: 				   $homeserver));
1.709     albertel 9124:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9125: 	return (undef,undef);
                   9126:     }
1.706     raeburn  9127:     if ($outcome) {
                   9128:         ($result,$resulttype) = split(/:/,$outcome);
                   9129:     } 
                   9130:     return ($result,$resulttype);
                   9131: }
                   9132: 
                   9133: sub auto_photochoice {
                   9134:     my ($cnum,$cdom) = @_;
                   9135:     my $homeserver = &homeserver($cnum,$cdom);
                   9136:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9137: 						       &escape($cdom),
                   9138: 						       $homeserver)));
1.709     albertel 9139:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9140: 	return (undef,undef);
                   9141:     }
1.706     raeburn  9142:     return ($update,$comment);
                   9143: }
                   9144: 
                   9145: sub auto_photoupdate {
                   9146:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9147:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9148:     my $host=&hostname($homeserver);
1.706     raeburn  9149:     my $cmd = '';
                   9150:     my $maxtries = 1;
1.800     albertel 9151:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9152:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9153:     }
                   9154:     $cmd =~ s/%%$//;
                   9155:     $cmd = &escape($cmd);
                   9156:     my $query = 'institutionalphotos';
                   9157:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9158:     unless ($queryid=~/^\Q$host\E\_/) {
                   9159:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9160:         return 'error: '.$queryid;
                   9161:     }
                   9162:     my $reply = &get_query_reply($queryid);
                   9163:     my $tries = 1;
                   9164:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9165:         $reply = &get_query_reply($queryid);
                   9166:         $tries ++;
                   9167:     }
                   9168:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9169:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9170:     } else {
                   9171:         my @responses = split(/:/,$reply);
                   9172:         my $outcome = shift(@responses); 
                   9173:         foreach my $item (@responses) {
                   9174:             my ($key,$value) = split(/=/,$item);
                   9175:             $$photo{$key} = $value;
                   9176:         }
                   9177:         return $outcome;
                   9178:     }
                   9179:     return 'error';
                   9180: }
                   9181: 
1.521     raeburn  9182: sub auto_instcode_format {
1.793     albertel 9183:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9184: 	$cat_order) = @_;
1.521     raeburn  9185:     my $courses = '';
1.772     raeburn  9186:     my @homeservers;
1.521     raeburn  9187:     if ($caller eq 'global') {
1.841     albertel 9188: 	my %servers = &get_servers($codedom,'library');
                   9189: 	foreach my $tryserver (keys(%servers)) {
                   9190: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9191: 		push(@homeservers,$tryserver);
                   9192: 	    }
1.584     raeburn  9193:         }
1.1022    raeburn  9194:     } elsif ($caller eq 'requests') {
                   9195:         if ($codedom =~ /^$match_domain$/) {
                   9196:             my $chome = &domain($codedom,'primary');
                   9197:             unless ($chome eq 'no_host') {
                   9198:                 push(@homeservers,$chome);
                   9199:             }
                   9200:         }
1.521     raeburn  9201:     } else {
1.772     raeburn  9202:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9203:     }
1.793     albertel 9204:     foreach my $code (keys(%{$instcodes})) {
                   9205:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9206:     }
                   9207:     chop($courses);
1.772     raeburn  9208:     my $ok_response = 0;
                   9209:     my $response;
                   9210:     while (@homeservers > 0 && $ok_response == 0) {
                   9211:         my $server = shift(@homeservers); 
                   9212:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9213:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9214:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9215: 		split(/:/,$response);
1.772     raeburn  9216:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9217:             push(@{$codetitles},&str2array($codetitles_str));
                   9218:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9219:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9220:             $ok_response = 1;
                   9221:         }
                   9222:     }
                   9223:     if ($ok_response) {
1.521     raeburn  9224:         return 'ok';
1.772     raeburn  9225:     } else {
                   9226:         return $response;
1.521     raeburn  9227:     }
                   9228: }
                   9229: 
1.792     raeburn  9230: sub auto_instcode_defaults {
                   9231:     my ($domain,$returnhash,$code_order) = @_;
                   9232:     my @homeservers;
1.841     albertel 9233: 
                   9234:     my %servers = &get_servers($domain,'library');
                   9235:     foreach my $tryserver (keys(%servers)) {
                   9236: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9237: 	    push(@homeservers,$tryserver);
                   9238: 	}
1.792     raeburn  9239:     }
1.841     albertel 9240: 
1.792     raeburn  9241:     my $response;
1.841     albertel 9242:     foreach my $server (@homeservers) {
1.792     raeburn  9243:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9244:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9245: 	
                   9246: 	foreach my $pair (split(/\&/,$response)) {
                   9247: 	    my ($name,$value)=split(/\=/,$pair);
                   9248: 	    if ($name eq 'code_order') {
                   9249: 		@{$code_order} = split(/\&/,&unescape($value));
                   9250: 	    } else {
                   9251: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9252: 	    }
                   9253: 	}
                   9254: 	return 'ok';
1.792     raeburn  9255:     }
1.841     albertel 9256: 
                   9257:     return $response;
1.1003    raeburn  9258: }
                   9259: 
                   9260: sub auto_possible_instcodes {
1.1007    raeburn  9261:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9262:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9263:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9264:         return;
                   9265:     }
1.1003    raeburn  9266:     my (@homeservers,$uhome);
                   9267:     if (defined(&domain($domain,'primary'))) {
                   9268:         $uhome=&domain($domain,'primary');
                   9269:         push(@homeservers,&domain($domain,'primary'));
                   9270:     } else {
                   9271:         my %servers = &get_servers($domain,'library');
                   9272:         foreach my $tryserver (keys(%servers)) {
                   9273:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9274:                 push(@homeservers,$tryserver);
                   9275:             }
                   9276:         }
                   9277:     }
                   9278:     my $response;
                   9279:     foreach my $server (@homeservers) {
                   9280:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9281:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9282:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9283:             split(':',$response);
                   9284:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9285:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9286:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9287:             my ($name,$value)=split('=',$item);
                   9288:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9289:         }
                   9290:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9291:             my ($name,$value)=split('=',$item);
                   9292:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9293:         }
                   9294:         return 'ok';
                   9295:     }
                   9296:     return $response;
                   9297: }
1.792     raeburn  9298: 
1.1010    raeburn  9299: sub auto_courserequest_checks {
                   9300:     my ($dom) = @_;
1.1020    raeburn  9301:     my ($homeserver,%validations);
                   9302:     if ($dom =~ /^$match_domain$/) {
                   9303:         $homeserver = &domain($dom,'primary');
                   9304:     }
                   9305:     unless ($homeserver eq 'no_host') {
                   9306:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9307:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9308:             my @items = split(/&/,$response);
                   9309:             foreach my $item (@items) {
                   9310:                 my ($key,$value) = split('=',$item);
                   9311:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9312:             }
                   9313:         }
                   9314:     }
1.1010    raeburn  9315:     return %validations; 
                   9316: }
                   9317: 
1.1020    raeburn  9318: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9319:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9320:     my ($homeserver,$response);
                   9321:     if ($dom =~ /^$match_domain$/) {
                   9322:         $homeserver = &domain($dom,'primary');
                   9323:     }
1.1172.2.43  raeburn  9324:     unless ($homeserver eq 'no_host') {
                   9325:         my $customdata;
                   9326:         if (ref($custominfo) eq 'HASH') {
                   9327:             $customdata = &freeze_escape($custominfo);
                   9328:         }
1.1020    raeburn  9329:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9330:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9331:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9332:                                     $customdata,$homeserver));
1.1020    raeburn  9333:     }
                   9334:     return $response;
                   9335: }
                   9336: 
1.777     albertel 9337: sub auto_validate_class_sec {
1.918     raeburn  9338:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9339:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9340:     my $ownerlist;
                   9341:     if (ref($owners) eq 'ARRAY') {
                   9342:         $ownerlist = join(',',@{$owners});
                   9343:     } else {
                   9344:         $ownerlist = $owners;
                   9345:     }
1.773     raeburn  9346:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9347:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9348:     return $response;
                   9349: }
                   9350: 
1.1172.2.94  raeburn  9351: sub auto_validate_instclasses {
                   9352:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9353:     my ($homeserver,%validations);
                   9354:     $homeserver = &homeserver($cnum,$cdom);
                   9355:     unless ($homeserver eq 'no_host') {
                   9356:         my $ownerlist;
                   9357:         if (ref($owners) eq 'ARRAY') {
                   9358:             $ownerlist = join(',',@{$owners});
                   9359:         } else {
                   9360:             $ownerlist = $owners;
                   9361:         }
                   9362:         if (ref($classesref) eq 'HASH') {
                   9363:             my $classes = &freeze_escape($classesref);
                   9364:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9365:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9366:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9367:                 my @items = split(/&/,$response);
                   9368:                 foreach my $item (@items) {
                   9369:                     my ($key,$value) = split('=',$item);
                   9370:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9371:                 }
                   9372:             }
                   9373:         }
                   9374:     }
                   9375:     return %validations;
                   9376: }
                   9377: 
1.1172.2.38  raeburn  9378: sub auto_crsreq_update {
                   9379:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9380:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9381:     my ($homeserver,%crsreqresponse);
                   9382:     if ($cdom =~ /^$match_domain$/) {
                   9383:         $homeserver = &domain($cdom,'primary');
                   9384:     }
                   9385:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9386:         my $info;
                   9387:         if (ref($inbound) eq 'HASH') {
                   9388:             $info = &freeze_escape($inbound);
                   9389:         }
                   9390:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9391:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9392:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9393:                             &escape($title).':'.&escape($code).':'.
                   9394:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9395:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9396:             my @items = split(/&/,$response);
                   9397:             foreach my $item (@items) {
                   9398:                 my ($key,$value) = split('=',$item);
                   9399:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9400:             }
                   9401:         }
                   9402:     }
                   9403:     return \%crsreqresponse;
                   9404: }
                   9405: 
1.1172.2.78  raeburn  9406: sub auto_export_grades {
                   9407:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9408:     my ($homeserver,%exportresponse);
                   9409:     if ($cdom =~ /^$match_domain$/) {
                   9410:         $homeserver = &domain($cdom,'primary');
                   9411:     }
                   9412:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9413:         my $info;
                   9414:         if (ref($inforef) eq 'HASH') {
                   9415:             $info = &freeze_escape($inforef);
                   9416:         }
                   9417:         if (ref($gradesref) eq 'HASH') {
                   9418:             my $grades = &freeze_escape($gradesref);
                   9419:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9420:                                 $info.':'.$grades,$homeserver);
                   9421:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9422:                 my @items = split(/&/,$response);
                   9423:                 foreach my $item (@items) {
                   9424:                     my ($key,$value) = split('=',$item);
                   9425:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9426:                 }
                   9427:             }
                   9428:         }
                   9429:     }
                   9430:     return \%exportresponse;
                   9431: }
                   9432: 
1.1172.2.68  raeburn  9433: sub check_instcode_cloning {
                   9434:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9435:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9436:         return;
                   9437:     }
                   9438:     my $canclone;
                   9439:     if (@{$code_order} > 0) {
                   9440:         my $instcoderegexp ='^';
                   9441:         my @clonecodes = split(/\&/,$cloner);
                   9442:         foreach my $item (@{$code_order}) {
                   9443:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9444:                 foreach my $pair (@clonecodes) {
                   9445:                     my ($key,$val) = split(/\=/,$pair,2);
                   9446:                     $val = &unescape($val);
                   9447:                     if ($key eq $item) {
                   9448:                         $instcoderegexp .= '('.$val.')';
                   9449:                         last;
                   9450:                     }
                   9451:                 }
                   9452:             } else {
                   9453:                 $instcoderegexp .= $codedefaults->{$item};
                   9454:             }
                   9455:         }
                   9456:         $instcoderegexp .= '$';
                   9457:         my (@from,@to);
                   9458:         eval {
                   9459:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9460:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9461:         };
                   9462:         if ((@from > 0) && (@to > 0)) {
                   9463:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9464:             if (!@diffs) {
                   9465:                 $canclone = 1;
                   9466:             }
                   9467:         }
                   9468:     }
                   9469:     return $canclone;
                   9470: }
                   9471: 
                   9472: sub default_instcode_cloning {
                   9473:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9474:     my (%codedefaults,@code_order,$canclone);
                   9475:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9476:         %codedefaults = %{$codedefaultsref};
                   9477:         @code_order = @{$codeorderref};
                   9478:     } elsif ($clonedom) {
                   9479:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9480:     }
                   9481:     if (($domdefclone) && (@code_order)) {
                   9482:         my @clonecodes = split(/\+/,$domdefclone);
                   9483:         my $instcoderegexp ='^';
                   9484:         foreach my $item (@code_order) {
                   9485:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9486:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9487:             } else {
                   9488:                 $instcoderegexp .= $codedefaults{$item};
                   9489:             }
                   9490:         }
                   9491:         $instcoderegexp .= '$';
                   9492:         my (@from,@to);
                   9493:         eval {
                   9494:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9495:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9496:         };
                   9497:         if ((@from > 0) && (@to > 0)) {
                   9498:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9499:             if (!@diffs) {
                   9500:                 $canclone = 1;
                   9501:             }
                   9502:         }
                   9503:     }
                   9504:     return $canclone;
                   9505: }
                   9506: 
1.679     raeburn  9507: # ------------------------------------------------------- Course Group routines
                   9508: 
                   9509: sub get_coursegroups {
1.809     raeburn  9510:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9511:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9512: }
                   9513: 
1.679     raeburn  9514: sub modify_coursegroup {
                   9515:     my ($cdom,$cnum,$groupsettings) = @_;
                   9516:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9517: }
                   9518: 
1.809     raeburn  9519: sub toggle_coursegroup_status {
                   9520:     my ($cdom,$cnum,$group,$action) = @_;
                   9521:     my ($from_namespace,$to_namespace);
                   9522:     if ($action eq 'delete') {
                   9523:         $from_namespace = 'coursegroups';
                   9524:         $to_namespace = 'deleted_groups';
                   9525:     } else {
                   9526:         $from_namespace = 'deleted_groups';
                   9527:         $to_namespace = 'coursegroups';
                   9528:     }
                   9529:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9530:     if (my $tmp = &error(%curr_group)) {
                   9531:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9532:         return ('read error',$tmp);
                   9533:     } else {
                   9534:         my %savedsettings = %curr_group; 
1.809     raeburn  9535:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9536:         my $deloutcome;
                   9537:         if ($result eq 'ok') {
1.809     raeburn  9538:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9539:         } else {
                   9540:             return ('write error',$result);
                   9541:         }
                   9542:         if ($deloutcome eq 'ok') {
                   9543:             return 'ok';
                   9544:         } else {
                   9545:             return ('delete error',$deloutcome);
                   9546:         }
                   9547:     }
                   9548: }
                   9549: 
1.679     raeburn  9550: sub modify_group_roles {
1.957     raeburn  9551:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9552:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9553:     my $role = 'gr/'.&escape($userprivs);
                   9554:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9555:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9556:     if ($result eq 'ok') {
                   9557:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9558:     }
1.679     raeburn  9559:     return $result;
                   9560: }
                   9561: 
                   9562: sub modify_coursegroup_membership {
                   9563:     my ($cdom,$cnum,$membership) = @_;
                   9564:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9565:     return $result;
                   9566: }
                   9567: 
1.682     raeburn  9568: sub get_active_groups {
                   9569:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9570:     my $now = time;
                   9571:     my %groups = ();
                   9572:     foreach my $key (keys(%env)) {
1.811     albertel 9573:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9574:             my ($start,$end) = split(/\./,$env{$key});
                   9575:             if (($end!=0) && ($end<$now)) { next; }
                   9576:             if (($start!=0) && ($start>$now)) { next; }
                   9577:             if ($1 eq $cdom && $2 eq $cnum) {
                   9578:                 $groups{$3} = $env{$key} ;
                   9579:             }
                   9580:         }
                   9581:     }
                   9582:     return %groups;
                   9583: }
                   9584: 
1.683     raeburn  9585: sub get_group_membership {
                   9586:     my ($cdom,$cnum,$group) = @_;
                   9587:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9588: }
                   9589: 
                   9590: sub get_users_groups {
                   9591:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9592:     my @usersgroups;
1.683     raeburn  9593:     my $cachetime=1800;
                   9594: 
                   9595:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9596:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9597:     if (defined($cached)) {
1.734     albertel 9598:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9599:     } else {  
                   9600:         $grouplist = '';
1.816     raeburn  9601:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9602:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9603:         my $access_end = $env{'course.'.$courseid.
                   9604:                               '.default_enrollment_end_date'};
                   9605:         my $now = time;
                   9606:         foreach my $key (keys(%roleshash)) {
                   9607:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9608:                 my $group = $1;
                   9609:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9610:                     my $start = $2;
                   9611:                     my $end = $1;
                   9612:                     if ($start == -1) { next; } # deleted from group
                   9613:                     if (($start!=0) && ($start>$now)) { next; }
                   9614:                     if (($end!=0) && ($end<$now)) {
                   9615:                         if ($access_end && $access_end < $now) {
                   9616:                             if ($access_end - $end < 86400) {
                   9617:                                 push(@usersgroups,$group);
1.733     raeburn  9618:                             }
                   9619:                         }
1.817     raeburn  9620:                         next;
1.733     raeburn  9621:                     }
1.817     raeburn  9622:                     push(@usersgroups,$group);
1.683     raeburn  9623:                 }
                   9624:             }
                   9625:         }
1.817     raeburn  9626:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9627:         $grouplist = join(':',@usersgroups);
                   9628:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9629:     }
1.733     raeburn  9630:     return @usersgroups;
1.683     raeburn  9631: }
                   9632: 
                   9633: sub devalidate_getgroups_cache {
                   9634:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9635:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9636: 
1.683     raeburn  9637:     my $hashid="$udom:$uname:$courseid";
                   9638:     &devalidate_cache_new('getgroups',$hashid);
                   9639: }
                   9640: 
1.12      www      9641: # ------------------------------------------------------------------ Plain Text
                   9642: 
                   9643: sub plaintext {
1.988     raeburn  9644:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9645:     if ($short =~ m{^cr/}) {
1.758     albertel 9646: 	return (split('/',$short))[-1];
                   9647:     }
1.742     raeburn  9648:     if (!defined($cid)) {
                   9649:         $cid = $env{'request.course.id'};
                   9650:     }
                   9651:     my %rolenames = (
1.1008    raeburn  9652:                       Course    => 'std',
                   9653:                       Community => 'alt1',
1.742     raeburn  9654:                     );
1.1037    raeburn  9655:     if ($cid ne '') {
                   9656:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9657:             unless ($forcedefault) {
                   9658:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9659:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9660:                 return &Apache::lonlocal::mt($roletext);
                   9661:             }
                   9662:         }
                   9663:     }
                   9664:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9665:         (defined($rolenames{$type})) && 
                   9666:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9667:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9668:     } elsif ($cid ne '') {
                   9669:         my $crstype = $env{'course.'.$cid.'.type'};
                   9670:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9671:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9672:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9673:         }
1.742     raeburn  9674:     }
1.1037    raeburn  9675:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9676: }
                   9677: 
                   9678: # ----------------------------------------------------------------- Assign Role
                   9679: 
                   9680: sub assignrole {
1.957     raeburn  9681:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9682:         $context)=@_;
1.21      www      9683:     my $mrole;
                   9684:     if ($role =~ /^cr\//) {
1.393     www      9685:         my $cwosec=$url;
1.811     albertel 9686:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9687: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9688:            my $refused = 1;
                   9689:            if ($context eq 'requestcourses') {
                   9690:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9691:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9692:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9693:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9694:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9695:                            if ($crsenv{'internal.courseowner'} eq
                   9696:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9697:                                $refused = '';
                   9698:                            }
                   9699:                        }
                   9700:                    }
                   9701:                }
                   9702:            }
                   9703:            if ($refused) {
                   9704:                &logthis('Refused custom assignrole: '.
                   9705:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9706:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9707:                return 'refused';
                   9708:            }
1.104     www      9709:         }
1.21      www      9710:         $mrole='cr';
1.678     raeburn  9711:     } elsif ($role =~ /^gr\//) {
                   9712:         my $cwogrp=$url;
1.811     albertel 9713:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9714:         unless (&allowed('mdg',$cwogrp)) {
                   9715:             &logthis('Refused group assignrole: '.
                   9716:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9717:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9718:             return 'refused';
                   9719:         }
                   9720:         $mrole='gr';
1.21      www      9721:     } else {
1.82      www      9722:         my $cwosec=$url;
1.811     albertel 9723:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9724:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9725:             my $refused;
                   9726:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9727:                 if (!(&allowed('c'.$role,$url))) {
                   9728:                     $refused = 1;
                   9729:                 }
                   9730:             } else {
                   9731:                 $refused = 1;
                   9732:             }
1.947     raeburn  9733:             if ($refused) {
1.1045    raeburn  9734:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9735:                 if (!$selfenroll && $context eq 'course') {
                   9736:                     my %crsenv;
                   9737:                     if ($role eq 'cc' || $role eq 'co') {
                   9738:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9739:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9740:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9741:                                 if ($crsenv{'internal.courseowner'} eq 
                   9742:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9743:                                     $refused = '';
                   9744:                                 }
                   9745:                             }
                   9746:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9747:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9748:                                 if ($crsenv{'internal.courseowner'} eq 
                   9749:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9750:                                     $refused = '';
                   9751:                                 }
                   9752:                             }
                   9753:                         }
                   9754:                     }
                   9755:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9756:                     $refused = '';
1.1017    raeburn  9757:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9758:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9759:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9760:                         my $wrongcc;
                   9761:                         if ($cnum =~ /^$match_community$/) {
                   9762:                             $wrongcc = 1 if ($role eq 'cc');
                   9763:                         } else {
                   9764:                             $wrongcc = 1 if ($role eq 'co');
                   9765:                         }
                   9766:                         unless ($wrongcc) {
                   9767:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9768:                             if ($crsenv{'internal.courseowner'} eq 
                   9769:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9770:                                 $refused = '';
                   9771:                             }
1.1017    raeburn  9772:                         }
                   9773:                     }
1.1172.2.9  raeburn  9774:                 } elsif ($context eq 'requestauthor') {
                   9775:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9776:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9777:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9778:                             $refused = '';
                   9779:                         } else {
                   9780:                             my %domdefaults = &get_domain_defaults($udom);
                   9781:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9782:                                 my $checkbystatus;
                   9783:                                 if ($env{'user.adv'}) {
                   9784:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9785:                                     if ($disposition eq 'automatic') {
                   9786:                                         $refused = '';
                   9787:                                     } elsif ($disposition eq '') {
                   9788:                                         $checkbystatus = 1;
                   9789:                                     }
                   9790:                                 } else {
                   9791:                                     $checkbystatus = 1;
                   9792:                                 }
                   9793:                                 if ($checkbystatus) {
                   9794:                                     if ($env{'environment.inststatus'}) {
                   9795:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9796:                                         foreach my $type (@inststatuses) {
                   9797:                                             if (($type ne '') &&
                   9798:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9799:                                                 $refused = '';
                   9800:                                             }
                   9801:                                         }
                   9802:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9803:                                         $refused = '';
                   9804:                                     }
                   9805:                                 }
                   9806:                             }
                   9807:                         }
                   9808:                     }
1.1017    raeburn  9809:                 }
                   9810:                 if ($refused) {
1.947     raeburn  9811:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9812:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9813: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9814:                     return 'refused';
                   9815:                 }
1.932     raeburn  9816:             }
1.1131    raeburn  9817:         } elsif ($role eq 'au') {
                   9818:             if ($url ne '/'.$udom.'/') {
                   9819:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9820:                          ' to assign author role for '.$uname.':'.$udom.
                   9821:                          ' in domain: '.$url.' refused (wrong domain).');
                   9822:                 return 'refused';
                   9823:             }
1.104     www      9824:         }
1.21      www      9825:         $mrole=$role;
                   9826:     }
1.620     albertel 9827:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9828:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9829:     if ($end) { $command.='_'.$end; }
1.21      www      9830:     if ($start) {
                   9831: 	if ($end) { 
1.81      www      9832:            $command.='_'.$start; 
1.21      www      9833:         } else {
1.81      www      9834:            $command.='_0_'.$start;
1.21      www      9835:         }
                   9836:     }
1.739     raeburn  9837:     my $origstart = $start;
                   9838:     my $origend = $end;
1.957     raeburn  9839:     my $delflag;
1.357     www      9840: # actually delete
                   9841:     if ($deleteflag) {
1.373     www      9842: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9843: # modify command to delete the role
1.620     albertel 9844:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9845:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9846: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9847: # set start and finish to negative values for userrolelog
                   9848:            $start=-1;
                   9849:            $end=-1;
1.957     raeburn  9850:            $delflag = 1;
1.357     www      9851:         }
                   9852:     }
                   9853: # send command
1.349     www      9854:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9855: # log new user role if status is ok
1.349     www      9856:     if ($answer eq 'ok') {
1.663     raeburn  9857: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9858:         if (($role eq 'cc') || ($role eq 'in') ||
                   9859:             ($role eq 'ep') || ($role eq 'ad') ||
                   9860:             ($role eq 'ta') || ($role eq 'st') ||
                   9861:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9862:             ($role eq 'co')) {
1.1172.2.13  raeburn  9863: # for course roles, perform group memberships changes triggered by role change.
                   9864:             unless ($role =~ /^gr/) {
                   9865:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9866:                                                  $origstart,$selfenroll,$context);
                   9867:             }
1.1172.2.9  raeburn  9868:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9869:                            $selfenroll,$context);
                   9870:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9871:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9872:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9873:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9874:                            $context);
                   9875:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9876:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9877:                              $context);
                   9878:         }
1.1053    raeburn  9879:         if ($role eq 'cc') {
                   9880:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9881:         }
1.349     www      9882:     }
                   9883:     return $answer;
1.169     harris41 9884: }
                   9885: 
1.1053    raeburn  9886: sub autoupdate_coowners {
                   9887:     my ($url,$end,$start,$uname,$udom) = @_;
                   9888:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9889:     if (($cdom ne '') && ($cnum ne '')) {
                   9890:         my $now = time;
                   9891:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9892:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9893:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9894:             my $instcode = $coursehash{'internal.coursecode'};
                   9895:             if ($instcode ne '') {
1.1056    raeburn  9896:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9897:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9898:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9899:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9900:                         if ($result eq 'valid') {
                   9901:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9902:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9903:                                     push(@newcoowners,$coowner);
                   9904:                                 }
                   9905:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9906:                                     push(@newcoowners,$uname.':'.$udom);
                   9907:                                 }
                   9908:                                 @newcoowners = sort(@newcoowners);
                   9909:                             } else {
                   9910:                                 push(@newcoowners,$uname.':'.$udom);
                   9911:                             }
                   9912:                         } else {
                   9913:                             if ($coursehash{'internal.co-owners'}) {
                   9914:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9915:                                     unless ($coowner eq $uname.':'.$udom) {
                   9916:                                         push(@newcoowners,$coowner);
                   9917:                                     }
                   9918:                                 }
                   9919:                                 unless (@newcoowners > 0) {
                   9920:                                     $delcoowners = 1;
                   9921:                                     $coowners = '';
                   9922:                                 }
                   9923:                             }
                   9924:                         }
                   9925:                         if (@newcoowners || $delcoowners) {
                   9926:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9927:                                             $delcoowners,@newcoowners);
                   9928:                         }
                   9929:                     }
                   9930:                 }
                   9931:             }
                   9932:         }
                   9933:     }
                   9934: }
                   9935: 
                   9936: sub store_coowners {
                   9937:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9938:     my $cid = $cdom.'_'.$cnum;
                   9939:     my ($coowners,$delresult,$putresult);
                   9940:     if (@newcoowners) {
                   9941:         $coowners = join(',',@newcoowners);
                   9942:         my %coownershash = (
                   9943:                             'internal.co-owners' => $coowners,
                   9944:                            );
                   9945:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9946:         if ($putresult eq 'ok') {
                   9947:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9948:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9949:             }
                   9950:         }
                   9951:     }
                   9952:     if ($delcoowners) {
                   9953:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9954:         if ($delresult eq 'ok') {
                   9955:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9956:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9957:             }
                   9958:         }
                   9959:     }
                   9960:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9961:         my %crsinfo =
                   9962:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9963:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9964:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9965:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9966:         }
                   9967:     }
                   9968: }
                   9969: 
1.169     harris41 9970: # -------------------------------------------------- Modify user authentication
1.197     www      9971: # Overrides without validation
                   9972: 
1.169     harris41 9973: sub modifyuserauth {
                   9974:     my ($udom,$uname,$umode,$upass)=@_;
                   9975:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  9976:     my $allowed;
                   9977:     if (&allowed('mau',$udom)) {
                   9978:         $allowed = 1;
                   9979:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   9980:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   9981:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   9982:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9983:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9984:         if (($cdom ne '') && ($cnum ne '')) {
                   9985:             my $is_owner = &is_course_owner($cdom,$cnum);
                   9986:             if ($is_owner) {
                   9987:                 $allowed = 1;
                   9988:             }
                   9989:         }
                   9990:     }
                   9991:     unless ($allowed) { return 'refused'; }
1.197     www      9992:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9993:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9994:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9995:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9996: 		     &escape($upass),$uhome);
1.620     albertel 9997:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9998:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9999:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   10000:     &log($udom,,$uname,$uhome,
1.620     albertel 10001:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10002:                                      $env{'user.name'}.', '.$umode.
1.197     www      10003:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 10004:     unless ($reply eq 'ok') {
1.197     www      10005:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10006: 	return 'error: '.$reply;
                   10007:     }   
1.170     harris41 10008:     return 'ok';
1.80      www      10009: }
                   10010: 
1.81      www      10011: # --------------------------------------------------------------- Modify a user
1.80      www      10012: 
1.81      www      10013: sub modifyuser {
1.206     matthew  10014:     my ($udom,    $uname, $uid,
                   10015:         $umode,   $upass, $first,
                   10016:         $middle,  $last,  $gene,
1.1058    raeburn  10017:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10018:     $udom= &LONCAPA::clean_domain($udom);
                   10019:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10020:     my $showcandelete = 'none';
                   10021:     if (ref($candelete) eq 'ARRAY') {
                   10022:         if (@{$candelete} > 0) {
                   10023:             $showcandelete = join(', ',@{$candelete});
                   10024:         }
                   10025:     }
1.81      www      10026:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10027:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10028: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10029:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10030:                                      ' desiredhome not specified'). 
1.620     albertel 10031:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10032:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10033:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10034:     my $newuser;
                   10035:     if ($uhome eq 'no_host') {
                   10036:         $newuser = 1;
                   10037:     }
1.80      www      10038: # ----------------------------------------------------------------- Create User
1.406     albertel 10039:     if (($uhome eq 'no_host') && 
                   10040: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      10041:         my $unhome='';
1.844     albertel 10042:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10043:             $unhome = $desiredhome;
1.620     albertel 10044: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10045: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10046:         } else { # load balancing routine for determining $unhome
1.81      www      10047:             my $loadm=10000000;
1.841     albertel 10048: 	    my %servers = &get_servers($udom,'library');
                   10049: 	    foreach my $tryserver (keys(%servers)) {
                   10050: 		my $answer=reply('load',$tryserver);
                   10051: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10052: 		    $loadm=$answer;
                   10053: 		    $unhome=$tryserver;
                   10054: 		}
1.80      www      10055: 	    }
                   10056:         }
                   10057:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10058: 	    return 'error: unable to find a home server for '.$uname.
                   10059:                    ' in domain '.$udom;
1.80      www      10060:         }
                   10061:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10062:                          &escape($upass),$unhome);
                   10063: 	unless ($reply eq 'ok') {
                   10064:             return 'error: '.$reply;
                   10065:         }   
1.230     stredwic 10066:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10067:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10068: 	    return 'error: unable verify users home machine.';
1.80      www      10069:         }
1.209     matthew  10070:     }   # End of creation of new user
1.80      www      10071: # ---------------------------------------------------------------------- Add ID
                   10072:     if ($uid) {
                   10073:        $uid=~tr/A-Z/a-z/;
                   10074:        my %uidhash=&idrget($udom,$uname);
1.196     www      10075:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10076:          && (!$forceid)) {
1.80      www      10077: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10078: 	      return 'error: user id "'.$uid.'" does not match '.
                   10079:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10080:           }
                   10081:        } else {
                   10082: 	  &idput($udom,($uname => $uid));
                   10083:        }
                   10084:     }
                   10085: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10086:     my @tmp=&get('environment',
1.899     raeburn  10087: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10088:                     'permanentemail','inststatus'],
1.134     albertel 10089: 		   $udom,$uname);
1.1075    raeburn  10090:     my (%names,%oldnames);
1.313     matthew  10091:     if ($tmp[0] =~ m/^error:.*/) { 
                   10092:         %names=(); 
                   10093:     } else {
                   10094:         %names = @tmp;
1.1075    raeburn  10095:         %oldnames = %names;
1.313     matthew  10096:     }
1.388     www      10097: #
1.1058    raeburn  10098: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10099: # of users did not contain them), do not overwrite existing values
                   10100: # unless field is in $candelete array ref.  
                   10101: #
                   10102: 
                   10103:     my @fields = ('firstname','middlename','lastname','generation',
                   10104:                   'permanentemail','id');
                   10105:     my %newvalues;
                   10106:     if (ref($candelete) eq 'ARRAY') {
                   10107:         foreach my $field (@fields) {
                   10108:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10109:                 if ($field eq 'firstname') {
                   10110:                     $names{$field} = $first;
                   10111:                 } elsif ($field eq 'middlename') {
                   10112:                     $names{$field} = $middle;
                   10113:                 } elsif ($field eq 'lastname') {
                   10114:                     $names{$field} = $last;
                   10115:                 } elsif ($field eq 'generation') { 
                   10116:                     $names{$field} = $gene;
                   10117:                 } elsif ($field eq 'permanentemail') {
                   10118:                     $names{$field} = $email;
                   10119:                 } elsif ($field eq 'id') {
                   10120:                     $names{$field}  = $uid;
                   10121:                 }
                   10122:             }
                   10123:         }
                   10124:     }
1.388     www      10125:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10126:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10127:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10128:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10129:     if ($email) {
                   10130:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10131:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10132:     }
1.899     raeburn  10133:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10134:     if (defined($inststatus)) {
                   10135:         $names{'inststatus'} = '';
                   10136:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10137:         if (ref($usertypes) eq 'HASH') {
                   10138:             my @okstatuses; 
                   10139:             foreach my $item (split(/:/,$inststatus)) {
                   10140:                 if (defined($usertypes->{$item})) {
                   10141:                     push(@okstatuses,$item);  
                   10142:                 }
                   10143:             }
                   10144:             if (@okstatuses) {
                   10145:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10146:             }
                   10147:         }
                   10148:     }
1.1075    raeburn  10149:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10150:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10151:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10152:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10153:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10154:     } else {
                   10155:         $logmsg .= ' during self creation';
                   10156:     }
1.1075    raeburn  10157:     my $changed;
                   10158:     if ($newuser) {
                   10159:         $changed = 1;
                   10160:     } else {
                   10161:         foreach my $field (@fields) {
                   10162:             if ($names{$field} ne $oldnames{$field}) {
                   10163:                 $changed = 1;
                   10164:                 last;
                   10165:             }
                   10166:         }
                   10167:     }
                   10168:     unless ($changed) {
                   10169:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10170:         &logthis($logmsg);
                   10171:         return 'ok';
                   10172:     }
                   10173:     my $reply = &put('environment', \%names, $udom,$uname);
                   10174:     if ($reply ne 'ok') { 
                   10175:         return 'error: '.$reply;
                   10176:     }
1.1087    raeburn  10177:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10178:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10179:     }
1.1075    raeburn  10180:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10181:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10182:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10183:     &logthis($logmsg);
1.134     albertel 10184:     return 'ok';
1.80      www      10185: }
                   10186: 
1.81      www      10187: # -------------------------------------------------------------- Modify student
1.80      www      10188: 
1.81      www      10189: sub modifystudent {
                   10190:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10191:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10192:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10193:     if (!$cid) {
1.620     albertel 10194: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10195: 	    return 'not_in_class';
                   10196: 	}
1.80      www      10197:     }
                   10198: # --------------------------------------------------------------- Make the user
1.81      www      10199:     my $reply=&modifyuser
1.209     matthew  10200: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10201:          $desiredhome,$email,$inststatus);
1.80      www      10202:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10203:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10204:     # student's environment
1.297     matthew  10205:     $uid = undef if (!$forceid);
1.455     albertel 10206:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10207: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10208:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10209:     return $reply;
                   10210: }
                   10211: 
                   10212: sub modify_student_enrollment {
1.1172.2.23  raeburn  10213:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10214:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10215:     my ($cdom,$cnum,$chome);
                   10216:     if (!$cid) {
1.620     albertel 10217: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10218: 	    return 'not_in_class';
                   10219: 	}
1.620     albertel 10220: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10221: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10222:     } else {
                   10223: 	($cdom,$cnum)=split(/_/,$cid);
                   10224:     }
1.620     albertel 10225:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10226:     if (!$chome) {
1.457     raeburn  10227: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10228:     }
1.455     albertel 10229:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10230:     # Make sure the user exists
1.81      www      10231:     my $uhome=&homeserver($uname,$udom);
                   10232:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10233: 	return 'error: no such user';
                   10234:     }
1.297     matthew  10235:     # Get student data if we were not given enough information
                   10236:     if (!defined($first)  || $first  eq '' || 
                   10237:         !defined($last)   || $last   eq '' || 
                   10238:         !defined($uid)    || $uid    eq '' || 
                   10239:         !defined($middle) || $middle eq '' || 
                   10240:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10241:         # They did not supply us with enough data to enroll the student, so
                   10242:         # we need to pick up more information.
1.297     matthew  10243:         my %tmp = &get('environment',
1.294     matthew  10244:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10245:                        ,$udom,$uname);
                   10246: 
1.800     albertel 10247:         #foreach my $key (keys(%tmp)) {
                   10248:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10249:         #}
1.294     matthew  10250:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10251:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10252:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10253:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10254:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10255:     }
1.556     albertel 10256:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10257:     my $user = "$uname:$udom";
                   10258:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10259:     my $reply=cput('classlist',
1.1148    raeburn  10260: 		   {$user => 
1.1172.2.76  raeburn  10261: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10262: 		   $cdom,$cnum);
1.1148    raeburn  10263:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10264:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10265:     } else { 
1.81      www      10266: 	return 'error: '.$reply;
                   10267:     }
1.297     matthew  10268:     # Add student role to user
1.83      www      10269:     my $uurl='/'.$cid;
1.81      www      10270:     $uurl=~s/\_/\//g;
                   10271:     if ($usec) {
                   10272: 	$uurl.='/'.$usec;
                   10273:     }
1.1148    raeburn  10274:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10275:                              $selfenroll,$context);
                   10276:     if ($result ne 'ok') {
                   10277:         if ($old_entry{$user} ne '') {
                   10278:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10279:         } else {
                   10280:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10281:         }
                   10282:     }
                   10283:     return $result; 
1.21      www      10284: }
                   10285: 
1.556     albertel 10286: sub format_name {
                   10287:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10288:     my $name;
                   10289:     if ($first ne 'lastname') {
                   10290: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10291:     } else {
                   10292: 	if ($lastname=~/\S/) {
                   10293: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10294: 	    $name=~s/\s+,/,/;
                   10295: 	} else {
                   10296: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10297: 	}
                   10298:     }
                   10299:     $name=~s/^\s+//;
                   10300:     $name=~s/\s+$//;
                   10301:     $name=~s/\s+/ /g;
                   10302:     return $name;
                   10303: }
                   10304: 
1.84      www      10305: # ------------------------------------------------- Write to course preferences
                   10306: 
                   10307: sub writecoursepref {
                   10308:     my ($courseid,%prefs)=@_;
                   10309:     $courseid=~s/^\///;
                   10310:     $courseid=~s/\_/\//g;
                   10311:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10312:     my $chome=homeserver($cnum,$cdomain);
                   10313:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10314: 	return 'error: no such course';
                   10315:     }
                   10316:     my $cstring='';
1.800     albertel 10317:     foreach my $pref (keys(%prefs)) {
                   10318: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10319:     }
1.84      www      10320:     $cstring=~s/\&$//;
                   10321:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10322: }
                   10323: 
                   10324: # ---------------------------------------------------------- Make/modify course
                   10325: 
                   10326: sub createcourse {
1.741     raeburn  10327:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1172.2.118.  .6(raebu 10328:20):         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      10329:     $url=&declutter($url);
                   10330:     my $cid='';
1.1028    raeburn  10331:     if ($context eq 'requestcourses') {
                   10332:         my $can_create = 0;
                   10333:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10334:         if ($udom eq $ownerdom) {
1.1172.2.118.  .6(raebu 10335:20):             my $reload;
                   10336:20):             if (($callercontext eq 'auto') &&
                   10337:20):                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   10338:20):                 $reload = 'reload';
                   10339:20):             }
                   10340:20):             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  10341:                                   $context)) {
                   10342:                 $can_create = 1;
                   10343:             }
                   10344:         } else {
                   10345:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10346:                                            $category);
                   10347:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10348:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10349:                 if (@curr > 0) {
                   10350:                     my @options = qw(approval validate autolimit);
                   10351:                     my $optregex = join('|',@options);
                   10352:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10353:                         $can_create = 1;
                   10354:                     }
                   10355:                 }
                   10356:             }
                   10357:         }
                   10358:         if ($can_create) {
                   10359:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10360:                 unless (&allowed('ccc',$udom)) {
                   10361:                     return 'refused'; 
                   10362:                 }
1.1017    raeburn  10363:             }
                   10364:         } else {
                   10365:             return 'refused';
                   10366:         }
1.1028    raeburn  10367:     } elsif (!&allowed('ccc',$udom)) {
                   10368:         return 'refused';
1.84      www      10369:     }
1.1011    raeburn  10370: # --------------------------------------------------------------- Get Unique ID
                   10371:     my $uname;
                   10372:     if ($cnum =~ /^$match_courseid$/) {
                   10373:         my $chome=&homeserver($cnum,$udom,'true');
                   10374:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10375:             $uname = $cnum;
                   10376:         } else {
1.1038    raeburn  10377:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10378:         }
                   10379:     } else {
1.1038    raeburn  10380:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10381:     }
                   10382:     return $uname if ($uname =~ /^error/);
                   10383: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10384:     if (!defined($course_server)) {
                   10385:         if (defined(&domain($udom,'primary'))) {
                   10386:             $course_server = &domain($udom,'primary');
                   10387:         } else {
                   10388:             $course_server = $env{'user.home'}; 
                   10389:         }
                   10390:     }
                   10391:     my %host_servers =
                   10392:         &Apache::lonnet::get_servers($udom,'library');
                   10393:     unless ($host_servers{$course_server}) {
                   10394:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10395:     }
1.84      www      10396: # ------------------------------------------------------------- Make the course
                   10397:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10398:                       $course_server);
1.84      www      10399:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10400:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10401:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10402: 	return 'error: no such course';
                   10403:     }
1.271     www      10404: # ----------------------------------------------------------------- Course made
1.516     raeburn  10405: # log existence
1.1029    raeburn  10406:     my $now = time;
1.918     raeburn  10407:     my $newcourse = {
                   10408:                     $udom.'_'.$uname => {
1.921     raeburn  10409:                                      description => $description,
                   10410:                                      inst_code   => $inst_code,
                   10411:                                      owner       => $course_owner,
                   10412:                                      type        => $crstype,
1.1029    raeburn  10413:                                      creator     => $env{'user.name'}.':'.
                   10414:                                                     $env{'user.domain'},
                   10415:                                      created     => $now,
                   10416:                                      context     => $context,
1.918     raeburn  10417:                                                 },
                   10418:                     };
1.921     raeburn  10419:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10420: # set toplevel url
1.271     www      10421:     my $topurl=$url;
                   10422:     unless ($nonstandard) {
                   10423: # ------------------------------------------ For standard courses, make top url
                   10424:         my $mapurl=&clutter($url);
1.278     www      10425:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10426:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10427: <map>
                   10428: <resource id="1" type="start"></resource>
                   10429: <resource id="2" src="$mapurl"></resource>
                   10430: <resource id="3" type="finish"></resource>
                   10431: <link index="1" from="1" to="2"></link>
                   10432: <link index="2" from="2" to="3"></link>
                   10433: </map>
                   10434: ENDINITMAP
                   10435:         $topurl=&declutter(
1.638     albertel 10436:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10437:                           );
                   10438:     }
                   10439: # ----------------------------------------------------------- Write preferences
1.84      www      10440:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10441:                      ('description'              => $description,
                   10442:                       'url'                      => $topurl,
                   10443:                       'internal.creator'         => $env{'user.name'}.':'.
                   10444:                                                     $env{'user.domain'},
                   10445:                       'internal.created'         => $now,
                   10446:                       'internal.creationcontext' => $context)
                   10447:                     );
1.84      www      10448:     return '/'.$udom.'/'.$uname;
                   10449: }
                   10450: 
1.1011    raeburn  10451: # ------------------------------------------------------------------- Create ID
                   10452: sub generate_coursenum {
1.1038    raeburn  10453:     my ($udom,$crstype) = @_;
1.1011    raeburn  10454:     my $domdesc = &domain($udom);
                   10455:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10456:     my $first;
                   10457:     if ($crstype eq 'Community') {
                   10458:         $first = '0';
                   10459:     } else {
                   10460:         $first = int(1+rand(9)); 
                   10461:     } 
                   10462:     my $uname=$first.
1.1011    raeburn  10463:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10464:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10465:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10466: # ----------------------------------------------- Make sure that does not exist
                   10467:     my $uhome=&homeserver($uname,$udom,'true');
                   10468:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10469:         if ($crstype eq 'Community') {
                   10470:             $first = '0';
                   10471:         } else {
                   10472:             $first = int(1+rand(9));
                   10473:         }
                   10474:         $uname=$first.
1.1011    raeburn  10475:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10476:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10477:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10478:         $uhome=&homeserver($uname,$udom,'true');
                   10479:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10480:             return 'error: unable to generate unique course-ID';
                   10481:         }
                   10482:     }
                   10483:     return $uname;
                   10484: }
                   10485: 
1.813     albertel 10486: sub is_course {
1.1167    droeschl 10487:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10488:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10489:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10490:     my $uhome=&homeserver($cnum,$cdom);
                   10491:     my $iscourse;
                   10492:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10493:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10494:     } else {
                   10495:         my $hashid = $cdom.':'.$cnum;
                   10496:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10497:         unless (defined($cached)) {
                   10498:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10499:                                         $cnum,undef,undef,'.');
                   10500:             $iscourse = 0;
                   10501:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10502:                 $iscourse = 1;
                   10503:             }
                   10504:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10505:         }
                   10506:     }
                   10507:     return unless($iscourse);
1.1167    droeschl 10508:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10509: }
                   10510: 
1.1015    raeburn  10511: sub store_userdata {
                   10512:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10513:     my $result;
1.1016    raeburn  10514:     if ($datakey ne '') {
1.1013    raeburn  10515:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10516:             if ($udom eq '' || $uname eq '') {
                   10517:                 $udom = $env{'user.domain'};
                   10518:                 $uname = $env{'user.name'};
                   10519:             }
                   10520:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10521:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10522:                 $result = 'error: no_host';
                   10523:             } else {
                   10524:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10525:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10526: 
                   10527:                 my $namevalue='';
                   10528:                 foreach my $key (keys(%{$storehash})) {
                   10529:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10530:                 }
                   10531:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10532:                 unless ($namespace eq 'courserequests') {
                   10533:                     $datakey = &escape($datakey);
                   10534:                 }
1.1105    raeburn  10535:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10536:                                   $namevalue,$uhome);
1.1013    raeburn  10537:             }
                   10538:         } else {
                   10539:             $result = 'error: data to store was not a hash reference'; 
                   10540:         }
                   10541:     } else {
                   10542:         $result= 'error: invalid requestkey'; 
                   10543:     }
                   10544:     return $result;
                   10545: }
                   10546: 
1.21      www      10547: # ---------------------------------------------------------- Assign Custom Role
                   10548: 
                   10549: sub assigncustomrole {
1.957     raeburn  10550:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10551:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10552:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10553: }
                   10554: 
                   10555: # ----------------------------------------------------------------- Revoke Role
                   10556: 
                   10557: sub revokerole {
1.957     raeburn  10558:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10559:     my $now=time;
1.965     raeburn  10560:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10561: }
                   10562: 
                   10563: # ---------------------------------------------------------- Revoke Custom Role
                   10564: 
                   10565: sub revokecustomrole {
1.957     raeburn  10566:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10567:     my $now=time;
1.357     www      10568:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10569:            $deleteflag,$selfenroll,$context);
1.17      www      10570: }
                   10571: 
1.533     banghart 10572: # ------------------------------------------------------------ Disk usage
1.535     albertel 10573: sub diskusage {
1.955     raeburn  10574:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10575:     $directorypath =~ s/\/$//;
                   10576:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10577:                        .&escape($getpropath).':'.&escape($uname).':'
                   10578:                        .&escape($udom),homeserver($uname,$udom));
                   10579:     if ($listing eq 'unknown_cmd') {
                   10580:         if ($getpropath) {
                   10581:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10582:         }
                   10583:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10584:     }
1.514     albertel 10585:     return $listing;
1.512     banghart 10586: }
                   10587: 
1.566     banghart 10588: sub is_locked {
1.1096    raeburn  10589:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10590:     my @check;
                   10591:     my $is_locked;
1.1093    raeburn  10592:     push (@check,$file_name);
1.613     albertel 10593:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10594: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10595:     my ($tmp)=keys(%locked);
                   10596:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10597:     
1.566     banghart 10598:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10599:         $is_locked = 'false';
                   10600:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10601:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10602:                $is_locked = 'true';
1.1096    raeburn  10603:                if (ref($which) eq 'ARRAY') {
                   10604:                    push(@{$which},$entry);
                   10605:                } else {
                   10606:                    last;
                   10607:                }
1.745     raeburn  10608:            }
                   10609:        }
1.566     banghart 10610:     } else {
                   10611:         $is_locked = 'false';
                   10612:     }
1.1093    raeburn  10613:     return $is_locked;
1.566     banghart 10614: }
                   10615: 
1.759     albertel 10616: sub declutter_portfile {
                   10617:     my ($file) = @_;
1.833     albertel 10618:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10619:     return $file;
                   10620: }
                   10621: 
1.559     banghart 10622: # ------------------------------------------------------------- Mark as Read Only
                   10623: 
                   10624: sub mark_as_readonly {
                   10625:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10626:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10627:     my ($tmp)=keys(%current_permissions);
                   10628:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10629:     foreach my $file (@{$files}) {
1.759     albertel 10630: 	$file = &declutter_portfile($file);
1.561     banghart 10631:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10632:     }
1.613     albertel 10633:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10634:     return;
                   10635: }
                   10636: 
1.572     banghart 10637: # ------------------------------------------------------------Save Selected Files
                   10638: 
                   10639: sub save_selected_files {
                   10640:     my ($user, $path, @files) = @_;
                   10641:     my $filename = $user."savedfiles";
1.573     banghart 10642:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  10643:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10644:     foreach my $file (@files) {
1.620     albertel 10645:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10646:     }
                   10647:     foreach my $file (@other_files) {
1.574     banghart 10648:         print (OUT $file."\n");
1.572     banghart 10649:     }
1.574     banghart 10650:     close (OUT);
1.572     banghart 10651:     return 'ok';
                   10652: }
                   10653: 
1.574     banghart 10654: sub clear_selected_files {
                   10655:     my ($user) = @_;
                   10656:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  10657:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10658:     print (OUT undef);
                   10659:     close (OUT);
                   10660:     return ("ok");    
                   10661: }
                   10662: 
1.572     banghart 10663: sub files_in_path {
                   10664:     my ($user, $path) = @_;
                   10665:     my $filename = $user."savedfiles";
                   10666:     my %return_files;
1.1172.2.96  raeburn  10667:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10668:     while (my $line_in = <IN>) {
1.574     banghart 10669:         chomp ($line_in);
                   10670:         my @paths_and_file = split (m!/!, $line_in);
                   10671:         my $file_part = pop (@paths_and_file);
                   10672:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10673:         $path_part.='/';
                   10674:         my $path_and_file = $path_part.$file_part;
                   10675:         if ($path_part eq $path) {
                   10676:             $return_files{$file_part}= 'selected';
                   10677:         }
                   10678:     }
1.574     banghart 10679:     close (IN);
                   10680:     return (\%return_files);
1.572     banghart 10681: }
                   10682: 
                   10683: # called in portfolio select mode, to show files selected NOT in current directory
                   10684: sub files_not_in_path {
                   10685:     my ($user, $path) = @_;
                   10686:     my $filename = $user."savedfiles";
                   10687:     my @return_files;
                   10688:     my $path_part;
1.1172.2.96  raeburn  10689:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10690:     while (my $line = <IN>) {
1.572     banghart 10691:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10692:         my @paths_and_file = split(m|/|, $line);
                   10693:         my $file_part = pop(@paths_and_file);
                   10694:         chomp($file_part);
                   10695:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10696:         $path_part .= '/';
                   10697:         my $path_and_file = $path_part.$file_part;
                   10698:         if ($path_part ne $path) {
1.800     albertel 10699:             push(@return_files, ($path_and_file));
1.572     banghart 10700:         }
                   10701:     }
1.800     albertel 10702:     close(OUT);
1.574     banghart 10703:     return (@return_files);
1.572     banghart 10704: }
                   10705: 
1.745     raeburn  10706: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10707: 
1.745     raeburn  10708: sub get_portfile_permissions {
                   10709:     my ($domain,$user) = @_;
1.613     albertel 10710:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10711:     my ($tmp)=keys(%current_permissions);
                   10712:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10713:     return \%current_permissions;
                   10714: }
                   10715: 
                   10716: #---------------------------------------------Get portfolio file access controls
                   10717: 
1.749     raeburn  10718: sub get_access_controls {
1.745     raeburn  10719:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10720:     my %access;
                   10721:     my $real_file = $file;
                   10722:     $file =~ s/\.meta$//;
1.745     raeburn  10723:     if (defined($file)) {
1.749     raeburn  10724:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10725:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10726:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10727:             }
                   10728:         }
1.745     raeburn  10729:     } else {
1.749     raeburn  10730:         foreach my $key (keys(%{$current_permissions})) {
                   10731:             if ($key =~ /\0accesscontrol$/) {
                   10732:                 if (defined($group)) {
                   10733:                     if ($key !~ m-^\Q$group\E/-) {
                   10734:                         next;
                   10735:                     }
                   10736:                 }
                   10737:                 my ($fullpath) = split(/\0/,$key);
                   10738:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10739:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10740:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10741:                     }
                   10742:                 }
                   10743:             }
                   10744:         }
                   10745:     }
                   10746:     return %access;
                   10747: }
                   10748: 
                   10749: sub modify_access_controls {
                   10750:     my ($file_name,$changes,$domain,$user)=@_;
                   10751:     my ($outcome,$deloutcome);
                   10752:     my %store_permissions;
                   10753:     my %new_values;
                   10754:     my %new_control;
                   10755:     my %translation;
                   10756:     my @deletions = ();
                   10757:     my $now = time;
                   10758:     if (exists($$changes{'activate'})) {
                   10759:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10760:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10761:             my $numnew = scalar(@newitems);
                   10762:             for (my $i=0; $i<$numnew; $i++) {
                   10763:                 my $newkey = $newitems[$i];
                   10764:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10765:                 if ($newkey =~ /^\d+:/) { 
                   10766:                     $newkey =~ s/^(\d+)/$newid/;
                   10767:                     $translation{$1} = $newid;
                   10768:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10769:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10770:                     $translation{$1} = $newid;
                   10771:                 }
1.749     raeburn  10772:                 $new_values{$file_name."\0".$newkey} = 
                   10773:                                           $$changes{'activate'}{$newitems[$i]};
                   10774:                 $new_control{$newkey} = $now;
                   10775:             }
                   10776:         }
                   10777:     }
                   10778:     my %todelete;
                   10779:     my %changed_items;
                   10780:     foreach my $action ('delete','update') {
                   10781:         if (exists($$changes{$action})) {
                   10782:             if (ref($$changes{$action}) eq 'HASH') {
                   10783:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10784:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10785:                     if ($action eq 'delete') { 
                   10786:                         $todelete{$itemnum} = 1;
                   10787:                     } else {
                   10788:                         $changed_items{$itemnum} = $key;
                   10789:                     }
                   10790:                 }
1.745     raeburn  10791:             }
                   10792:         }
1.749     raeburn  10793:     }
                   10794:     # get lock on access controls for file.
                   10795:     my $lockhash = {
                   10796:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10797:                                                        ':'.$env{'user.domain'},
                   10798:                    }; 
                   10799:     my $tries = 0;
                   10800:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10801:    
1.1172.2.79  raeburn  10802:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10803:         $tries ++;
1.1172.2.79  raeburn  10804:         sleep(0.1);
1.749     raeburn  10805:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10806:     }
                   10807:     if ($gotlock eq 'ok') {
                   10808:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10809:         my ($tmp)=keys(%curr_permissions);
                   10810:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10811:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10812:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10813:             if (ref($curr_controls) eq 'HASH') {
                   10814:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10815:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10816:                     if (defined($todelete{$itemnum})) {
                   10817:                         push(@deletions,$file_name."\0".$control_item);
                   10818:                     } else {
                   10819:                         if (defined($changed_items{$itemnum})) {
                   10820:                             $new_control{$changed_items{$itemnum}} = $now;
                   10821:                             push(@deletions,$file_name."\0".$control_item);
                   10822:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10823:                         } else {
                   10824:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10825:                         }
                   10826:                     }
1.745     raeburn  10827:                 }
                   10828:             }
                   10829:         }
1.970     raeburn  10830:         my ($group);
                   10831:         if (&is_course($domain,$user)) {
                   10832:             ($group,my $file) = split(/\//,$file_name,2);
                   10833:         }
1.749     raeburn  10834:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10835:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10836:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10837:         #  remove lock
                   10838:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10839:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10840:         my $sqlresult =
1.970     raeburn  10841:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10842:                                     $group);
1.749     raeburn  10843:     } else {
                   10844:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10845:     }
1.749     raeburn  10846:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10847: }
                   10848: 
1.827     raeburn  10849: sub make_public_indefinitely {
                   10850:     my ($requrl) = @_;
                   10851:     my $now = time;
                   10852:     my $action = 'activate';
                   10853:     my $aclnum = 0;
                   10854:     if (&is_portfolio_url($requrl)) {
                   10855:         my (undef,$udom,$unum,$file_name,$group) =
                   10856:             &parse_portfolio_url($requrl);
                   10857:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10858:         my %access_controls = &get_access_controls($current_perms,
                   10859:                                                    $group,$file_name);
                   10860:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10861:             my ($num,$scope,$end,$start) = 
                   10862:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10863:             if ($scope eq 'public') {
                   10864:                 if ($start <= $now && $end == 0) {
                   10865:                     $action = 'none';
                   10866:                 } else {
                   10867:                     $action = 'update';
                   10868:                     $aclnum = $num;
                   10869:                 }
                   10870:                 last;
                   10871:             }
                   10872:         }
                   10873:         if ($action eq 'none') {
                   10874:              return 'ok';
                   10875:         } else {
                   10876:             my %changes;
                   10877:             my $newend = 0;
                   10878:             my $newstart = $now;
                   10879:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10880:             $changes{$action}{$newkey} = {
                   10881:                 type => 'public',
                   10882:                 time => {
                   10883:                     start => $newstart,
                   10884:                     end   => $newend,
                   10885:                 },
                   10886:             };
                   10887:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10888:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10889:             return $outcome;
                   10890:         }
                   10891:     } else {
                   10892:         return 'invalid';
                   10893:     }
                   10894: }
                   10895: 
1.745     raeburn  10896: #------------------------------------------------------Get Marked as Read Only
                   10897: 
                   10898: sub get_marked_as_readonly {
                   10899:     my ($domain,$user,$what,$group) = @_;
                   10900:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10901:     my @readonly_files;
1.629     banghart 10902:     my $cmp1=$what;
                   10903:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10904:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10905:         if (defined($group)) {
                   10906:             if ($file_name !~ m-^\Q$group\E/-) {
                   10907:                 next;
                   10908:             }
                   10909:         }
1.561     banghart 10910:         if (ref($value) eq "ARRAY"){
                   10911:             foreach my $stored_what (@{$value}) {
1.629     banghart 10912:                 my $cmp2=$stored_what;
1.759     albertel 10913:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10914:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10915:                 }
1.629     banghart 10916:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10917:                     push(@readonly_files, $file_name);
1.745     raeburn  10918:                     last;
1.563     banghart 10919:                 } elsif (!defined($what)) {
                   10920:                     push(@readonly_files, $file_name);
1.745     raeburn  10921:                     last;
1.561     banghart 10922:                 }
                   10923:             }
1.745     raeburn  10924:         }
1.561     banghart 10925:     }
                   10926:     return @readonly_files;
                   10927: }
1.577     banghart 10928: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10929: 
1.577     banghart 10930: sub get_marked_as_readonly_hash {
1.745     raeburn  10931:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10932:     my %readonly_files;
1.745     raeburn  10933:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10934:         if (defined($group)) {
                   10935:             if ($file_name !~ m-^\Q$group\E/-) {
                   10936:                 next;
                   10937:             }
                   10938:         }
1.577     banghart 10939:         if (ref($value) eq "ARRAY"){
                   10940:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10941:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10942:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10943:                         if ($lock_descriptor eq 'graded') {
                   10944:                             $readonly_files{$file_name} = 'graded';
                   10945:                         } elsif ($lock_descriptor eq 'handback') {
                   10946:                             $readonly_files{$file_name} = 'handback';
                   10947:                         } else {
                   10948:                             if (!exists($readonly_files{$file_name})) {
                   10949:                                 $readonly_files{$file_name} = 'locked';
                   10950:                             }
                   10951:                         }
1.745     raeburn  10952:                     }
1.750     banghart 10953:                 } 
1.577     banghart 10954:             }
                   10955:         } 
                   10956:     }
                   10957:     return %readonly_files;
                   10958: }
1.559     banghart 10959: # ------------------------------------------------------------ Unmark as Read Only
                   10960: 
                   10961: sub unmark_as_readonly {
1.629     banghart 10962:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10963:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10964:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10965:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10966:     my $symb_crs = $what;
                   10967:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10968:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10969:     my ($tmp)=keys(%current_permissions);
                   10970:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10971:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10972:     foreach my $file (@readonly_files) {
1.759     albertel 10973: 	my $clean_file = &declutter_portfile($file);
                   10974: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10975: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10976:         my @new_locks;
                   10977:         my @del_keys;
                   10978:         if (ref($current_locks) eq "ARRAY"){
                   10979:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10980:                 my $compare=$locker;
1.749     raeburn  10981:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10982:                     $compare=join('',@{$locker});
1.746     raeburn  10983:                     if ($compare ne $symb_crs) {
                   10984:                         push(@new_locks, $locker);
                   10985:                     }
1.563     banghart 10986:                 }
                   10987:             }
1.650     albertel 10988:             if (scalar(@new_locks) > 0) {
1.563     banghart 10989:                 $current_permissions{$file} = \@new_locks;
                   10990:             } else {
                   10991:                 push(@del_keys, $file);
1.613     albertel 10992:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10993:                 delete($current_permissions{$file});
1.563     banghart 10994:             }
                   10995:         }
1.561     banghart 10996:     }
1.613     albertel 10997:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10998:     return;
                   10999: }
1.512     banghart 11000: 
1.17      www      11001: # ------------------------------------------------------------ Directory lister
                   11002: 
                   11003: sub dirlist {
1.955     raeburn  11004:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11005:     $uri=~s/^\///;
                   11006:     $uri=~s/\/$//;
1.253     stredwic 11007:     my ($udom, $uname);
1.955     raeburn  11008:     if ($getuserdir) {
1.253     stredwic 11009:         $udom = $userdomain;
                   11010:         $uname = $username;
1.955     raeburn  11011:     } else {
                   11012:         (undef,$udom,$uname)=split(/\//,$uri);
                   11013:         if(defined($userdomain)) {
                   11014:             $udom = $userdomain;
                   11015:         }
                   11016:         if(defined($username)) {
                   11017:             $uname = $username;
                   11018:         }
1.253     stredwic 11019:     }
1.955     raeburn  11020:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11021: 
1.955     raeburn  11022:     $dirRoot = $perlvar{'lonDocRoot'};
                   11023:     if (defined($getpropath)) {
                   11024:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11025:         $dirRoot =~ s/\/$//;
1.955     raeburn  11026:     } elsif (defined($getuserdir)) {
                   11027:         my $subdir=$uname.'__';
                   11028:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11029:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11030:                    ."/$udom/$subdir/$uname";
                   11031:     } elsif (defined($alternateRoot)) {
                   11032:         $dirRoot = $alternateRoot;
1.751     banghart 11033:     }
1.253     stredwic 11034: 
                   11035:     if($udom) {
                   11036:         if($uname) {
1.1135    raeburn  11037:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11038:             if ($uhome eq 'no_host') {
                   11039:                 return ([],'no_host');
                   11040:             }
1.955     raeburn  11041:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11042:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11043:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11044:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11045:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11046:             } else {
                   11047:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11048:             }
1.605     matthew  11049:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11050:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11051:                 @listing_results = split(/:/,$listing);
                   11052:             } else {
                   11053:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11054:             }
1.1135    raeburn  11055:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11056:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11057:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11058:                 return ([],$listing);
                   11059:             } else {
                   11060:                 return (\@listing_results);
1.1135    raeburn  11061:             }
1.955     raeburn  11062:         } elsif(!$alternateRoot) {
1.1136    raeburn  11063:             my (%allusers,%listerror);
1.841     albertel 11064: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11065:  	    foreach my $tryserver (keys(%servers)) {
                   11066:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11067:                                   &escape($udom),$tryserver);
                   11068:                 if ($listing eq 'unknown_cmd') {
                   11069: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11070: 				      $udom, $tryserver);
                   11071:                 } else {
                   11072:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11073:                 }
1.841     albertel 11074: 		if ($listing eq 'unknown_cmd') {
                   11075: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11076: 				      $udom, $tryserver);
                   11077: 		    @listing_results = split(/:/,$listing);
                   11078: 		} else {
                   11079: 		    @listing_results =
                   11080: 			map { &unescape($_); } split(/:/,$listing);
                   11081: 		}
1.1136    raeburn  11082:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11083:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11084:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11085:                     $listerror{$tryserver} = $listing;
                   11086:                 } else {
1.841     albertel 11087: 		    foreach my $line (@listing_results) {
                   11088: 			my ($entry) = split(/&/,$line,2);
                   11089: 			$allusers{$entry} = 1;
                   11090: 		    }
                   11091: 		}
1.253     stredwic 11092:             }
1.1136    raeburn  11093:             my @alluserslist=();
1.800     albertel 11094:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11095:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11096:             }
1.1172.2.80  raeburn  11097:             if (!%listerror) {
                   11098:                 # no errors
                   11099:                 return (\@alluserslist);
                   11100:             } elsif (scalar(keys(%servers)) == 1) {
                   11101:                 # one library server, one error
                   11102:                 my ($key) = keys(%listerror);
                   11103:                 return (\@alluserslist, $listerror{$key});
                   11104:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11105:                 # con_lost indicates that we might miss data from at least one
                   11106:                 # library server
                   11107:                 return (\@alluserslist, 'con_lost');
                   11108:             } else {
                   11109:                 # multiple library servers and no con_lost -> data should be
                   11110:                 # complete.
                   11111:                 return (\@alluserslist);
                   11112:             }
                   11113: 
1.253     stredwic 11114:         } else {
1.1136    raeburn  11115:             return ([],'missing username');
1.253     stredwic 11116:         }
1.955     raeburn  11117:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11118:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11119:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11120:         return (\@all_domains);
1.955     raeburn  11121:     } else {
1.1136    raeburn  11122:         return ([],'missing domain');
1.275     stredwic 11123:     }
                   11124: }
                   11125: 
                   11126: # --------------------------------------------- GetFileTimestamp
                   11127: # This function utilizes dirlist and returns the date stamp for
                   11128: # when it was last modified.  It will also return an error of -1
                   11129: # if an error occurs
                   11130: 
                   11131: sub GetFileTimestamp {
1.955     raeburn  11132:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11133:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11134:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11135:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11136:                                     undef,$getuserdir);
                   11137:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11138:         return -1;
                   11139:     }
                   11140:     if (ref($fileref) eq 'ARRAY') {
                   11141:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11142:         # @stats contains first the filename, then the stat output
                   11143:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11144:     } else {
                   11145:         return -1;
1.253     stredwic 11146:     }
1.26      www      11147: }
                   11148: 
1.712     albertel 11149: sub stat_file {
                   11150:     my ($uri) = @_;
1.787     albertel 11151:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11152: 
1.955     raeburn  11153:     my ($udom,$uname,$file);
1.712     albertel 11154:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11155: 	($udom,$uname,$file) =
1.811     albertel 11156: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11157: 	$file = 'userfiles/'.$file;
                   11158:     }
                   11159:     if ($uri =~ m-^/res/-) {
                   11160: 	($udom,$uname) = 
1.807     albertel 11161: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11162: 	$file = $uri;
                   11163:     }
                   11164: 
                   11165:     if (!$udom || !$uname || !$file) {
                   11166: 	# unable to handle the uri
                   11167: 	return ();
                   11168:     }
1.956     raeburn  11169:     my $getpropath;
                   11170:     if ($file =~ /^userfiles\//) {
                   11171:         $getpropath = 1;
                   11172:     }
1.1136    raeburn  11173:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11174:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11175:         return ();
                   11176:     } else {
                   11177:         if (ref($listref) eq 'ARRAY') {
                   11178:             my @stats = split('&',$listref->[0]);
                   11179: 	    shift(@stats); #filename is first
                   11180: 	    return @stats;
                   11181:         }
1.712     albertel 11182:     }
                   11183:     return ();
                   11184: }
                   11185: 
1.26      www      11186: # -------------------------------------------------------- Value of a Condition
                   11187: 
1.713     albertel 11188: # gets the value of a specific preevaluated condition
                   11189: #    stored in the string  $env{user.state.<cid>}
                   11190: # or looks up a condition reference in the bighash and if if hasn't
                   11191: # already been evaluated recurses into docondval to get the value of
                   11192: # the condition, then memoizing it to 
                   11193: #   $env{user.state.<cid>.<condition>}
1.40      www      11194: sub directcondval {
                   11195:     my $number=shift;
1.620     albertel 11196:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11197: 	&Apache::lonuserstate::evalstate();
                   11198:     }
1.713     albertel 11199:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11200: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11201:     } elsif ($number =~ /^_/) {
                   11202: 	my $sub_condition;
                   11203: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11204: 		&GDBM_READER(),0640)) {
                   11205: 	    $sub_condition=$bighash{'conditions'.$number};
                   11206: 	    untie(%bighash);
                   11207: 	}
                   11208: 	my $value = &docondval($sub_condition);
1.949     raeburn  11209: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11210: 	return $value;
                   11211:     }
1.620     albertel 11212:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11213:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11214:     } else {
                   11215:        return 2;
                   11216:     }
                   11217: }
                   11218: 
1.713     albertel 11219: # get the collection of conditions for this resource
1.26      www      11220: sub condval {
                   11221:     my $condidx=shift;
1.54      www      11222:     my $allpathcond='';
1.713     albertel 11223:     foreach my $cond (split(/\|/,$condidx)) {
                   11224: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11225: 	    $allpathcond.=
                   11226: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11227: 	}
1.191     harris41 11228:     }
1.54      www      11229:     $allpathcond=~s/\|$//;
1.713     albertel 11230:     return &docondval($allpathcond);
                   11231: }
                   11232: 
                   11233: #evaluates an expression of conditions
                   11234: sub docondval {
                   11235:     my ($allpathcond) = @_;
                   11236:     my $result=0;
                   11237:     if ($env{'request.course.id'}
                   11238: 	&& defined($allpathcond)) {
                   11239: 	my $operand='|';
                   11240: 	my @stack;
                   11241: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11242: 	    if ($chunk eq '(') {
                   11243: 		push @stack,($operand,$result);
                   11244: 	    } elsif ($chunk eq ')') {
                   11245: 		my $before=pop @stack;
                   11246: 		if (pop @stack eq '&') {
                   11247: 		    $result=$result>$before?$before:$result;
                   11248: 		} else {
                   11249: 		    $result=$result>$before?$result:$before;
                   11250: 		}
                   11251: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11252: 		$operand=$chunk;
                   11253: 	    } else {
                   11254: 		my $new=directcondval($chunk);
                   11255: 		if ($operand eq '&') {
                   11256: 		    $result=$result>$new?$new:$result;
                   11257: 		} else {
                   11258: 		    $result=$result>$new?$result:$new;
                   11259: 		}
                   11260: 	    }
                   11261: 	}
1.26      www      11262:     }
                   11263:     return $result;
1.421     albertel 11264: }
                   11265: 
                   11266: # ---------------------------------------------------- Devalidate courseresdata
                   11267: 
                   11268: sub devalidatecourseresdata {
                   11269:     my ($coursenum,$coursedomain)=@_;
                   11270:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11271:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11272: }
                   11273: 
1.763     www      11274: 
1.200     www      11275: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11276: #
                   11277: #  Parameters:
                   11278: #      $coursenum    - Number of the course.
                   11279: #      $coursedomain - Domain at which the course was created.
                   11280: #  Returns:
                   11281: #     A hash of the course parameters along (I think) with timestamps
                   11282: #     and version info.
1.877     foxr     11283: 
1.624     albertel 11284: sub get_courseresdata {
                   11285:     my ($coursenum,$coursedomain)=@_;
1.200     www      11286:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11287:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11288:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11289:     my %dumpreply;
1.417     albertel 11290:     unless (defined($cached)) {
1.624     albertel 11291: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11292: 	$result=\%dumpreply;
1.251     albertel 11293: 	my ($tmp) = keys(%dumpreply);
                   11294: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11295: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11296: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11297: 	    return $tmp;
1.416     albertel 11298: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11299: 	    $result=undef;
1.599     albertel 11300: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11301: 	}
                   11302:     }
1.624     albertel 11303:     return $result;
                   11304: }
                   11305: 
1.633     albertel 11306: sub devalidateuserresdata {
                   11307:     my ($uname,$udom)=@_;
                   11308:     my $hashid="$udom:$uname";
                   11309:     &devalidate_cache_new('userres',$hashid);
                   11310: }
                   11311: 
1.624     albertel 11312: sub get_userresdata {
                   11313:     my ($uname,$udom)=@_;
                   11314:     #most student don\'t have any data set, check if there is some data
                   11315:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11316: 
                   11317:     my $hashid="$udom:$uname";
                   11318:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11319:     if (!defined($cached)) {
                   11320: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11321: 	$result=\%resourcedata;
                   11322: 	&do_cache_new('userres',$hashid,$result,600);
                   11323:     }
                   11324:     my ($tmp)=keys(%$result);
                   11325:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11326: 	return $result;
                   11327:     }
                   11328:     #error 2 occurs when the .db doesn't exist
                   11329:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11330:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11331: 	    &logthis("<font color=\"blue\">WARNING:".
                   11332: 		     " Trying to get resource data for ".
                   11333: 		     $uname." at ".$udom.": ".
                   11334: 		     $tmp."</font>");
                   11335:         }
1.624     albertel 11336:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11337: 	#&EXT_cache_set($udom,$uname);
                   11338: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11339: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11340:     }
                   11341:     return $tmp;
                   11342: }
1.879     foxr     11343: #----------------------------------------------- resdata - return resource data
                   11344: #  Purpose:
                   11345: #    Return resource data for either users or for a course.
                   11346: #  Parameters:
                   11347: #     $name      - Course/user name.
                   11348: #     $domain    - Name of the domain the user/course is registered on.
1.1172.2.118.  .1(raebu 11349:20): #     $type      - Type of thing $name is (must be 'course' or 'user')
1.879     foxr     11350: #     @which     - Array of names of resources desired.
                   11351: #  Returns:
                   11352: #     The value of the first reasource in @which that is found in the
                   11353: #     resource hash.
                   11354: #  Exceptional Conditions:
                   11355: #     If the $type passed in is not valid (not the string 'course' or 
                   11356: #     'user', an undefined  reference is returned.
                   11357: #     If none of the resources are found, an undef is returned
1.624     albertel 11358: sub resdata {
                   11359:     my ($name,$domain,$type,@which)=@_;
                   11360:     my $result;
                   11361:     if ($type eq 'course') {
                   11362: 	$result=&get_courseresdata($name,$domain);
                   11363:     } elsif ($type eq 'user') {
                   11364: 	$result=&get_userresdata($name,$domain);
                   11365:     }
                   11366:     if (!ref($result)) { return $result; }    
1.251     albertel 11367:     foreach my $item (@which) {
1.1172.2.118.  .8(raebu 11368:20): 	if (defined($result->{$item->[0]})) {
                   11369:20): 	    return [$result->{$item->[0]},$item->[1]];
          .1(raebu 11370:20):         }
1.250     albertel 11371:     }
1.291     albertel 11372:     return undef;
1.200     www      11373: }
                   11374: 
1.1172.2.118.  .10(raeb 11375:-20): sub get_domain_lti {
                   11376:-20):     my ($cdom,$context) = @_;
                   11377:-20):     my ($name,%lti);
                   11378:-20):     if ($context eq 'consumer') {
                   11379:-20):         $name = 'ltitools';
                   11380:-20):     } elsif ($context eq 'provider') {
                   11381:-20):         $name = 'lti';
                   11382:-20):     } else {
                   11383:-20):         return %lti;
                   11384:-20):     }
                   11385:-20):     my ($result,$cached)=&is_cached_new($name,$cdom);
          .1(raebu 11386:20):     if (defined($cached)) {
                   11387:20):         if (ref($result) eq 'HASH') {
          .10(raeb 11388:-20):             %lti = %{$result};
          .1(raebu 11389:20):         }
                   11390:20):     } else {
          .10(raeb 11391:-20):         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   11392:-20):         if (ref($domconfig{$name}) eq 'HASH') {
                   11393:-20):             %lti = %{$domconfig{$name}};
                   11394:-20):             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
                   11395:-20):             if (ref($encdomconfig{$name}) eq 'HASH') {
                   11396:-20):                 foreach my $id (keys(%lti)) {
                   11397:-20):                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
          .1(raebu 11398:20):                         foreach my $item ('key','secret') {
          .10(raeb 11399:-20):                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
          .1(raebu 11400:20):                         }
                   11401:20):                     }
                   11402:20):                 }
                   11403:20):             }
                   11404:20):         }
                   11405:20):         my $cachetime = 24*60*60;
          .10(raeb 11406:-20):         &do_cache_new($name,$cdom,\%lti,$cachetime);
          .1(raebu 11407:20):     }
          .10(raeb 11408:-20):     return %lti;
          .1(raebu 11409:20): }
                   11410:20): 
1.1172.2.31  raeburn  11411: sub get_numsuppfiles {
                   11412:     my ($cnum,$cdom,$ignorecache)=@_;
                   11413:     my $hashid=$cnum.':'.$cdom;
                   11414:     my ($suppcount,$cached);
                   11415:     unless ($ignorecache) {
                   11416:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11417:     }
                   11418:     unless (defined($cached)) {
                   11419:         my $chome=&homeserver($cnum,$cdom);
                   11420:         unless ($chome eq 'no_host') {
                   11421:             ($suppcount,my $errors) = (0,0);
                   11422:             my $suppmap = 'supplemental.sequence';
                   11423:             ($suppcount,$errors) =
                   11424:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11425:         }
                   11426:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11427:     }
                   11428:     return $suppcount;
                   11429: }
                   11430: 
1.379     matthew  11431: #
                   11432: # EXT resource caching routines
                   11433: #
                   11434: 
                   11435: sub clear_EXT_cache_status {
1.383     albertel 11436:     &delenv('cache.EXT.');
1.379     matthew  11437: }
                   11438: 
                   11439: sub EXT_cache_status {
                   11440:     my ($target_domain,$target_user) = @_;
1.383     albertel 11441:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11442:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11443:         # We know already the user has no data
                   11444:         return 1;
                   11445:     } else {
                   11446:         return 0;
                   11447:     }
                   11448: }
                   11449: 
                   11450: sub EXT_cache_set {
                   11451:     my ($target_domain,$target_user) = @_;
1.383     albertel 11452:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11453:     #&appenv({$cachename => time});
1.379     matthew  11454: }
                   11455: 
1.28      www      11456: # --------------------------------------------------------- Value of a Variable
1.58      www      11457: sub EXT {
1.715     albertel 11458: 
1.1172.2.28  raeburn  11459:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11460:     unless ($varname) { return ''; }
1.218     albertel 11461:     #get real user name/domain, courseid and symb
                   11462:     my $courseid;
1.359     albertel 11463:     my $publicuser;
1.427     www      11464:     if ($symbparm) {
                   11465: 	$symbparm=&get_symb_from_alias($symbparm);
                   11466:     }
1.218     albertel 11467:     if (!($uname && $udom)) {
1.790     albertel 11468:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11469:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11470:     } else {
1.620     albertel 11471: 	$courseid=$env{'request.course.id'};
1.218     albertel 11472:     }
1.48      www      11473:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11474:     my $rest;
1.320     albertel 11475:     if (defined($therest[0])) {
1.48      www      11476:        $rest=join('.',@therest);
                   11477:     } else {
                   11478:        $rest='';
                   11479:     }
1.320     albertel 11480: 
1.57      www      11481:     my $qualifierrest=$qualifier;
                   11482:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11483:     my $spacequalifierrest=$space;
                   11484:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11485:     if ($realm eq 'user') {
1.48      www      11486: # --------------------------------------------------------------- user.resource
                   11487: 	if ($space eq 'resource') {
1.651     albertel 11488: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11489: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11490: 		 &&
1.744     albertel 11491: 		 ($symbparm eq &symbread()) ) {	
                   11492: 		# if we are in the middle of processing the resource the
                   11493: 		# get the value we are planning on committing
                   11494:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11495:                     return $Apache::lonhomework::results{$qualifierrest};
                   11496:                 } else {
                   11497:                     return $Apache::lonhomework::history{$qualifierrest};
                   11498:                 }
1.335     albertel 11499: 	    } else {
1.359     albertel 11500: 		my %restored;
1.620     albertel 11501: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11502: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11503: 		} else {
                   11504: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11505: 		}
1.335     albertel 11506: 		return $restored{$qualifierrest};
                   11507: 	    }
1.48      www      11508: # ----------------------------------------------------------------- user.access
                   11509:         } elsif ($space eq 'access') {
1.218     albertel 11510: 	    # FIXME - not supporting calls for a specific user
1.48      www      11511:             return &allowed($qualifier,$rest);
                   11512: # ------------------------------------------ user.preferences, user.environment
                   11513:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11514: 	    if (($uname eq $env{'user.name'}) &&
                   11515: 		($udom eq $env{'user.domain'})) {
                   11516: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11517: 	    } else {
1.359     albertel 11518: 		my %returnhash;
                   11519: 		if (!$publicuser) {
                   11520: 		    %returnhash=&userenvironment($udom,$uname,
                   11521: 						 $qualifierrest);
                   11522: 		}
1.218     albertel 11523: 		return $returnhash{$qualifierrest};
                   11524: 	    }
1.48      www      11525: # ----------------------------------------------------------------- user.course
                   11526:         } elsif ($space eq 'course') {
1.218     albertel 11527: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11528:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11529: # ------------------------------------------------------------------- user.role
                   11530:         } elsif ($space eq 'role') {
1.218     albertel 11531: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11532:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11533:             if ($qualifier eq 'value') {
                   11534: 		return $role;
                   11535:             } elsif ($qualifier eq 'extent') {
                   11536:                 return $where;
                   11537:             }
                   11538: # ----------------------------------------------------------------- user.domain
                   11539:         } elsif ($space eq 'domain') {
1.218     albertel 11540:             return $udom;
1.48      www      11541: # ------------------------------------------------------------------- user.name
                   11542:         } elsif ($space eq 'name') {
1.218     albertel 11543:             return $uname;
1.48      www      11544: # ---------------------------------------------------- Any other user namespace
1.29      www      11545:         } else {
1.359     albertel 11546: 	    my %reply;
                   11547: 	    if (!$publicuser) {
                   11548: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11549: 	    }
                   11550: 	    return $reply{$qualifierrest};
1.48      www      11551:         }
1.236     www      11552:     } elsif ($realm eq 'query') {
                   11553: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11554:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11555: 						[$spacequalifierrest]);
1.620     albertel 11556: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11557:    } elsif ($realm eq 'request') {
1.48      www      11558: # ------------------------------------------------------------- request.browser
                   11559:         if ($space eq 'browser') {
1.1145    bisitz   11560:             return $env{'browser.'.$qualifier};
1.57      www      11561: # ------------------------------------------------------------ request.filename
                   11562:         } else {
1.620     albertel 11563:             return $env{'request.'.$spacequalifierrest};
1.29      www      11564:         }
1.28      www      11565:     } elsif ($realm eq 'course') {
1.48      www      11566: # ---------------------------------------------------------- course.description
1.620     albertel 11567:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11568:     } elsif ($realm eq 'resource') {
1.165     www      11569: 
1.620     albertel 11570: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11571: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11572: 	}
1.693     albertel 11573: 
1.1172.2.30  raeburn  11574:         if ($qualifier eq '') {
                   11575: 	    if ($space eq 'title') {
                   11576: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11577: 	        return &gettitle($symbparm);
                   11578: 	    }
1.693     albertel 11579: 	
1.1172.2.30  raeburn  11580: 	    if ($space eq 'map') {
                   11581: 	        my ($map) = &decode_symb($symbparm);
                   11582: 	        return &symbread($map);
                   11583: 	    }
                   11584:             if ($space eq 'maptitle') {
                   11585:                 my ($map) = &decode_symb($symbparm);
                   11586:                 return &gettitle($map);
                   11587:             }
                   11588: 	    if ($space eq 'filename') {
                   11589: 	        if ($symbparm) {
                   11590: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11591: 	        }
                   11592: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11593: 	    }
1.1172.2.30  raeburn  11594: 
                   11595:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11596:                 if ($space eq 'visibleparts') {
                   11597:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11598:                     my $item;
                   11599:                     if (ref($navmap)) {
                   11600:                         my $res = $navmap->getBySymb($symbparm);
                   11601:                         my $parts = $res->parts();
                   11602:                         if (ref($parts) eq 'ARRAY') {
                   11603:                             $item = join(',',@{$parts});
                   11604:                         }
                   11605:                         undef($navmap);
                   11606:                     }
                   11607:                     return $item;
                   11608:                 }
                   11609:             }
                   11610:         }
1.693     albertel 11611: 
                   11612: 	my ($section, $group, @groups);
1.593     albertel 11613: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  11614:         if (($courseid eq '') && ($cid)) {
                   11615:             $courseid = $cid;
                   11616:         }
                   11617: 	if (($symbparm && $courseid) && 
                   11618: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      11619: 
1.218     albertel 11620: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11621: 
1.60      www      11622: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11623: 	    my $symbp=$symbparm;
1.735     albertel 11624: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11625: 
                   11626: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   11627: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   11628: 
1.620     albertel 11629: 	    if (($env{'user.name'} eq $uname) &&
                   11630: 		($env{'user.domain'} eq $udom)) {
                   11631: 		$section=$env{'request.course.sec'};
1.733     raeburn  11632:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11633:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11634: 	    } else {
1.539     albertel 11635: 		if (! defined($usection)) {
1.551     albertel 11636: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11637: 		} else {
                   11638: 		    $section = $usection;
                   11639: 		}
1.733     raeburn  11640:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11641: 	    }
                   11642: 
                   11643: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11644: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   11645: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11646: 
1.593     albertel 11647: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11648: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 11649: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11650: 
1.60      www      11651: # ----------------------------------------------------------- first, check user
1.624     albertel 11652: 
                   11653: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 11654: 				       ([$courselevelr,'resource'],
                   11655: 					[$courselevelm,'map'     ],
                   11656: 					[$courselevel, 'course'  ]));
1.931     albertel 11657: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11658: 
1.594     albertel 11659: # ------------------------------------------------ second, check some of course
1.684     raeburn  11660:             my $coursereply;
1.691     raeburn  11661:             if (@groups > 0) {
                   11662:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   11663:                                        $mapparm,$spacequalifierrest);
1.927     albertel 11664:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  11665:             }
1.96      www      11666: 
1.684     raeburn  11667: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11668: 				  $env{'course.'.$courseid.'.domain'},
                   11669: 				  'course',
                   11670: 				  ([$seclevelr,   'resource'],
                   11671: 				   [$seclevelm,   'map'     ],
                   11672: 				   [$seclevel,    'course'  ],
                   11673: 				   [$courselevelr,'resource']));
                   11674: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11675: 
1.60      www      11676: # ------------------------------------------------------ third, check map parms
1.218     albertel 11677: 	    my %parmhash=();
                   11678: 	    my $thisparm='';
                   11679: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11680: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11681: 		    &GDBM_READER(),0640)) {
1.218     albertel 11682: 		$thisparm=$parmhash{$symbparm};
                   11683: 		untie(%parmhash);
                   11684: 	    }
1.927     albertel 11685: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11686: 	}
1.594     albertel 11687: # ------------------------------------------ fourth, look in resource metadata
1.71      www      11688: 
1.218     albertel 11689: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 11690: 	my $filename;
                   11691: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11692: 	if ($symbparm) {
1.409     www      11693: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11694: 	} else {
1.620     albertel 11695: 	    $filename=$env{'request.filename'};
1.282     albertel 11696: 	}
                   11697: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 11698: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 11699: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 11700: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11701: 
1.927     albertel 11702: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 11703: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11704: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11705: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11706: 				     $env{'course.'.$courseid.'.domain'},
                   11707: 				     'course',
1.927     albertel 11708: 				     ([$courselevelm,'map'   ],
                   11709: 				      [$courselevel, 'course']));
                   11710: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11711: 	}
1.145     www      11712: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11713: 	unless ($space eq '0') {
1.336     albertel 11714: 	    my @parts=split(/_/,$space);
                   11715: 	    my $id=pop(@parts);
                   11716: 	    my $part=join('_',@parts);
                   11717: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11718: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11719: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11720: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11721: 	}
1.395     albertel 11722: 	if ($recurse) { return undef; }
                   11723: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11724: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11725: # ---------------------------------------------------- Any other user namespace
                   11726:     } elsif ($realm eq 'environment') {
                   11727: # ----------------------------------------------------------------- environment
1.620     albertel 11728: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11729: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11730: 	} else {
1.770     albertel 11731: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11732: 		return '';
                   11733: 	    }
1.219     albertel 11734: 	    my %returnhash=&userenvironment($udom,$uname,
                   11735: 					    $spacequalifierrest);
                   11736: 	    return $returnhash{$spacequalifierrest};
                   11737: 	}
1.28      www      11738:     } elsif ($realm eq 'system') {
1.48      www      11739: # ----------------------------------------------------------------- system.time
                   11740: 	if ($space eq 'time') {
                   11741: 	    return time;
                   11742:         }
1.696     albertel 11743:     } elsif ($realm eq 'server') {
                   11744: # ----------------------------------------------------------------- system.time
                   11745: 	if ($space eq 'name') {
                   11746: 	    return $ENV{'SERVER_NAME'};
                   11747:         }
1.28      www      11748:     }
1.48      www      11749:     return '';
1.61      www      11750: }
                   11751: 
1.927     albertel 11752: sub get_reply {
                   11753:     my ($reply_value) = @_;
1.940     raeburn  11754:     if (ref($reply_value) eq 'ARRAY') {
                   11755:         if (wantarray) {
                   11756: 	    return @$reply_value;
                   11757:         }
                   11758:         return $reply_value->[0];
                   11759:     } else {
                   11760:         return $reply_value;
1.927     albertel 11761:     }
                   11762: }
                   11763: 
1.691     raeburn  11764: sub check_group_parms {
                   11765:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11766:     my @groupitems = ();
                   11767:     my $resultitem;
1.927     albertel 11768:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11769:     foreach my $group (@{$groups}) {
                   11770:         foreach my $level (@levels) {
1.927     albertel 11771:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11772:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11773:         }
                   11774:     }
                   11775:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11776:                             $env{'course.'.$courseid.'.domain'},
                   11777:                                      'course',@groupitems);
                   11778:     return $coursereply;
                   11779: }
                   11780: 
                   11781: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11782:     my ($courseid,@groups) = @_;
                   11783:     @groups = sort(@groups);
1.691     raeburn  11784:     return @groups;
                   11785: }
                   11786: 
1.395     albertel 11787: sub packages_tab_default {
                   11788:     my ($uri,$varname)=@_;
                   11789:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11790: 
                   11791:     my (@extension,@specifics,$do_default);
                   11792:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11793: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11794: 	if ($pack_type eq 'default') {
                   11795: 	    $do_default=1;
                   11796: 	} elsif ($pack_type eq 'extension') {
                   11797: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11798: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11799: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11800: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11801: 	}
                   11802:     }
                   11803:     # first look for a package that matches the requested part id
                   11804:     foreach my $package (@specifics) {
                   11805: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11806: 	next if ($pack_part ne $part);
                   11807: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11808: 	    return $packagetab{"$pack_type&$name&default"};
                   11809: 	}
                   11810:     }
                   11811:     # look for any possible matching non extension_ package
                   11812:     foreach my $package (@specifics) {
                   11813: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11814: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11815: 	    return $packagetab{"$pack_type&$name&default"};
                   11816: 	}
1.585     albertel 11817: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11818: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11819: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11820: 	}
                   11821:     }
1.738     albertel 11822:     # look for any posible extension_ match
                   11823:     foreach my $package (@extension) {
                   11824: 	my ($package,$pack_type)=@{$package};
                   11825: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11826: 	    return $packagetab{"$pack_type&$name&default"};
                   11827: 	}
                   11828: 	if (defined($packagetab{$package."&$name&default"})) {
                   11829: 	    return $packagetab{$package."&$name&default"};
                   11830: 	}
                   11831:     }
                   11832:     # look for a global default setting
                   11833:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11834: 	return $packagetab{"default&$name&default"};
                   11835:     }
1.395     albertel 11836:     return undef;
                   11837: }
                   11838: 
1.334     albertel 11839: sub add_prefix_and_part {
                   11840:     my ($prefix,$part)=@_;
                   11841:     my $keyroot;
                   11842:     if (defined($prefix) && $prefix !~ /^__/) {
                   11843: 	# prefix that has a part already
                   11844: 	$keyroot=$prefix;
                   11845:     } elsif (defined($prefix)) {
                   11846: 	# prefix that is missing a part
                   11847: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11848:     } else {
                   11849: 	# no prefix at all
                   11850: 	if (defined($part)) { $keyroot='_'.$part; }
                   11851:     }
                   11852:     return $keyroot;
                   11853: }
                   11854: 
1.71      www      11855: # ---------------------------------------------------------------- Get metadata
                   11856: 
1.599     albertel 11857: my %metaentry;
1.1070    www      11858: my %importedpartids;
1.1172.2.99  raeburn  11859: my %importedrespids;
1.71      www      11860: sub metadata {
1.176     www      11861:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11862:     $uri=&declutter($uri);
1.288     albertel 11863:     # if it is a non metadata possible uri return quickly
1.529     albertel 11864:     if (($uri eq '') || 
                   11865: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.118.  .1(raebu 11866:20): 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  11867:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11868: 	return undef;
                   11869:     }
1.1172.2.49  raeburn  11870:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11871: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11872: 	return undef;
1.288     albertel 11873:     }
1.73      www      11874:     my $filename=$uri;
                   11875:     $uri=~s/\.meta$//;
1.172     www      11876: #
                   11877: # Is the metadata already cached?
1.177     www      11878: # Look at timestamp of caching
1.172     www      11879: # Everything is cached by the main uri, libraries are never directly cached
                   11880: #
1.428     albertel 11881:     if (!defined($liburi)) {
1.599     albertel 11882: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11883: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11884:     }
                   11885:     {
1.1069    www      11886: # Imported parts would go here
1.1172.2.99  raeburn  11887:         my @origfiletagids=();
1.1069    www      11888:         my $importedparts=0;
1.1172.2.99  raeburn  11889: 
                   11890: # Imported responseids would go here
                   11891:         my $importedresponses=0;
1.172     www      11892: #
                   11893: # Is this a recursive call for a library?
                   11894: #
1.599     albertel 11895: #	if (! exists($metacache{$uri})) {
                   11896: #	    $metacache{$uri}={};
                   11897: #	}
1.924     albertel 11898: 	my $cachetime = 60*60;
1.171     www      11899:         if ($liburi) {
                   11900: 	    $liburi=&declutter($liburi);
                   11901:             $filename=$liburi;
1.401     bowersj2 11902:         } else {
1.599     albertel 11903: 	    &devalidate_cache_new('meta',$uri);
                   11904: 	    undef(%metaentry);
1.401     bowersj2 11905: 	}
1.140     www      11906:         my %metathesekeys=();
1.73      www      11907:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11908: 	my $metastring;
1.1140    www      11909: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11910: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11911: 	    $metastring = 
1.929     albertel 11912: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11913: 					  ('grade_target' => 'meta'));
                   11914: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11915: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11916:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11917: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11918: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11919: 	    $metastring=&getfile($file);
1.489     albertel 11920: 	}
1.208     albertel 11921:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11922:         my $token;
1.140     www      11923:         undef %metathesekeys;
1.71      www      11924:         while ($token=$parser->get_token) {
1.339     albertel 11925: 	    if ($token->[0] eq 'S') {
                   11926: 		if (defined($token->[2]->{'package'})) {
1.172     www      11927: #
                   11928: # This is a package - get package info
                   11929: #
1.339     albertel 11930: 		    my $package=$token->[2]->{'package'};
                   11931: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11932: 		    if (defined($token->[2]->{'id'})) { 
                   11933: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11934: 		    }
1.599     albertel 11935: 		    if ($metaentry{':packages'}) {
                   11936: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11937: 		    } else {
1.599     albertel 11938: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11939: 		    }
1.736     albertel 11940: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11941: 			my $part=$keyroot;
                   11942: 			$part=~s/^\_//;
1.736     albertel 11943: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11944: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11945: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11946: 			    # ignore package.tab specified default values
                   11947:                             # here &package_tab_default() will fetch those
                   11948: 			    if ($subp eq 'default') { next; }
1.736     albertel 11949: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11950: 			    my $unikey;
                   11951: 			    if ($pack =~ /_0$/) {
                   11952: 				$unikey='parameter_0_'.$name;
                   11953: 				$part=0;
                   11954: 			    } else {
                   11955: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11956: 			    }
1.339     albertel 11957: 			    if ($subp eq 'display') {
                   11958: 				$value.=' [Part: '.$part.']';
                   11959: 			    }
1.599     albertel 11960: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11961: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11962: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11963: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11964: 			    }
1.599     albertel 11965: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11966: 				$metaentry{':'.$unikey}=
                   11967: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11968: 			    }
1.339     albertel 11969: 			}
                   11970: 		    }
                   11971: 		} else {
1.172     www      11972: #
                   11973: # This is not a package - some other kind of start tag
1.339     albertel 11974: #
                   11975: 		    my $entry=$token->[1];
1.1068    www      11976: 		    my $unikey='';
1.175     www      11977: 
1.339     albertel 11978: 		    if ($entry eq 'import') {
1.175     www      11979: #
                   11980: # Importing a library here
1.339     albertel 11981: #
1.1067    www      11982:                         my $location=$parser->get_text('/import');
                   11983:                         my $dir=$filename;
                   11984:                         $dir=~s|[^/]*$||;
                   11985:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  11986: 
                   11987:                         my $importid=$token->[2]->{'id'};
1.1068    www      11988:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  11989: #
                   11990: # Check metadata for imported file to
                   11991: # see if it contained response items
                   11992: #
                   11993:                         my %currmetaentry = %metaentry;
                   11994:                         my $libresponseorder = &metadata($location,'responseorder');
                   11995:                         my $origfile;
                   11996:                         if ($libresponseorder ne '') {
                   11997:                             if ($#origfiletagids<0) {
                   11998:                                 undef(%importedrespids);
                   11999:                                 undef(%importedpartids);
                   12000:                             }
                   12001:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   12002:                             if (@{$importedrespids{$importid}} > 0) {
                   12003:                                 $importedresponses = 1;
                   12004: # We need to get the original file and the imported file to get the response order correct
                   12005: # Load and inspect original file
                   12006:                                 if ($#origfiletagids<0) {
                   12007:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12008:                                     $origfile=&getfile($origfilelocation);
                   12009:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12010:                                 }
                   12011:                             }
                   12012:                         }
                   12013: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12014: # hash populated for imported library file
                   12015:                         %metaentry = %currmetaentry;
                   12016:                         undef(%currmetaentry);
1.1068    www      12017:                         if ($importmode eq 'problem') {
1.1069    www      12018: # Import as problem/response
1.1068    www      12019:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12020:                         } elsif ($importmode eq 'part') {
                   12021: # Import as part(s)
1.1069    www      12022:                            $importedparts=1;
                   12023: # We need to get the original file and the imported file to get the part order correct
                   12024: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  12025: # Load and inspect original file if we didn't do that already
                   12026:                            if ($#origfiletagids<0) {
                   12027:                                undef(%importedrespids);
                   12028:                                undef(%importedpartids);
                   12029:                                if ($origfile eq '') {
                   12030:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12031:                                    $origfile=&getfile($origfilelocation);
                   12032:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12033:                                }
1.1070    www      12034:                            }
                   12035: 
1.1069    www      12036: # Load and inspect imported file
                   12037:                            my $impfile=&getfile($location);
                   12038:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12039:                            if ($#impfilepartids>=0) {
                   12040: # This problem had parts
1.1070    www      12041:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12042:                            } else {
                   12043: # Importing by turning a single problem into a problem part
                   12044: # It gets the import-tags ID as part-ID
                   12045:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12046:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12047:                            }
1.1068    www      12048:                         } else {
                   12049: # Normal import
                   12050:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12051:                            if (defined($token->[2]->{'id'})) {
                   12052:                               $unikey.='_'.$token->[2]->{'id'};
                   12053:                            }
1.1067    www      12054:                         }
                   12055: 
1.339     albertel 12056: 			if ($depthcount<20) {
1.736     albertel 12057: 			    my $metadata = 
                   12058: 				&metadata($uri,'keys', $location,$unikey,
                   12059: 					  $depthcount+1);
                   12060: 			    foreach my $meta (split(',',$metadata)) {
                   12061: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12062: 				$metathesekeys{$meta}=1;
1.339     albertel 12063: 			    }
1.1068    www      12064: 			
                   12065:                         }
1.1067    www      12066: 		    } else {
                   12067: #
                   12068: # Not importing, some other kind of non-package, non-library start tag
                   12069: # 
                   12070:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12071:                         if (defined($token->[2]->{'id'})) {
                   12072:                             $unikey.='_'.$token->[2]->{'id'};
                   12073:                         }
1.339     albertel 12074: 			if (defined($token->[2]->{'name'})) { 
                   12075: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12076: 			}
                   12077: 			$metathesekeys{$unikey}=1;
1.736     albertel 12078: 			foreach my $param (@{$token->[3]}) {
                   12079: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12080: 				$token->[2]->{$param};
1.339     albertel 12081: 			}
                   12082: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12083: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12084: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12085: 		 # only ws inside the tag, and not in default, so use default
                   12086: 		 # as value
1.599     albertel 12087: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12088: 			} elsif ( $internaltext =~ /\S/ ) {
                   12089: 		  # something interesting inside the tag
                   12090: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12091: 			} else {
1.908     albertel 12092: 		  # no interesting values, don't set a default
1.339     albertel 12093: 			}
1.172     www      12094: # end of not-a-package not-a-library import
1.339     albertel 12095: 		    }
1.172     www      12096: # end of not-a-package start tag
1.339     albertel 12097: 		}
1.172     www      12098: # the next is the end of "start tag"
1.339     albertel 12099: 	    }
                   12100: 	}
1.483     albertel 12101: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12102: 	$extension = lc($extension);
                   12103: 	if ($extension eq 'htm') { $extension='html'; }
                   12104: 
1.737     albertel 12105: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12106: 	    #no specific packages #how's our extension
                   12107: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12108: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12109: 					 \%metathesekeys);
                   12110: 	}
1.883     albertel 12111: 
                   12112: 	if (!exists($metaentry{':packages'})
                   12113: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12114: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12115: 		#no specific packages well let's get default then
                   12116: 		if ($key!~/^default&/) { next; }
1.488     albertel 12117: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12118: 					     \%metathesekeys);
                   12119: 	    }
                   12120: 	}
1.338     www      12121: # are there custom rights to evaluate
1.599     albertel 12122: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12123: 
1.338     www      12124:     #
                   12125:     # Importing a rights file here
1.339     albertel 12126:     #
                   12127: 	    unless ($depthcount) {
1.599     albertel 12128: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12129: 		my $dir=$filename;
                   12130: 		$dir=~s|[^/]*$||;
                   12131: 		$location=&filelocation($dir,$location);
1.736     albertel 12132: 		my $rights_metadata =
                   12133: 		    &metadata($uri,'keys',$location,'_rights',
                   12134: 			      $depthcount+1);
                   12135: 		foreach my $rights (split(',',$rights_metadata)) {
                   12136: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12137: 		    $metathesekeys{$rights}=1;
1.339     albertel 12138: 		}
                   12139: 	    }
                   12140: 	}
1.737     albertel 12141: 	# uniqifiy package listing
                   12142: 	my %seen;
                   12143: 	my @uniq_packages =
                   12144: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12145: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12146: 
1.1172.2.99  raeburn  12147:         if (($importedresponses) || ($importedparts)) {
                   12148:             if ($importedparts) {
1.1070    www      12149: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  12150:                 $metaentry{':partorder'}='';
                   12151:                 $metathesekeys{'partorder'}=1;
                   12152:             }
                   12153:             if ($importedresponses) {
                   12154: # We had imported responses and need to rebuild responseorder
                   12155:                 $metaentry{':responseorder'}='';
                   12156:                 $metathesekeys{'responseorder'}=1;
                   12157:             }
                   12158:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12159:                 my $origid = $origfiletagids[$index+1];
                   12160:                 if ($origfiletagids[$index] eq 'part') {
                   12161: # Original part, part of the problem
                   12162:                     if ($importedparts) {
                   12163:                         $metaentry{':partorder'}.=','.$origid;
                   12164:                     }
                   12165:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12166:                     if ($importedparts) {
                   12167: # We have imported parts at this position
                   12168:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12169:                     }
                   12170:                     if ($importedresponses) {
                   12171: # We have imported responses at this position
                   12172:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   12173:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   12174:                         }
                   12175:                     }
                   12176:                 } else {
                   12177: # Original response item, part of the problem
                   12178:                     if ($importedresponses) {
                   12179:                         $metaentry{':responseorder'}.=','.$origid;
                   12180:                     }
                   12181:                 }
                   12182:             }
                   12183:             if ($importedparts) {
                   12184:                 $metaentry{':partorder'}=~s/^\,//;
                   12185:             }
                   12186:             if ($importedresponses) {
                   12187:                 $metaentry{':responseorder'}=~s/^\,//;
                   12188:             }
1.1070    www      12189:         }
                   12190: 
1.737     albertel 12191: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12192: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  12193: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 12194: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      12195: # this is the end of "was not already recently cached
1.71      www      12196:     }
1.599     albertel 12197:     return $metaentry{':'.$what};
1.261     albertel 12198: }
                   12199: 
1.488     albertel 12200: sub metadata_create_package_def {
1.483     albertel 12201:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12202:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12203:     if ($subp eq 'default') { next; }
                   12204:     
1.599     albertel 12205:     if (defined($metaentry{':packages'})) {
                   12206: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12207:     } else {
1.599     albertel 12208: 	$metaentry{':packages'}=$package;
1.483     albertel 12209:     }
                   12210:     my $value=$packagetab{$key};
                   12211:     my $unikey;
                   12212:     $unikey='parameter_0_'.$name;
1.599     albertel 12213:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12214:     $$metathesekeys{$unikey}=1;
1.599     albertel 12215:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12216: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12217:     }
1.599     albertel 12218:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12219: 	$metaentry{':'.$unikey}=
                   12220: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12221:     }
                   12222: }
                   12223: 
1.261     albertel 12224: sub metadata_generate_part0 {
                   12225:     my ($metadata,$metacache,$uri) = @_;
                   12226:     my %allnames;
1.737     albertel 12227:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12228: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12229: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12230: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12231: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12232: 	    $allnames{$name}=$part;
                   12233: 	  }
                   12234: 	}
                   12235:     }
                   12236:     foreach my $name (keys(%allnames)) {
                   12237:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12238:       my $key=":parameter_0_$name";
1.261     albertel 12239:       $$metacache{"$key.part"}='0';
                   12240:       $$metacache{"$key.name"}=$name;
1.428     albertel 12241:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12242: 					   $allnames{$name}.'_'.$name.
                   12243: 					   '.type'};
1.428     albertel 12244:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12245: 			     '.display'};
1.644     www      12246:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12247:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12248:       $$metacache{"$key.display"}=$olddis;
                   12249:     }
1.71      www      12250: }
                   12251: 
1.764     albertel 12252: # ------------------------------------------------------ Devalidate title cache
                   12253: 
                   12254: sub devalidate_title_cache {
                   12255:     my ($url)=@_;
                   12256:     if (!$env{'request.course.id'}) { return; }
                   12257:     my $symb=&symbread($url);
                   12258:     if (!$symb) { return; }
                   12259:     my $key=$env{'request.course.id'}."\0".$symb;
                   12260:     &devalidate_cache_new('title',$key);
                   12261: }
                   12262: 
1.1014    droeschl 12263: # ------------------------------------------------- Get the title of a course
                   12264: 
                   12265: sub current_course_title {
                   12266:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12267: }
1.301     www      12268: # ------------------------------------------------- Get the title of a resource
                   12269: 
                   12270: sub gettitle {
                   12271:     my $urlsymb=shift;
                   12272:     my $symb=&symbread($urlsymb);
1.534     albertel 12273:     if ($symb) {
1.620     albertel 12274: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12275: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12276: 	if (defined($cached)) { 
                   12277: 	    return $result;
                   12278: 	}
1.534     albertel 12279: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12280: 	my $title='';
1.907     albertel 12281: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12282: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12283: 	} else {
                   12284: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12285: 		    &GDBM_READER(),0640)) {
                   12286: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12287: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12288: 		untie(%bighash);
                   12289: 	    }
1.534     albertel 12290: 	}
                   12291: 	$title=~s/\&colon\;/\:/gs;
                   12292: 	if ($title) {
1.1159    www      12293: # Remember both $symb and $title for dynamic metadata
                   12294:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12295:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12296: # Cache this title and then return it
1.599     albertel 12297: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12298: 	}
                   12299: 	$urlsymb=$url;
                   12300:     }
                   12301:     my $title=&metadata($urlsymb,'title');
                   12302:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12303:     return $title;
1.301     www      12304: }
1.613     albertel 12305: 
1.614     albertel 12306: sub get_slot {
                   12307:     my ($which,$cnum,$cdom)=@_;
                   12308:     if (!$cnum || !$cdom) {
1.790     albertel 12309: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12310: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12311: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12312:     }
1.703     albertel 12313:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12314:     my %slotinfo;
                   12315:     if (exists($remembered{$key})) {
                   12316: 	$slotinfo{$which} = $remembered{$key};
                   12317:     } else {
                   12318: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12319: 	&Apache::lonhomework::showhash(%slotinfo);
                   12320: 	my ($tmp)=keys(%slotinfo);
                   12321: 	if ($tmp=~/^error:/) { return (); }
                   12322: 	$remembered{$key} = $slotinfo{$which};
                   12323:     }
1.616     albertel 12324:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12325: 	return %{$slotinfo{$which}};
                   12326:     }
                   12327:     return $slotinfo{$which};
1.614     albertel 12328: }
1.1150    raeburn  12329: 
                   12330: sub get_reservable_slots {
                   12331:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12332:     my $now = time;
                   12333:     my $reservable_info;
                   12334:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12335:     if (exists($remembered{$key})) {
                   12336:         $reservable_info = $remembered{$key};
                   12337:     } else {
                   12338:         my %resv;
                   12339:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12340:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12341:         $reservable_info = \%resv;
                   12342:         $remembered{$key} = $reservable_info;
                   12343:     }
                   12344:     return $reservable_info;
                   12345: }
                   12346: 
                   12347: sub get_course_slots {
                   12348:     my ($cnum,$cdom) = @_;
                   12349:     my $hashid=$cnum.':'.$cdom;
                   12350:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12351:     if (defined($cached)) {
                   12352:         if (ref($result) eq 'HASH') {
                   12353:             return %{$result};
                   12354:         }
                   12355:     } else {
                   12356:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12357:         my ($tmp) = keys(%slots);
                   12358:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12359:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12360:             return %slots;
                   12361:         }
                   12362:     }
                   12363:     return;
                   12364: }
                   12365: 
                   12366: sub devalidate_slots_cache {
                   12367:     my ($cnum,$cdom)=@_;
                   12368:     my $hashid=$cnum.':'.$cdom;
                   12369:     &devalidate_cache_new('allslots',$hashid);
                   12370: }
                   12371: 
1.1172.2.8  raeburn  12372: sub get_coursechange {
                   12373:     my ($cdom,$cnum) = @_;
                   12374:     if ($cdom eq '' || $cnum eq '') {
                   12375:         return unless ($env{'request.course.id'});
                   12376:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12377:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12378:     }
                   12379:     my $hashid=$cdom.'_'.$cnum;
                   12380:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12381:     if ((defined($cached)) && ($change ne '')) {
                   12382:         return $change;
                   12383:     } else {
                   12384:         my %crshash;
                   12385:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12386:         if ($crshash{'internal.contentchange'} eq '') {
                   12387:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12388:             if ($change eq '') {
                   12389:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12390:                 $change = $crshash{'internal.created'};
                   12391:             }
                   12392:         } else {
                   12393:             $change = $crshash{'internal.contentchange'};
                   12394:         }
                   12395:         my $cachetime = 600;
                   12396:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12397:     }
                   12398:     return $change;
                   12399: }
                   12400: 
                   12401: sub devalidate_coursechange_cache {
                   12402:     my ($cnum,$cdom)=@_;
                   12403:     my $hashid=$cnum.':'.$cdom;
                   12404:     &devalidate_cache_new('crschange',$hashid);
                   12405: }
                   12406: 
1.31      www      12407: # ------------------------------------------------- Update symbolic store links
                   12408: 
                   12409: sub symblist {
                   12410:     my ($mapname,%newhash)=@_;
1.438     www      12411:     $mapname=&deversion(&declutter($mapname));
1.31      www      12412:     my %hash;
1.620     albertel 12413:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12414:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12415:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12416: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12417: 		next if ($url eq 'last_known'
                   12418: 			 && $env{'form.no_update_last_known'});
                   12419: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12420: 						    $newhash{$url}->[1],
                   12421: 						    $newhash{$url}->[0]);
1.191     harris41 12422:             }
1.31      www      12423:             if (untie(%hash)) {
                   12424: 		return 'ok';
                   12425:             }
                   12426:         }
                   12427:     }
                   12428:     return 'error';
1.212     www      12429: }
                   12430: 
                   12431: # --------------------------------------------------------------- Verify a symb
                   12432: 
                   12433: sub symbverify {
1.1172.2.11  raeburn  12434:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12435:     my $thisfn=$thisurl;
1.439     www      12436:     $thisfn=&declutter($thisfn);
1.215     www      12437: # direct jump to resource in page or to a sequence - will construct own symbs
                   12438:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12439: # check URL part
1.409     www      12440:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12441: 
1.431     www      12442:     unless ($url eq $thisfn) { return 0; }
1.213     www      12443: 
1.216     www      12444:     $symb=&symbclean($symb);
1.510     www      12445:     $thisurl=&deversion($thisurl);
1.439     www      12446:     $thisfn=&deversion($thisfn);
1.213     www      12447: 
                   12448:     my %bighash;
                   12449:     my $okay=0;
1.431     www      12450: 
1.620     albertel 12451:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12452:                             &GDBM_READER(),0640)) {
1.1032    raeburn  12453:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12454:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  12455:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12456:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12457:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12458:             }
                   12459:         }
                   12460:         my $ids;
1.1172.2.118.  .5(raebu 12461:20):         if ($map =~ m{^uploaded/.+\.page$}) {
                   12462:20):             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13  raeburn  12463:         } else {
                   12464:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12465:         }
1.1102    raeburn  12466:         unless ($ids) {
1.1172.2.13  raeburn  12467:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  12468:             $ids=$bighash{$idkey};
1.216     www      12469:         }
                   12470:         if ($ids) {
                   12471: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  12472:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   12473:                 $symb =~ s/\?.+$//;
                   12474:             }
1.800     albertel 12475: 	    foreach my $id (split(/\,/,$ids)) {
                   12476: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12477:                if (
                   12478:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  12479:    eq $symb) {
1.1172.2.11  raeburn  12480:                    if (ref($encstate)) {
                   12481:                        $$encstate = $bighash{'encrypted_'.$id};
                   12482:                    }
1.1172.2.13  raeburn  12483:                    if (($env{'request.role.adv'}) ||
                   12484:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  12485:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  12486:                        $okay=1;
                   12487:                        last;
                   12488:                    }
                   12489:                }
                   12490:            }
1.216     www      12491:         }
1.213     www      12492: 	untie(%bighash);
                   12493:     }
                   12494:     return $okay;
1.31      www      12495: }
                   12496: 
1.210     www      12497: # --------------------------------------------------------------- Clean-up symb
                   12498: 
                   12499: sub symbclean {
                   12500:     my $symb=shift;
1.568     albertel 12501:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12502: # remove version from map
                   12503:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12504: 
1.210     www      12505: # remove version from URL
                   12506:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12507: 
1.507     www      12508: # remove wrapper
                   12509: 
1.510     www      12510:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12511:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12512:     return $symb;
1.409     www      12513: }
                   12514: 
                   12515: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12516: 
                   12517: sub encode_symb {
                   12518:     my ($map,$resid,$url)=@_;
                   12519:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12520: }
1.409     www      12521: 
                   12522: sub decode_symb {
1.568     albertel 12523:     my $symb=shift;
                   12524:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12525:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12526:     return (&fixversion($map),$resid,&fixversion($url));
                   12527: }
                   12528: 
                   12529: sub fixversion {
                   12530:     my $fn=shift;
1.609     banghart 12531:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12532:     my %bighash;
                   12533:     my $uri=&clutter($fn);
1.620     albertel 12534:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12535: # is this cached?
1.599     albertel 12536:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12537:     if (defined($cached)) { return $result; }
                   12538: # unfortunately not cached, or expired
1.620     albertel 12539:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12540: 	    &GDBM_READER(),0640)) {
                   12541:  	if ($bighash{'version_'.$uri}) {
                   12542:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12543:  	    unless (($version eq 'mostrecent') || 
                   12544: 		    ($version==&getversion($uri))) {
1.440     www      12545:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12546:  	    }
                   12547:  	}
                   12548:  	untie %bighash;
1.413     www      12549:     }
1.599     albertel 12550:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12551: }
                   12552: 
                   12553: sub deversion {
                   12554:     my $url=shift;
                   12555:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12556:     return $url;
1.210     www      12557: }
                   12558: 
1.31      www      12559: # ------------------------------------------------------ Return symb list entry
                   12560: 
                   12561: sub symbread {
1.1172.2.118.  .8(raebu 12562:20):     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
          .9(raebu 12563:20):         $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54  raeburn  12564:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.118.  .9(raebu 12565:20):     if (defined($env{$cache_str})) {
          .8(raebu 12566:20):         unless (ref($possibles) eq 'HASH') {
                   12567:20):             if ($ignorecachednull) {
                   12568:20):                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12569:20):             } else {
                   12570:20):                 return $env{$cache_str};
                   12571:20):             }
1.1172.2.66  raeburn  12572:         }
                   12573:     }
1.242     www      12574: # no filename provided? try from environment
1.1172.2.54  raeburn  12575:     unless ($thisfn) {
1.620     albertel 12576:         if ($env{'request.symb'}) {
1.1172.2.118.  .9(raebu 12577:20):             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13  raeburn  12578:         }
                   12579:         $thisfn=$env{'request.filename'};
1.44      www      12580:     }
1.569     albertel 12581:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12582: # is that filename actually a symb? Verify, clean, and return
                   12583:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12584: 	if (&symbverify($thisfn,$1)) {
1.1172.2.118.  .9(raebu 12585:20): 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12586: 	}
1.242     www      12587:     }
1.44      www      12588:     $thisfn=declutter($thisfn);
1.31      www      12589:     my %hash;
1.37      www      12590:     my %bighash;
                   12591:     my $syval='';
1.620     albertel 12592:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12593:         my $targetfn = $thisfn;
1.609     banghart 12594:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12595:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12596:         }
1.687     albertel 12597: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12598: 	    $targetfn=$1;
                   12599: 	}
1.1172.2.118.  .9(raebu 12600:20):         unless ($ignoresymbdb) {
          .8(raebu 12601:20):             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   12602:20):                           &GDBM_READER(),0640)) {
                   12603:20): 	        $syval=$hash{$targetfn};
                   12604:20):                 untie(%hash);
                   12605:20):             }
          .9(raebu 12606:20):             if ($syval && $checkforblock) {
                   12607:20):                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
          .8(raebu 12608:20):                 if (@blockers) {
                   12609:20):                     $syval='';
                   12610:20):                 }
                   12611:20):             }
1.37      www      12612:         }
                   12613: # ---------------------------------------------------------- There was an entry
                   12614:         if ($syval) {
1.601     albertel 12615: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12616: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12617: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12618: 		    #return $env{$cache_str}='';
1.601     albertel 12619: 		#}    
                   12620: 		#$syval.=$1;
                   12621: 	    #}
1.37      www      12622:         } else {
                   12623: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12624:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12625:                             &GDBM_READER(),0640)) {
1.37      www      12626: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12627:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12628:               unless ($ids) { 
                   12629:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12630:               }
                   12631:               unless ($ids) {
                   12632: # alias?
                   12633: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12634:               }
1.37      www      12635:               if ($ids) {
                   12636: # ------------------------------------------------------------------- Has ID(s)
                   12637:                  my @possibilities=split(/\,/,$ids);
1.39      www      12638:                  if ($#possibilities==0) {
                   12639: # ----------------------------------------------- There is only one possibility
1.37      www      12640: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12641: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12642: 						    $resid,$thisfn);
1.1172.2.66  raeburn  12643:                      if (ref($possibles) eq 'HASH') {
1.1172.2.118.  .8(raebu 12644:20):                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   12645:20):                              $possibles->{$syval} = 1;
                   12646:20):                          }
1.1172.2.66  raeburn  12647:                      }
                   12648:                      if ($checkforblock) {
1.1172.2.118.  .8(raebu 12649:20):                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   12650:20):                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
                   12651:20):                              if (@blockers) {
                   12652:20):                                  $syval = '';
                   12653:20):                                  untie(%bighash);
                   12654:20):                                  return $env{$cache_str}='';
                   12655:20):                              }
1.1172.2.66  raeburn  12656:                          }
                   12657:                      }
                   12658:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      12659: # ------------------------------------------ There is more than one possibility
                   12660:                      my $realpossible=0;
1.800     albertel 12661:                      foreach my $id (@possibilities) {
                   12662: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  12663:                          my $canaccess;
                   12664:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12665:                              $canaccess = 1;
                   12666:                          } else {
                   12667:                              $canaccess = &allowed('bre',$file);
                   12668:                          }
                   12669:                          if ($canaccess) {
                   12670:          		     my ($mapid,$resid)=split(/\./,$id);
                   12671:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12672:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12673:                                                              $resid,$thisfn);
1.1172.2.118.  .8(raebu 12674:20):                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
                   12675:20):                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66  raeburn  12676:                                  if ($checkforblock) {
1.1172.2.118.  .8(raebu 12677:20):                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
                   12678:20):                                      if (@blockers > 0) {
                   12679:20):                                          $syval = '';
                   12680:20):                                      } else {
1.1172.2.66  raeburn  12681:                                          $syval = $poss_syval;
                   12682:                                          $realpossible++;
                   12683:                                      }
                   12684:                                  } else {
                   12685:                                      $syval = $poss_syval;
                   12686:                                      $realpossible++;
                   12687:                                  }
1.1172.2.118.  .8(raebu 12688:20):                                  if ($syval) {
                   12689:20):                                      if (ref($possibles) eq 'HASH') {
                   12690:20):                                          $possibles->{$syval} = 1;
                   12691:20):                                      }
                   12692:20):                                  }
1.1172.2.66  raeburn  12693:                              }
1.39      www      12694: 			 }
1.191     harris41 12695:                      }
1.39      www      12696: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12697:                  } else {
                   12698:                      $syval='';
1.37      www      12699:                  }
                   12700: 	      }
1.1172.2.66  raeburn  12701:               untie(%bighash);
1.481     raeburn  12702:            }
1.31      www      12703:         }
1.62      www      12704:         if ($syval) {
1.1172.2.118.  .9(raebu 12705:20): 	    return $env{$cache_str}=$syval;
1.62      www      12706:         }
1.31      www      12707:     }
1.949     raeburn  12708:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12709:     return $env{$cache_str}='';
1.31      www      12710: }
                   12711: 
                   12712: # ---------------------------------------------------------- Return random seed
                   12713: 
1.32      www      12714: sub numval {
                   12715:     my $txt=shift;
                   12716:     $txt=~tr/A-J/0-9/;
                   12717:     $txt=~tr/a-j/0-9/;
                   12718:     $txt=~tr/K-T/0-9/;
                   12719:     $txt=~tr/k-t/0-9/;
                   12720:     $txt=~tr/U-Z/0-5/;
                   12721:     $txt=~tr/u-z/0-5/;
                   12722:     $txt=~s/\D//g;
1.564     albertel 12723:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12724:     return int($txt);
1.368     albertel 12725: }
                   12726: 
1.484     albertel 12727: sub numval2 {
                   12728:     my $txt=shift;
                   12729:     $txt=~tr/A-J/0-9/;
                   12730:     $txt=~tr/a-j/0-9/;
                   12731:     $txt=~tr/K-T/0-9/;
                   12732:     $txt=~tr/k-t/0-9/;
                   12733:     $txt=~tr/U-Z/0-5/;
                   12734:     $txt=~tr/u-z/0-5/;
                   12735:     $txt=~s/\D//g;
                   12736:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12737:     my $total;
                   12738:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12739:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12740:     return int($total);
                   12741: }
                   12742: 
1.575     albertel 12743: sub numval3 {
                   12744:     use integer;
                   12745:     my $txt=shift;
                   12746:     $txt=~tr/A-J/0-9/;
                   12747:     $txt=~tr/a-j/0-9/;
                   12748:     $txt=~tr/K-T/0-9/;
                   12749:     $txt=~tr/k-t/0-9/;
                   12750:     $txt=~tr/U-Z/0-5/;
                   12751:     $txt=~tr/u-z/0-5/;
                   12752:     $txt=~s/\D//g;
                   12753:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12754:     my $total;
                   12755:     foreach my $val (@txts) { $total+=$val; }
                   12756:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12757:     return $total;
                   12758: }
                   12759: 
1.675     albertel 12760: sub digest {
                   12761:     my ($data)=@_;
                   12762:     my $digest=&Digest::MD5::md5($data);
                   12763:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12764:     my ($e,$f);
                   12765:     {
                   12766:         use integer;
                   12767:         $e=($a+$b);
                   12768:         $f=($c+$d);
                   12769:         if ($_64bit) {
                   12770:             $e=(($e<<32)>>32);
                   12771:             $f=(($f<<32)>>32);
                   12772:         }
                   12773:     }
                   12774:     if (wantarray) {
                   12775: 	return ($e,$f);
                   12776:     } else {
                   12777: 	my $g;
                   12778: 	{
                   12779: 	    use integer;
                   12780: 	    $g=($e+$f);
                   12781: 	    if ($_64bit) {
                   12782: 		$g=(($g<<32)>>32);
                   12783: 	    }
                   12784: 	}
                   12785: 	return $g;
                   12786:     }
                   12787: }
                   12788: 
1.368     albertel 12789: sub latest_rnd_algorithm_id {
1.675     albertel 12790:     return '64bit5';
1.366     albertel 12791: }
1.32      www      12792: 
1.503     albertel 12793: sub get_rand_alg {
                   12794:     my ($courseid)=@_;
1.790     albertel 12795:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12796:     if ($courseid) {
1.620     albertel 12797: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12798:     }
                   12799:     return &latest_rnd_algorithm_id();
                   12800: }
                   12801: 
1.562     albertel 12802: sub validCODE {
                   12803:     my ($CODE)=@_;
                   12804:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12805:     return 0;
                   12806: }
                   12807: 
1.491     albertel 12808: sub getCODE {
1.620     albertel 12809:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12810:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12811: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12812: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12813: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12814:     }
                   12815:     return undef;
                   12816: }
1.1133    foxr     12817: #
                   12818: #  Determines the random seed for a specific context:
                   12819: #
                   12820: # parameters:
                   12821: #   symb      - in course context the symb for the seed.
                   12822: #   course_id - The course id of the form domain_coursenum.
                   12823: #   domain    - Domain for the user.
                   12824: #   course    - Course for the user.
                   12825: #   cenv      - environment of the course.
                   12826: #
                   12827: # NOTE:
                   12828: #   All parameters are picked out of the environment if missing
                   12829: #   or not defined.
                   12830: #   If a symb cannot be determined the current time is used instead.
                   12831: #
                   12832: #  For a given well defined symb, courside, domain, username,
                   12833: #  and course environment, the seed is reproducible.
                   12834: #
1.31      www      12835: sub rndseed {
1.1133    foxr     12836:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12837:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12838:     if (!defined($symb)) {
1.366     albertel 12839: 	unless ($symb=$wsymb) { return time; }
                   12840:     }
1.1146    foxr     12841:     if (!defined $courseid) { 
                   12842: 	$courseid=$wcourseid; 
                   12843:     }
                   12844:     if (!defined $domain) { $domain=$wdomain; }
                   12845:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12846: 
                   12847:     my $which;
                   12848:     if (defined($cenv->{'rndseed'})) {
                   12849: 	$which = $cenv->{'rndseed'};
                   12850:     } else {
                   12851: 	$which =&get_rand_alg($courseid);
                   12852:     }
1.491     albertel 12853:     if (defined(&getCODE())) {
1.675     albertel 12854: 	if ($which eq '64bit5') {
                   12855: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12856: 	} elsif ($which eq '64bit4') {
1.575     albertel 12857: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12858: 	} else {
                   12859: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12860: 	}
1.675     albertel 12861:     } elsif ($which eq '64bit5') {
                   12862: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12863:     } elsif ($which eq '64bit4') {
                   12864: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12865:     } elsif ($which eq '64bit3') {
                   12866: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12867:     } elsif ($which eq '64bit2') {
                   12868: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12869:     } elsif ($which eq '64bit') {
                   12870: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12871:     }
                   12872:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12873: }
                   12874: 
                   12875: sub rndseed_32bit {
                   12876:     my ($symb,$courseid,$domain,$username)=@_;
                   12877:     {
                   12878: 	use integer;
                   12879: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12880: 	my $symbseed=numval($symb) << 22;
                   12881: 	my $namechck=unpack("%32C*",$username) << 17;
                   12882: 	my $nameseed=numval($username) << 12;
                   12883: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12884: 	my $courseseed=unpack("%32C*",$courseid);
                   12885: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12886: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12887: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12888: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12889: 	return $num;
                   12890:     }
                   12891: }
                   12892: 
                   12893: sub rndseed_64bit {
                   12894:     my ($symb,$courseid,$domain,$username)=@_;
                   12895:     {
                   12896: 	use integer;
                   12897: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12898: 	my $symbseed=numval($symb) << 10;
                   12899: 	my $namechck=unpack("%32S*",$username);
                   12900: 	
                   12901: 	my $nameseed=numval($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 :$num:$symb");
1.564     albertel 12909: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12910: 	return "$num1,$num2";
1.155     albertel 12911:     }
1.366     albertel 12912: }
                   12913: 
1.443     albertel 12914: sub rndseed_64bit2 {
                   12915:     my ($symb,$courseid,$domain,$username)=@_;
                   12916:     {
                   12917: 	use integer;
                   12918: 	# strings need to be an even # of cahracters long, it it is odd the
                   12919:         # last characters gets thrown away
                   12920: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12921: 	my $symbseed=numval($symb) << 10;
                   12922: 	my $namechck=unpack("%32S*",$username.' ');
                   12923: 	
                   12924: 	my $nameseed=numval($username) << 21;
1.501     albertel 12925: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12926: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12927: 	
                   12928: 	my $num1=$symbchck+$symbseed+$namechck;
                   12929: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12930: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12931: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12932: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12933: 	return "$num1,$num2";
                   12934:     }
                   12935: }
                   12936: 
                   12937: sub rndseed_64bit3 {
                   12938:     my ($symb,$courseid,$domain,$username)=@_;
                   12939:     {
                   12940: 	use integer;
                   12941: 	# strings need to be an even # of cahracters long, it it is odd the
                   12942:         # last characters gets thrown away
                   12943: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12944: 	my $symbseed=numval2($symb) << 10;
                   12945: 	my $namechck=unpack("%32S*",$username.' ');
                   12946: 	
                   12947: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12948: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12949: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12950: 	
                   12951: 	my $num1=$symbchck+$symbseed+$namechck;
                   12952: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12953: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12954: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12955: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12956: 	
1.503     albertel 12957: 	return "$num1:$num2";
1.443     albertel 12958:     }
                   12959: }
                   12960: 
1.575     albertel 12961: sub rndseed_64bit4 {
                   12962:     my ($symb,$courseid,$domain,$username)=@_;
                   12963:     {
                   12964: 	use integer;
                   12965: 	# strings need to be an even # of cahracters long, it it is odd the
                   12966:         # last characters gets thrown away
                   12967: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12968: 	my $symbseed=numval3($symb) << 10;
                   12969: 	my $namechck=unpack("%32S*",$username.' ');
                   12970: 	
                   12971: 	my $nameseed=numval3($username) << 21;
                   12972: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12973: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12974: 	
                   12975: 	my $num1=$symbchck+$symbseed+$namechck;
                   12976: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12977: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12978: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12979: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12980: 	
1.575     albertel 12981: 	return "$num1:$num2";
                   12982:     }
                   12983: }
                   12984: 
1.675     albertel 12985: sub rndseed_64bit5 {
                   12986:     my ($symb,$courseid,$domain,$username)=@_;
                   12987:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12988:     return "$num1:$num2";
                   12989: }
                   12990: 
1.366     albertel 12991: sub rndseed_CODE_64bit {
                   12992:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12993:     {
1.366     albertel 12994: 	use integer;
1.443     albertel 12995: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12996: 	my $symbseed=numval2($symb);
1.491     albertel 12997: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12998: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12999: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13000: 	my $num1=$symbseed+$CODEchck;
                   13001: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13002: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13003: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13004: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13005: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13006: 	return "$num1:$num2";
1.366     albertel 13007:     }
                   13008: }
                   13009: 
1.575     albertel 13010: sub rndseed_CODE_64bit4 {
                   13011:     my ($symb,$courseid,$domain,$username)=@_;
                   13012:     {
                   13013: 	use integer;
                   13014: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13015: 	my $symbseed=numval3($symb);
                   13016: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13017: 	my $CODEseed=numval3(&getCODE());
                   13018: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13019: 	my $num1=$symbseed+$CODEchck;
                   13020: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13021: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13022: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13023: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13024: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13025: 	return "$num1:$num2";
                   13026:     }
                   13027: }
                   13028: 
1.675     albertel 13029: sub rndseed_CODE_64bit5 {
                   13030:     my ($symb,$courseid,$domain,$username)=@_;
                   13031:     my $code = &getCODE();
                   13032:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13033:     return "$num1:$num2";
                   13034: }
                   13035: 
1.366     albertel 13036: sub setup_random_from_rndseed {
                   13037:     my ($rndseed)=@_;
1.503     albertel 13038:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  13039: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13040:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13041:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13042:         } else {
                   13043:             &Math::Random::random_set_seed($num1,$num2);
                   13044:         }
1.366     albertel 13045:     } else {
                   13046: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13047:     }
1.36      albertel 13048: }
                   13049: 
1.474     albertel 13050: sub latest_receipt_algorithm_id {
1.835     albertel 13051:     return 'receipt3';
1.474     albertel 13052: }
                   13053: 
1.480     www      13054: sub recunique {
                   13055:     my $fucourseid=shift;
                   13056:     my $unique;
1.835     albertel 13057:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13058: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13059: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13060:     } else {
                   13061: 	$unique=$perlvar{'lonReceipt'};
                   13062:     }
                   13063:     return unpack("%32C*",$unique);
                   13064: }
                   13065: 
                   13066: sub recprefix {
                   13067:     my $fucourseid=shift;
                   13068:     my $prefix;
1.835     albertel 13069:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13070: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13071: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13072:     } else {
                   13073: 	$prefix=$perlvar{'lonHostID'};
                   13074:     }
                   13075:     return unpack("%32C*",$prefix);
                   13076: }
                   13077: 
1.76      www      13078: sub ireceipt {
1.474     albertel 13079:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13080: 
                   13081:     my $return =&recprefix($fucourseid).'-';
                   13082: 
                   13083:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13084: 	$env{'request.state'} eq 'construct') {
                   13085: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13086: 	return $return;
                   13087:     }
                   13088: 
1.76      www      13089:     my $cuname=unpack("%32C*",$funame);
                   13090:     my $cudom=unpack("%32C*",$fudom);
                   13091:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13092:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13093:     my $cunique=&recunique($fucourseid);
1.474     albertel 13094:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13095:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13096: 
1.790     albertel 13097: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13098: 			       
                   13099: 	$return.= ($cunique%$cuname+
                   13100: 		   $cunique%$cudom+
                   13101: 		   $cusymb%$cuname+
                   13102: 		   $cusymb%$cudom+
                   13103: 		   $cucourseid%$cuname+
                   13104: 		   $cucourseid%$cudom+
                   13105: 		   $cpart%$cuname+
                   13106: 		   $cpart%$cudom);
                   13107:     } else {
                   13108: 	$return.= ($cunique%$cuname+
                   13109: 		   $cunique%$cudom+
                   13110: 		   $cusymb%$cuname+
                   13111: 		   $cusymb%$cudom+
                   13112: 		   $cucourseid%$cuname+
                   13113: 		   $cucourseid%$cudom);
                   13114:     }
                   13115:     return $return;
1.76      www      13116: }
                   13117: 
                   13118: sub receipt {
1.474     albertel 13119:     my ($part)=@_;
1.790     albertel 13120:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13121:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13122: }
1.260     ng       13123: 
1.790     albertel 13124: sub whichuser {
                   13125:     my ($passedsymb)=@_;
                   13126:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13127:     if (defined($env{'form.grade_symb'})) {
                   13128: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13129: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13130: 	if (!$allowed &&
                   13131: 	    exists($env{'request.course.sec'}) &&
                   13132: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13133: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13134: 			      '/'.$env{'request.course.sec'});
                   13135: 	}
                   13136: 	if ($allowed) {
                   13137: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13138: 	    $courseid=$tmp_courseid;
                   13139: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13140: 	    ($name)=&get_env_multiple('form.grade_username');
                   13141: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13142: 	}
                   13143:     }
                   13144:     if (!$passedsymb) {
                   13145: 	$symb=&symbread();
                   13146:     } else {
                   13147: 	$symb=$passedsymb;
                   13148:     }
                   13149:     $courseid=$env{'request.course.id'};
                   13150:     $domain=$env{'user.domain'};
                   13151:     $name=$env{'user.name'};
                   13152:     if ($name eq 'public' && $domain eq 'public') {
                   13153: 	if (!defined($env{'form.username'})) {
                   13154: 	    $env{'form.username'}.=time.rand(10000000);
                   13155: 	}
                   13156: 	$name.=$env{'form.username'};
                   13157:     }
                   13158:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13159: 
                   13160: }
                   13161: 
1.36      albertel 13162: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13163: # returns either the contents of the file or 
                   13164: # -1 if the file doesn't exist
1.481     raeburn  13165: #
                   13166: # if the target is a file that was uploaded via DOCS, 
                   13167: # a check will be made to see if a current copy exists on the local server,
                   13168: # if it does this will be served, otherwise a copy will be retrieved from
                   13169: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13170: # the local server.   
1.472     albertel 13171: 
1.36      albertel 13172: sub getfile {
1.538     albertel 13173:     my ($file) = @_;
1.609     banghart 13174:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13175:     &repcopy($file);
                   13176:     return &readfile($file);
                   13177: }
                   13178: 
                   13179: sub repcopy_userfile {
                   13180:     my ($file)=@_;
1.1142    raeburn  13181:     my $londocroot = $perlvar{'lonDocRoot'};
                   13182:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13183:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13184:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13185: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13186:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13187:     if (-e "$file") {
1.828     www      13188: # we already have a local copy, check it out
1.538     albertel 13189: 	my @fileinfo = stat($file);
1.828     www      13190: 	my $rtncode;
                   13191: 	my $info;
1.538     albertel 13192: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13193: 	if ($lwpresp ne 'ok') {
1.828     www      13194: # there is no such file anymore, even though we had a local copy
1.482     albertel 13195: 	    if ($rtncode eq '404') {
1.538     albertel 13196: 		unlink($file);
1.482     albertel 13197: 	    }
                   13198: 	    return -1;
                   13199: 	}
                   13200: 	if ($info < $fileinfo[9]) {
1.828     www      13201: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13202: 	    return 'ok';
1.828     www      13203: 	} else {
                   13204: # the file is outdated, get rid of it
                   13205: 	    unlink($file);
1.482     albertel 13206: 	}
1.828     www      13207:     }
                   13208: # one way or the other, at this point, we don't have the file
                   13209: # construct the correct path for the file
                   13210:     my @parts = ($cdom,$cnum); 
                   13211:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13212: 	push @parts, split(/\//,$1);
                   13213:     }
                   13214:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13215:     foreach my $part (@parts) {
                   13216: 	$path .= '/'.$part;
                   13217: 	if (!-e $path) {
                   13218: 	    mkdir($path,0770);
1.482     albertel 13219: 	}
                   13220:     }
1.828     www      13221: # now the path exists for sure
                   13222: # get a user agent
                   13223:     my $ua=new LWP::UserAgent;
                   13224:     my $transferfile=$file.'.in.transfer';
                   13225: # FIXME: this should flock
                   13226:     if (-e $transferfile) { return 'ok'; }
                   13227:     my $request;
                   13228:     $uri=~s/^\///;
1.980     raeburn  13229:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.118.  .3(raebu 13230:20):     my $hostname = &hostname($homeserver);
1.980     raeburn  13231:     my $protocol = $protocol{$homeserver};
                   13232:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu 13233:20):     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      13234:     my $response=$ua->request($request,$transferfile);
                   13235: # did it work?
                   13236:     if ($response->is_error()) {
                   13237: 	unlink($transferfile);
                   13238: 	&logthis("Userfile repcopy failed for $uri");
                   13239: 	return -1;
                   13240:     }
                   13241: # worked, rename the transfer file
                   13242:     rename($transferfile,$file);
1.607     raeburn  13243:     return 'ok';
1.481     raeburn  13244: }
                   13245: 
1.517     albertel 13246: sub tokenwrapper {
                   13247:     my $uri=shift;
1.980     raeburn  13248:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13249:     $uri=~s|^/||;
1.620     albertel 13250:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13251:     my $token=$1;
1.552     albertel 13252:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13253:     if ($udom && $uname && $file) {
                   13254: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13255:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13256:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.118.  .3(raebu 13257:20):         my $hostname = &hostname($homeserver);
1.980     raeburn  13258:         my $protocol = $protocol{$homeserver};
                   13259:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu 13260:20):         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13261:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13262:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13263:     } else {
                   13264:         return '/adm/notfound.html';
                   13265:     }
                   13266: }
                   13267: 
1.828     www      13268: # call with reqtype HEAD: get last modification time
                   13269: # call with reqtype GET: get the file contents
                   13270: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13271: #
1.481     raeburn  13272: sub getuploaded {
                   13273:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13274:     $uri=~s/^\///;
1.980     raeburn  13275:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.118.  .3(raebu 13276:20):     my $hostname = &hostname($homeserver);
1.980     raeburn  13277:     my $protocol = $protocol{$homeserver};
                   13278:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu 13279:20):     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13280:     my $ua=new LWP::UserAgent;
                   13281:     my $request=new HTTP::Request($reqtype,$uri);
                   13282:     my $response=$ua->request($request);
                   13283:     $$rtncode = $response->code;
1.482     albertel 13284:     if (! $response->is_success()) {
                   13285: 	return 'failed';
                   13286:     }      
                   13287:     if ($reqtype eq 'HEAD') {
1.486     www      13288: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13289:     } elsif ($reqtype eq 'GET') {
                   13290: 	$$info = $response->content;
1.472     albertel 13291:     }
1.482     albertel 13292:     return 'ok';
1.36      albertel 13293: }
                   13294: 
1.481     raeburn  13295: sub readfile {
                   13296:     my $file = shift;
                   13297:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13298:     my $fh;
1.1172.2.96  raeburn  13299:     open($fh,"<",$file);
1.481     raeburn  13300:     my $a='';
1.800     albertel 13301:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13302:     return $a;
                   13303: }
                   13304: 
1.36      albertel 13305: sub filelocation {
1.590     banghart 13306:     my ($dir,$file) = @_;
                   13307:     my $location;
                   13308:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13309: 
                   13310:     if ($file =~ m-^/adm/-) {
                   13311: 	$file=~s-^/adm/wrapper/-/-;
                   13312: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13313:     }
1.882     albertel 13314: 
1.1139    www      13315:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13316:         $location = $file;
1.609     banghart 13317:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13318:         my ($udom,$uname,$filename)=
1.811     albertel 13319:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13320:         my $home=&homeserver($uname,$udom);
                   13321:         my $is_me=0;
                   13322:         my @ids=&current_machine_ids();
                   13323:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13324:         if ($is_me) {
1.1117    foxr     13325:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13326:         } else {
                   13327:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13328:   	      $udom.'/'.$uname.'/'.$filename;
                   13329:         }
1.882     albertel 13330:     } elsif ($file =~ m-^/adm/-) {
                   13331: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13332:     } else {
                   13333:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13334:         $file=~s:^/(res|priv)/:/:;
                   13335:         my $space=$1;
1.590     banghart 13336:         if ( !( $file =~ m:^/:) ) {
                   13337:             $location = $dir. '/'.$file;
                   13338:         } else {
1.1142    raeburn  13339:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13340:         }
1.59      albertel 13341:     }
1.590     banghart 13342:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13343:     while ($location=~m{/\.\./}) {
                   13344: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13345: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13346: 	} else {
                   13347: 	    $location=~ s{/\.\./}{/}g;
                   13348: 	}
                   13349:     } #remove dir/..
1.590     banghart 13350:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13351:     return $location;
1.46      www      13352: }
1.36      albertel 13353: 
1.46      www      13354: sub hreflocation {
                   13355:     my ($dir,$file)=@_;
1.980     raeburn  13356:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13357: 	$file=filelocation($dir,$file);
1.700     albertel 13358:     } elsif ($file=~m-^/adm/-) {
                   13359: 	$file=~s-^/adm/wrapper/-/-;
                   13360: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13361:     }
                   13362:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13363: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13364:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13365: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13366: 	        {/uploaded/$1/$2/}x;
1.46      www      13367:     }
1.913     albertel 13368:     if ($file=~ m{^/userfiles/}) {
                   13369: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13370:     }
1.462     albertel 13371:     return $file;
1.465     albertel 13372: }
                   13373: 
1.1139    www      13374: 
                   13375: 
                   13376: 
                   13377: 
1.465     albertel 13378: sub current_machine_domains {
1.853     albertel 13379:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13380: }
                   13381: 
                   13382: sub machine_domains {
                   13383:     my ($hostname) = @_;
1.465     albertel 13384:     my @domains;
1.838     albertel 13385:     my %hostname = &all_hostnames();
1.465     albertel 13386:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13387: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13388: 	if ($hostname eq $name) {
1.844     albertel 13389: 	    push(@domains,&host_domain($id));
1.465     albertel 13390: 	}
                   13391:     }
                   13392:     return @domains;
                   13393: }
                   13394: 
                   13395: sub current_machine_ids {
1.853     albertel 13396:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13397: }
                   13398: 
                   13399: sub machine_ids {
                   13400:     my ($hostname) = @_;
                   13401:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13402:     my @ids;
1.888     albertel 13403:     my %name_to_host = &all_names();
1.889     albertel 13404:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13405: 	return @{ $name_to_host{$hostname} };
                   13406:     }
                   13407:     return;
1.31      www      13408: }
                   13409: 
1.824     raeburn  13410: sub additional_machine_domains {
                   13411:     my @domains;
1.1172.2.96  raeburn  13412:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13413:     while( my $line = <$fh>) {
                   13414:         $line =~ s/\s//g;
                   13415:         push(@domains,$line);
                   13416:     }
                   13417:     return @domains;
                   13418: }
                   13419: 
                   13420: sub default_login_domain {
                   13421:     my $domain = $perlvar{'lonDefDomain'};
                   13422:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13423:     foreach my $posdom (&current_machine_domains(),
                   13424:                         &additional_machine_domains()) {
                   13425:         if (lc($posdom) eq lc($testdomain)) {
                   13426:             $domain=$posdom;
                   13427:             last;
                   13428:         }
                   13429:     }
                   13430:     return $domain;
                   13431: }
                   13432: 
1.1172.2.106  raeburn  13433: sub shared_institution {
                   13434:     my ($dom) = @_;
                   13435:     my $same_intdom;
                   13436:     my $hostintdom = &internet_dom($perlvar{'lonHostID'});
                   13437:     if ($hostintdom ne '') {
                   13438:         my %iphost = &get_iphost();
                   13439:         my $primary_id = &domain($dom,'primary');
                   13440:         my $primary_ip = &get_host_ip($primary_id);
                   13441:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   13442:             foreach my $id (@{$iphost{$primary_ip}}) {
                   13443:                 my $intdom = &internet_dom($id);
                   13444:                 if ($intdom eq $hostintdom) {
                   13445:                     $same_intdom = 1;
                   13446:                     last;
                   13447:                 }
                   13448:             }
                   13449:         }
                   13450:     }
                   13451:     return $same_intdom;
                   13452: }
                   13453: 
1.1172.2.118.  .3(raebu 13454:20): sub uses_sts {
                   13455:20):     my ($ignore_cache) = @_;
                   13456:20):     my $lonhost = $perlvar{'lonHostID'};
                   13457:20):     my $hostname = &hostname($lonhost);
                   13458:20):     my $sts_on;
                   13459:20):     if ($protocol{$lonhost} eq 'https') {
                   13460:20):         my $cachetime = 12*3600;
                   13461:20):         if (!$ignore_cache) {
                   13462:20):             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   13463:20):             if (defined($cached)) {
                   13464:20):                 return $sts_on;
                   13465:20):             }
                   13466:20):         }
          .4(raebu 13467:20):         my $ua=new LWP::UserAgent;
          .3(raebu 13468:20):         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   13469:20):         my $request=new HTTP::Request('HEAD',$url);
          .4(raebu 13470:20):         my $response=$ua->request($request);
          .3(raebu 13471:20):         if ($response->is_success) {
                   13472:20):             my $has_sts = $response->header('Strict-Transport-Security');
                   13473:20):             if ($has_sts eq '') {
                   13474:20):                 $sts_on = 0;
                   13475:20):             } else {
                   13476:20):                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   13477:20):                     my $maxage = $1;
                   13478:20):                     if ($maxage) {
                   13479:20):                         $sts_on = 1;
                   13480:20):                     } else {
                   13481:20):                         $sts_on = 0;
                   13482:20):                     }
                   13483:20):                 } else {
                   13484:20):                     $sts_on = 0;
                   13485:20):                 }
                   13486:20):             }
                   13487:20):             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   13488:20):         }
                   13489:20):     }
                   13490:20):     return;
                   13491:20): }
                   13492:20): 
1.31      www      13493: # ------------------------------------------------------------- Declutters URLs
                   13494: 
                   13495: sub declutter {
                   13496:     my $thisfn=shift;
1.569     albertel 13497:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  13498:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13499:         $thisfn=~s{^/home/httpd/html}{};
                   13500:     }
1.31      www      13501:     $thisfn=~s/^\///;
1.697     albertel 13502:     $thisfn=~s|^adm/wrapper/||;
                   13503:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13504:     $thisfn=~s/^res\///;
1.1172    bisitz   13505:     $thisfn=~s/^priv\///;
1.1032    raeburn  13506:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13507:         $thisfn=~s/\?.+$//;
                   13508:     }
1.268     www      13509:     return $thisfn;
                   13510: }
                   13511: 
                   13512: # ------------------------------------------------------------- Clutter up URLs
                   13513: 
                   13514: sub clutter {
                   13515:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13516:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13517: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13518:        $thisfn='/res'.$thisfn; 
                   13519:     }
1.1031    raeburn  13520:     if ($thisfn !~m|^/adm|) {
                   13521: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13522: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13523: 	} else {
                   13524: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13525: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13526: 	    if ($embstyle eq 'ssi'
                   13527: 		|| ($embstyle eq 'hdn')
                   13528: 		|| ($embstyle eq 'rat')
                   13529: 		|| ($embstyle eq 'prv')
                   13530: 		|| ($embstyle eq 'ign')) {
                   13531: 		#do nothing with these
                   13532: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13533: 		|| ($embstyle eq 'emb')
                   13534: 		|| ($embstyle eq 'wrp')) {
                   13535: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13536: 	    } elsif ($embstyle eq 'unk'
                   13537: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13538: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13539: 	    } else {
1.718     www      13540: #		&logthis("Got a blank emb style");
1.695     albertel 13541: 	    }
1.694     albertel 13542: 	}
1.1172.2.118.  .1(raebu 13543:20):     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
                   13544:20):         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 13545:     }
1.31      www      13546:     return $thisfn;
1.12      www      13547: }
                   13548: 
1.787     albertel 13549: sub clutter_with_no_wrapper {
                   13550:     my $uri = &clutter(shift);
                   13551:     if ($uri =~ m-^/adm/-) {
                   13552: 	$uri =~ s-^/adm/wrapper/-/-;
                   13553: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13554:     }
                   13555:     return $uri;
                   13556: }
                   13557: 
1.557     albertel 13558: sub freeze_escape {
                   13559:     my ($value)=@_;
                   13560:     if (ref($value)) {
                   13561: 	$value=&nfreeze($value);
                   13562: 	return '__FROZEN__'.&escape($value);
                   13563:     }
                   13564:     return &escape($value);
                   13565: }
                   13566: 
1.11      www      13567: 
1.557     albertel 13568: sub thaw_unescape {
                   13569:     my ($value)=@_;
                   13570:     if ($value =~ /^__FROZEN__/) {
                   13571: 	substr($value,0,10,undef);
                   13572: 	$value=&unescape($value);
                   13573: 	return &thaw($value);
                   13574:     }
                   13575:     return &unescape($value);
                   13576: }
                   13577: 
1.436     albertel 13578: sub correct_line_ends {
                   13579:     my ($result)=@_;
                   13580:     $$result =~s/\r\n/\n/mg;
                   13581:     $$result =~s/\r/\n/mg;
1.415     albertel 13582: }
1.1       albertel 13583: # ================================================================ Main Program
                   13584: 
1.184     www      13585: sub goodbye {
1.204     albertel 13586:    &logthis("Starting Shut down");
1.443     albertel 13587: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13588:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13589: #converted
1.599     albertel 13590: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13591:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13592: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13593: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13594: #1.1 only
1.870     albertel 13595: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13596: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13597: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13598: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13599:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13600:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13601:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13602:    &flushcourselogs();
                   13603:    &logthis("Shutting down");
                   13604: }
                   13605: 
1.852     albertel 13606: sub get_dns {
1.1172.2.17  raeburn  13607:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13608:     if (!$ignore_cache) {
                   13609: 	my ($content,$cached)=
                   13610: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13611: 	if ($cached) {
1.1172.2.17  raeburn  13612: 	    &$func($content,$hashref);
1.869     albertel 13613: 	    return;
                   13614: 	}
                   13615:     }
                   13616: 
                   13617:     my %alldns;
1.1172.2.96  raeburn  13618:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13619:         foreach my $dns (<$config>) {
                   13620: 	    next if ($dns !~ /^\^(\S*)/x);
                   13621:             my $line = $1;
                   13622:             my ($host,$protocol) = split(/:/,$line);
                   13623:             if ($protocol ne 'https') {
                   13624:                 $protocol = 'http';
                   13625:             }
                   13626: 	    $alldns{$host} = $protocol;
1.979     raeburn  13627:         }
1.1172.2.96  raeburn  13628:         close($config);
1.869     albertel 13629:     }
                   13630:     while (%alldns) {
1.1172.2.52  raeburn  13631: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 13632: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  13633:         $ua->timeout(30);
1.979     raeburn  13634: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 13635: 	my $response=$ua->request($request);
1.979     raeburn  13636:         delete($alldns{$dns});
1.852     albertel 13637: 	next if ($response->is_error());
                   13638: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  13639:         unless ($nocache) {
1.1172.2.23  raeburn  13640: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  13641:         }
                   13642: 	&$func(\@content,$hashref);
1.869     albertel 13643: 	return;
1.852     albertel 13644:     }
1.871     albertel 13645:     my $which = (split('/',$url))[3];
                   13646:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  13647:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13648:         my @content = <$config>;
                   13649:         &$func(\@content,$hashref);
                   13650:     }
1.1172.2.17  raeburn  13651:     return;
                   13652: }
                   13653: 
                   13654: # ------------------------------------------------------Get DNS checksums file
                   13655: sub parse_dns_checksums_tab {
                   13656:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  13657:     my $lonhost = $perlvar{'lonHostID'};
                   13658:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  13659:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  13660:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13661:     my $webconfdir = '/etc/httpd/conf';
                   13662:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13663:         $webconfdir = '/etc/apache2';
                   13664:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13665:         if ($1 >= 10) {
                   13666:             $webconfdir = '/etc/apache2';
                   13667:         }
                   13668:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13669:         if ($1 >= 10.0) {
                   13670:             $webconfdir = '/etc/apache2';
                   13671:         }
                   13672:     }
1.1172.2.17  raeburn  13673:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13674:     my (%chksum,%revnum);
                   13675:     if (ref($lines) eq 'ARRAY') {
                   13676:         chomp(@{$lines});
1.1172.2.34  raeburn  13677:         my $version = shift(@{$lines});
                   13678:         if ($version eq $release) {
1.1172.2.17  raeburn  13679:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  13680:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  13681:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13682:                     if ($webconfdir eq '/etc/apache2') {
                   13683:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13684:                     }
                   13685:                 }
1.1172.2.34  raeburn  13686:                 $chksum{$file} = $shasum;
                   13687:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  13688:             }
                   13689:             if (ref($hashref) eq 'HASH') {
                   13690:                 %{$hashref} = (
                   13691:                                 sums     => \%chksum,
                   13692:                                 versions => \%revnum,
                   13693:                               );
                   13694:             }
                   13695:         }
                   13696:     }
1.869     albertel 13697:     return;
1.852     albertel 13698: }
1.1172.2.17  raeburn  13699: 
                   13700: sub fetch_dns_checksums {
                   13701:     my %checksums;
1.1172.2.34  raeburn  13702:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  13703:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  13704:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13705:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  13706:              \%checksums);
                   13707:     return \%checksums;
                   13708: }
                   13709: 
1.327     albertel 13710: # ------------------------------------------------------------ Read domain file
                   13711: {
1.852     albertel 13712:     my $loaded;
1.846     albertel 13713:     my %domain;
                   13714: 
1.852     albertel 13715:     sub parse_domain_tab {
                   13716: 	my ($lines) = @_;
                   13717: 	foreach my $line (@$lines) {
                   13718: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13719: 
1.846     albertel 13720: 	    chomp($line);
1.852     albertel 13721: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13722: 	    my %this_domain;
                   13723: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13724: 			       'lang_def', 'city', 'longi', 'lati',
                   13725: 			       'primary') {
                   13726: 		$this_domain{$field} = shift(@elements);
                   13727: 	    }
                   13728: 	    $domain{$name} = \%this_domain;
1.852     albertel 13729: 	}
                   13730:     }
1.864     albertel 13731: 
                   13732:     sub reset_domain_info {
                   13733: 	undef($loaded);
                   13734: 	undef(%domain);
                   13735:     }
                   13736: 
1.852     albertel 13737:     sub load_domain_tab {
1.1172.2.70  raeburn  13738: 	my ($ignore_cache,$nocache) = @_;
                   13739: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13740: 	my $fh;
1.1172.2.96  raeburn  13741: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13742: 	    my @lines = <$fh>;
                   13743: 	    &parse_domain_tab(\@lines);
1.448     albertel 13744: 	}
1.852     albertel 13745: 	close($fh);
                   13746: 	$loaded = 1;
1.327     albertel 13747:     }
1.846     albertel 13748: 
                   13749:     sub domain {
1.852     albertel 13750: 	&load_domain_tab() if (!$loaded);
                   13751: 
1.846     albertel 13752: 	my ($name,$what) = @_;
                   13753: 	return if ( !exists($domain{$name}) );
                   13754: 
                   13755: 	if (!$what) {
                   13756: 	    return $domain{$name}{'description'};
                   13757: 	}
                   13758: 	return $domain{$name}{$what};
                   13759:     }
1.974     raeburn  13760: 
                   13761:     sub domain_info {
                   13762:         &load_domain_tab() if (!$loaded);
                   13763:         return %domain;
                   13764:     }
                   13765: 
1.327     albertel 13766: }
                   13767: 
                   13768: 
1.1       albertel 13769: # ------------------------------------------------------------- Read hosts file
                   13770: {
1.838     albertel 13771:     my %hostname;
1.844     albertel 13772:     my %hostdom;
1.845     albertel 13773:     my %libserv;
1.852     albertel 13774:     my $loaded;
1.888     albertel 13775:     my %name_to_host;
1.1074    raeburn  13776:     my %internetdom;
1.1107    raeburn  13777:     my %LC_dns_serv;
1.852     albertel 13778: 
                   13779:     sub parse_hosts_tab {
                   13780: 	my ($file) = @_;
                   13781: 	foreach my $configline (@$file) {
                   13782: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13783:             chomp($configline);
                   13784: 	    if ($configline =~ /^\^/) {
                   13785:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13786:                     $LC_dns_serv{$1} = 1;
                   13787:                 }
                   13788:                 next;
                   13789:             }
1.1074    raeburn  13790: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13791: 	    $name=~s/\s//g;
                   13792: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  13793:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13794:                     my $curr = $hostname{$id};
                   13795:                     my $skip;
                   13796:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13797:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13798:                             $skip = 1;
                   13799:                         } else {
                   13800:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13801:                         }
                   13802:                     }
                   13803:                     unless ($skip) {
                   13804:                         push(@{$name_to_host{$name}},$id);
                   13805:                     }
                   13806:                 } else {
                   13807:                     push(@{$name_to_host{$name}},$id);
                   13808:                 }
1.852     albertel 13809: 		$hostname{$id}=$name;
                   13810: 		$hostdom{$id}=$domain;
                   13811: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13812:                 if (defined($protocol)) {
                   13813:                     if ($protocol eq 'https') {
                   13814:                         $protocol{$id} = $protocol;
                   13815:                     } else {
                   13816:                         $protocol{$id} = 'http'; 
                   13817:                     }
1.968     raeburn  13818:                 } else {
1.969     raeburn  13819:                     $protocol{$id} = 'http';
1.968     raeburn  13820:                 }
1.1074    raeburn  13821:                 if (defined($intdom)) {
                   13822:                     $internetdom{$id} = $intdom;
                   13823:                 }
1.852     albertel 13824: 	    }
                   13825: 	}
                   13826:     }
1.864     albertel 13827:     
                   13828:     sub reset_hosts_info {
1.897     albertel 13829: 	&purge_remembered();
1.864     albertel 13830: 	&reset_domain_info();
                   13831: 	&reset_hosts_ip_info();
1.892     albertel 13832: 	undef(%name_to_host);
1.864     albertel 13833: 	undef(%hostname);
                   13834: 	undef(%hostdom);
                   13835: 	undef(%libserv);
                   13836: 	undef($loaded);
                   13837:     }
1.1       albertel 13838: 
1.852     albertel 13839:     sub load_hosts_tab {
1.1172.2.70  raeburn  13840: 	my ($ignore_cache,$nocache) = @_;
                   13841: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  13842: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13843: 	my @config = <$config>;
                   13844: 	&parse_hosts_tab(\@config);
                   13845: 	close($config);
                   13846: 	$loaded=1;
1.1       albertel 13847:     }
1.852     albertel 13848: 
1.838     albertel 13849:     sub hostname {
1.852     albertel 13850: 	&load_hosts_tab() if (!$loaded);
                   13851: 
1.838     albertel 13852: 	my ($lonid) = @_;
                   13853: 	return $hostname{$lonid};
                   13854:     }
1.845     albertel 13855: 
1.838     albertel 13856:     sub all_hostnames {
1.852     albertel 13857: 	&load_hosts_tab() if (!$loaded);
                   13858: 
1.838     albertel 13859: 	return %hostname;
                   13860:     }
1.845     albertel 13861: 
1.888     albertel 13862:     sub all_names {
1.1172.2.70  raeburn  13863:         my ($ignore_cache,$nocache) = @_;
                   13864: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13865: 
                   13866: 	return %name_to_host;
                   13867:     }
                   13868: 
1.974     raeburn  13869:     sub all_host_domain {
                   13870:         &load_hosts_tab() if (!$loaded);
                   13871:         return %hostdom;
                   13872:     }
                   13873: 
1.845     albertel 13874:     sub is_library {
1.852     albertel 13875: 	&load_hosts_tab() if (!$loaded);
                   13876: 
1.845     albertel 13877: 	return exists($libserv{$_[0]});
                   13878:     }
                   13879: 
                   13880:     sub all_library {
1.852     albertel 13881: 	&load_hosts_tab() if (!$loaded);
                   13882: 
1.845     albertel 13883: 	return %libserv;
                   13884:     }
                   13885: 
1.1062    droeschl 13886:     sub unique_library {
                   13887: 	#2x reverse removes all hostnames that appear more than once
                   13888:         my %unique = reverse &all_library();
                   13889:         return reverse %unique;
                   13890:     }
                   13891: 
1.841     albertel 13892:     sub get_servers {
1.852     albertel 13893: 	&load_hosts_tab() if (!$loaded);
                   13894: 
1.841     albertel 13895: 	my ($domain,$type) = @_;
                   13896: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13897: 	                                          : %hostname;
                   13898: 	my %result;
1.842     albertel 13899: 	if (ref($domain) eq 'ARRAY') {
                   13900: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13901: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13902: 		    $result{$host} = $hostname;
                   13903: 		}
                   13904: 	    }
                   13905: 	} else {
                   13906: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13907: 		if ($hostdom{$host} eq $domain) {
                   13908: 		    $result{$host} = $hostname;
                   13909: 		}
1.841     albertel 13910: 	    }
                   13911: 	}
                   13912: 	return %result;
                   13913:     }
1.845     albertel 13914: 
1.1062    droeschl 13915:     sub get_unique_servers {
                   13916:         my %unique = reverse &get_servers(@_);
                   13917: 	return reverse %unique;
                   13918:     }
                   13919: 
1.844     albertel 13920:     sub host_domain {
1.852     albertel 13921: 	&load_hosts_tab() if (!$loaded);
                   13922: 
1.844     albertel 13923: 	my ($lonid) = @_;
                   13924: 	return $hostdom{$lonid};
                   13925:     }
                   13926: 
1.841     albertel 13927:     sub all_domains {
1.852     albertel 13928: 	&load_hosts_tab() if (!$loaded);
                   13929: 
1.841     albertel 13930: 	my %seen;
                   13931: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13932: 	return @uniq;
                   13933:     }
1.1074    raeburn  13934: 
                   13935:     sub internet_dom {
                   13936:         &load_hosts_tab() if (!$loaded);
                   13937: 
                   13938:         my ($lonid) = @_;
                   13939:         return $internetdom{$lonid};
                   13940:     }
1.1107    raeburn  13941: 
                   13942:     sub is_LC_dns {
                   13943:         &load_hosts_tab() if (!$loaded);
                   13944: 
                   13945:         my ($hostname) = @_;
                   13946:         return exists($LC_dns_serv{$hostname});
                   13947:     }
                   13948: 
1.1       albertel 13949: }
                   13950: 
1.847     albertel 13951: { 
                   13952:     my %iphost;
1.856     albertel 13953:     my %name_to_ip;
                   13954:     my %lonid_to_ip;
1.869     albertel 13955: 
1.847     albertel 13956:     sub get_hosts_from_ip {
                   13957: 	my ($ip) = @_;
                   13958: 	my %iphosts = &get_iphost();
                   13959: 	if (ref($iphosts{$ip})) {
                   13960: 	    return @{$iphosts{$ip}};
                   13961: 	}
                   13962: 	return;
1.839     albertel 13963:     }
1.864     albertel 13964:     
                   13965:     sub reset_hosts_ip_info {
                   13966: 	undef(%iphost);
                   13967: 	undef(%name_to_ip);
                   13968: 	undef(%lonid_to_ip);
                   13969:     }
1.856     albertel 13970: 
                   13971:     sub get_host_ip {
                   13972: 	my ($lonid) = @_;
                   13973: 	if (exists($lonid_to_ip{$lonid})) {
                   13974: 	    return $lonid_to_ip{$lonid};
                   13975: 	}
                   13976: 	my $name=&hostname($lonid);
                   13977:    	my $ip = gethostbyname($name);
                   13978: 	return if (!$ip || length($ip) ne 4);
                   13979: 	$ip=inet_ntoa($ip);
                   13980: 	$name_to_ip{$name}   = $ip;
                   13981: 	$lonid_to_ip{$lonid} = $ip;
                   13982: 	return $ip;
                   13983:     }
1.847     albertel 13984:     
                   13985:     sub get_iphost {
1.1172.2.70  raeburn  13986: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13987: 
1.869     albertel 13988: 	if (!$ignore_cache) {
                   13989: 	    if (%iphost) {
                   13990: 		return %iphost;
                   13991: 	    }
                   13992: 	    my ($ip_info,$cached)=
                   13993: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13994: 	    if ($cached) {
                   13995: 		%iphost      = %{$ip_info->[0]};
                   13996: 		%name_to_ip  = %{$ip_info->[1]};
                   13997: 		%lonid_to_ip = %{$ip_info->[2]};
                   13998: 		return %iphost;
                   13999: 	    }
                   14000: 	}
1.894     albertel 14001: 
                   14002: 	# get yesterday's info for fallback
                   14003: 	my %old_name_to_ip;
                   14004: 	my ($ip_info,$cached)=
                   14005: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14006: 	if ($cached) {
                   14007: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14008: 	}
                   14009: 
1.1172.2.70  raeburn  14010: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14011: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14012: 	    my $ip;
                   14013: 	    if (!exists($name_to_ip{$name})) {
                   14014: 		$ip = gethostbyname($name);
                   14015: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14016: 		    if (defined($old_name_to_ip{$name})) {
                   14017: 			$ip = $old_name_to_ip{$name};
                   14018: 			&logthis("Can't find $name defaulting to old $ip");
                   14019: 		    } else {
                   14020: 			&logthis("Name $name no IP found");
                   14021: 			next;
                   14022: 		    }
                   14023: 		} else {
                   14024: 		    $ip=inet_ntoa($ip);
1.847     albertel 14025: 		}
                   14026: 		$name_to_ip{$name} = $ip;
                   14027: 	    } else {
                   14028: 		$ip = $name_to_ip{$name};
1.653     albertel 14029: 	    }
1.888     albertel 14030: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14031: 		$lonid_to_ip{$id} = $ip;
                   14032: 	    }
                   14033: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14034: 	}
1.1172.2.70  raeburn  14035:         unless ($nocache) {
                   14036: 	    &do_cache_new('iphost','iphost',
                   14037: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14038: 		          48*60*60);
                   14039:         }
1.869     albertel 14040: 
1.847     albertel 14041: 	return %iphost;
1.598     albertel 14042:     }
                   14043: 
1.992     raeburn  14044:     #
                   14045:     #  Given a DNS returns the loncapa host name for that DNS 
                   14046:     # 
                   14047:     sub host_from_dns {
                   14048:         my ($dns) = @_;
                   14049:         my @hosts;
                   14050:         my $ip;
                   14051: 
1.993     raeburn  14052:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14053:             $ip = $name_to_ip{$dns};
                   14054:         }
                   14055:         if (!$ip) {
                   14056:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14057:             if (length($ip) == 4) { 
                   14058: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14059:             }
                   14060:         }
                   14061:         if ($ip) {
                   14062: 	    @hosts = get_hosts_from_ip($ip);
                   14063: 	    return $hosts[0];
                   14064:         }
                   14065:         return undef;
1.986     foxr     14066:     }
1.992     raeburn  14067: 
1.1074    raeburn  14068:     sub get_internet_names {
                   14069:         my ($lonid) = @_;
                   14070:         return if ($lonid eq '');
                   14071:         my ($idnref,$cached)=
                   14072:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14073:         if ($cached) {
                   14074:             return $idnref;
                   14075:         }
                   14076:         my $ip = &get_host_ip($lonid);
                   14077:         my @hosts = &get_hosts_from_ip($ip);
                   14078:         my %iphost = &get_iphost();
                   14079:         my (@idns,%seen);
                   14080:         foreach my $id (@hosts) {
                   14081:             my $dom = &host_domain($id);
                   14082:             my $prim_id = &domain($dom,'primary');
                   14083:             my $prim_ip = &get_host_ip($prim_id);
                   14084:             next if ($seen{$prim_ip});
                   14085:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14086:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14087:                     my $intdom = &internet_dom($id);
                   14088:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14089:                         push(@idns,$intdom);
                   14090:                     }
                   14091:                 }
                   14092:             }
                   14093:             $seen{$prim_ip} = 1;
                   14094:         }
1.1172.2.23  raeburn  14095:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14096:     }
                   14097: 
1.986     foxr     14098: }
                   14099: 
1.1079    raeburn  14100: sub all_loncaparevs {
1.1172.2.39  raeburn  14101:     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  14102: }
                   14103: 
1.1172.2.27  raeburn  14104: # ------------------------------------------------------- Read loncaparev table
                   14105: {
                   14106:     sub load_loncaparevs {
                   14107:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  14108:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  14109:                 while (my $configline=<$config>) {
                   14110:                     chomp($configline);
                   14111:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14112:                     $loncaparevs{$hostid}=$loncaparev;
                   14113:                 }
                   14114:                 close($config);
                   14115:             }
                   14116:         }
                   14117:     }
                   14118: }
                   14119: 
                   14120: # ----------------------------------------------------- Read serverhostID table
                   14121: {
                   14122:     sub load_serverhomeIDs {
                   14123:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  14124:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  14125:                 while (my $configline=<$config>) {
                   14126:                     chomp($configline);
                   14127:                     my ($name,$id)=split(/:/,$configline);
                   14128:                     $serverhomeIDs{$name}=$id;
                   14129:                 }
                   14130:                 close($config);
                   14131:             }
                   14132:         }
                   14133:     }
                   14134: }
                   14135: 
                   14136: 
1.862     albertel 14137: BEGIN {
                   14138: 
                   14139: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14140:     unless ($readit) {
                   14141: {
                   14142:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14143:     %perlvar = (%perlvar,%{$configvars});
                   14144: }
                   14145: 
                   14146: 
1.1       albertel 14147: # ------------------------------------------------------ Read spare server file
                   14148: {
1.1172.2.96  raeburn  14149:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14150: 
                   14151:     while (my $configline=<$config>) {
                   14152:        chomp($configline);
1.284     matthew  14153:        if ($configline) {
1.784     albertel 14154: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14155: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14156: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14157:        }
                   14158:     }
1.448     albertel 14159:     close($config);
1.1       albertel 14160: }
1.11      www      14161: # ------------------------------------------------------------ Read permissions
                   14162: {
1.1172.2.96  raeburn  14163:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14164: 
                   14165:     while (my $configline=<$config>) {
1.448     albertel 14166: 	chomp($configline);
                   14167: 	if ($configline) {
                   14168: 	    my ($role,$perm)=split(/ /,$configline);
                   14169: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14170: 	}
1.11      www      14171:     }
1.448     albertel 14172:     close($config);
1.11      www      14173: }
                   14174: 
                   14175: # -------------------------------------------- Read plain texts for permissions
                   14176: {
1.1172.2.96  raeburn  14177:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14178: 
                   14179:     while (my $configline=<$config>) {
1.448     albertel 14180: 	chomp($configline);
                   14181: 	if ($configline) {
1.742     raeburn  14182: 	    my ($short,@plain)=split(/:/,$configline);
                   14183:             %{$prp{$short}} = ();
                   14184: 	    if (@plain > 0) {
                   14185:                 $prp{$short}{'std'} = $plain[0];
                   14186:                 for (my $i=1; $i<@plain; $i++) {
                   14187:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14188:                 }
                   14189:             }
1.448     albertel 14190: 	}
1.135     www      14191:     }
1.448     albertel 14192:     close($config);
1.135     www      14193: }
                   14194: 
                   14195: # ---------------------------------------------------------- Read package table
                   14196: {
1.1172.2.96  raeburn  14197:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14198: 
                   14199:     while (my $configline=<$config>) {
1.483     albertel 14200: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14201: 	chomp($configline);
                   14202: 	my ($short,$plain)=split(/:/,$configline);
                   14203: 	my ($pack,$name)=split(/\&/,$short);
                   14204: 	if ($plain ne '') {
                   14205: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14206: 	    $packagetab{$short}=$plain; 
                   14207: 	}
1.11      www      14208:     }
1.448     albertel 14209:     close($config);
1.329     matthew  14210: }
                   14211: 
1.1172.2.27  raeburn  14212: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  14213: 
1.1172.2.27  raeburn  14214: &load_loncaparevs();
                   14215: 
                   14216: # ------------------------------------------------------- Read serverhostID table
                   14217: 
                   14218: &load_serverhomeIDs();
1.1074    raeburn  14219: 
1.1172.2.27  raeburn  14220: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14221: {
                   14222:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14223:     if (-e $file) {
                   14224:         my $parser = HTML::LCParser->new($file);
                   14225:         while (my $token = $parser->get_token()) {
                   14226:             if ($token->[0] eq 'S') {
                   14227:                 my $item = $token->[1];
                   14228:                 my $name = $token->[2]{'name'};
                   14229:                 my $value = $token->[2]{'value'};
                   14230:                 if ($item ne '' && $name ne '' && $value ne '') {
                   14231:                     my $release = $parser->get_text();
                   14232:                     $release =~ s/(^\s*|\s*$ )//gx;
                   14233:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   14234:                 }
                   14235:             }
                   14236:         }
                   14237:     }
1.1073    raeburn  14238: }
                   14239: 
1.1138    raeburn  14240: # ---------------------------------------------------------- Read managers table
                   14241: {
                   14242:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  14243:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14244:             while (my $configline=<$config>) {
                   14245:                 chomp($configline);
                   14246:                 next if ($configline =~ /^\#/);
                   14247:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14248:                     $managerstab{$configline} = 1;
                   14249:                 }
                   14250:             }
                   14251:             close($config);
                   14252:         }
                   14253:     }
                   14254: }
                   14255: 
1.329     matthew  14256: # ------------- set up temporary directory
                   14257: {
1.1117    foxr     14258:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14259: 
1.11      www      14260: }
                   14261: 
1.1172.2.104  raeburn  14262: # ------------- set default texengine (domain default overrides this)
                   14263: {
                   14264:     $deftex = LONCAPA::texengine();
                   14265: }
                   14266: 
1.1172.2.114  raeburn  14267: # ------------- set default minimum length for passwords for internal auth users
                   14268: {
                   14269:     $passwdmin = LONCAPA::passwd_min();
                   14270: }
                   14271: 
1.794     albertel 14272: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14273: 				'compress_threshold'=> 20_000,
                   14274:  			        });
1.185     www      14275: 
1.281     www      14276: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14277: $dumpcount=0;
1.958     www      14278: $locknum=0;
1.22      www      14279: 
1.163     harris41 14280: &logtouch();
1.672     albertel 14281: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14282: $readit=1;
1.564     albertel 14283:     {
                   14284: 	use integer;
                   14285: 	my $test=(2**32)+1;
1.568     albertel 14286: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14287: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14288:     }
1.195     www      14289: }
1.1       albertel 14290: }
1.179     www      14291: 
1.1       albertel 14292: 1;
1.191     harris41 14293: __END__
                   14294: 
1.243     albertel 14295: =pod
                   14296: 
1.191     harris41 14297: =head1 NAME
                   14298: 
1.243     albertel 14299: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14300: 
                   14301: =head1 SYNOPSIS
                   14302: 
1.243     albertel 14303: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14304: 
                   14305:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14306: 
1.243     albertel 14307: Common parameters:
                   14308: 
                   14309: =over 4
                   14310: 
                   14311: =item *
                   14312: 
                   14313: $uname : an internal username (if $cname expecting a course Id specifically)
                   14314: 
                   14315: =item *
                   14316: 
                   14317: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14318: 
                   14319: =item *
                   14320: 
                   14321: $symb : a resource instance identifier
                   14322: 
                   14323: =item *
                   14324: 
                   14325: $namespace : the name of a .db file that contains the data needed or
                   14326: being set.
                   14327: 
                   14328: =back
                   14329: 
1.394     bowersj2 14330: =head1 OVERVIEW
1.191     harris41 14331: 
1.394     bowersj2 14332: lonnet provides subroutines which interact with the
                   14333: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14334: about classes, users, and resources.
1.243     albertel 14335: 
                   14336: For many of these objects you can also use this to store data about
                   14337: them or modify them in various ways.
1.191     harris41 14338: 
1.394     bowersj2 14339: =head2 Symbs
1.191     harris41 14340: 
1.394     bowersj2 14341: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14342: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14343: map, the resource number of the resource in the map, and the URL of
                   14344: the resource itself. The latter is somewhat redundant, but might help
                   14345: if maps change.
                   14346: 
                   14347: An example is
                   14348: 
                   14349:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14350: 
                   14351: The respective map entry is
                   14352: 
                   14353:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14354:   title="Problem 2">
                   14355:  </resource>
                   14356: 
                   14357: Symbs are used by the random number generator, as well as to store and
                   14358: restore data specific to a certain instance of for example a problem.
                   14359: 
                   14360: =head2 Storing And Retrieving Data
                   14361: 
                   14362: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14363: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14364: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14365: is is the non-critical message twin of cstore. These functions are for
                   14366: handlers to store a perl hash to a user's permanent data space in an
                   14367: easy manner, and to retrieve it again on another call. It is expected
                   14368: that a handler would use this once at the beginning to retrieve data,
                   14369: and then again once at the end to send only the new data back.
                   14370: 
                   14371: The data is stored in the user's data directory on the user's
                   14372: homeserver under the ID of the course.
                   14373: 
                   14374: The hash that is returned by restore will have all of the previous
                   14375: value for all of the elements of the hash.
                   14376: 
                   14377: Example:
                   14378: 
                   14379:  #creating a hash
                   14380:  my %hash;
                   14381:  $hash{'foo'}='bar';
                   14382: 
                   14383:  #storing it
                   14384:  &Apache::lonnet::cstore(\%hash);
                   14385: 
                   14386:  #changing a value
                   14387:  $hash{'foo'}='notbar';
                   14388: 
                   14389:  #adding a new value
                   14390:  $hash{'bar'}='foo';
                   14391:  &Apache::lonnet::cstore(\%hash);
                   14392: 
                   14393:  #retrieving the hash
                   14394:  my %history=&Apache::lonnet::restore();
                   14395: 
                   14396:  #print the hash
                   14397:  foreach my $key (sort(keys(%history))) {
                   14398:    print("\%history{$key} = $history{$key}");
                   14399:  }
                   14400: 
                   14401: Will print out:
1.191     harris41 14402: 
1.394     bowersj2 14403:  %history{1:foo} = bar
                   14404:  %history{1:keys} = foo:timestamp
                   14405:  %history{1:timestamp} = 990455579
                   14406:  %history{2:bar} = foo
                   14407:  %history{2:foo} = notbar
                   14408:  %history{2:keys} = foo:bar:timestamp
                   14409:  %history{2:timestamp} = 990455580
                   14410:  %history{bar} = foo
                   14411:  %history{foo} = notbar
                   14412:  %history{timestamp} = 990455580
                   14413:  %history{version} = 2
                   14414: 
                   14415: Note that the special hash entries C<keys>, C<version> and
                   14416: C<timestamp> were added to the hash. C<version> will be equal to the
                   14417: total number of versions of the data that have been stored. The
                   14418: C<timestamp> attribute will be the UNIX time the hash was
                   14419: stored. C<keys> is available in every historical section to list which
                   14420: keys were added or changed at a specific historical revision of a
                   14421: hash.
                   14422: 
                   14423: B<Warning>: do not store the hash that restore returns directly. This
                   14424: will cause a mess since it will restore the historical keys as if the
                   14425: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14426: 
1.394     bowersj2 14427: Calling convention:
1.191     harris41 14428: 
1.1172.2.27  raeburn  14429:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  14430:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14431: 
1.394     bowersj2 14432: For more detailed information, see lonnet specific documentation.
1.191     harris41 14433: 
1.394     bowersj2 14434: =head1 RETURN MESSAGES
1.191     harris41 14435: 
1.394     bowersj2 14436: =over 4
1.191     harris41 14437: 
1.394     bowersj2 14438: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14439: 
1.394     bowersj2 14440: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14441: when the connection is brought back up
1.191     harris41 14442: 
1.394     bowersj2 14443: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14444: for later delivery
1.191     harris41 14445: 
1.967     bisitz   14446: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14447: 
1.394     bowersj2 14448: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14449: that was requested
1.191     harris41 14450: 
1.243     albertel 14451: =back
1.191     harris41 14452: 
1.243     albertel 14453: =head1 PUBLIC SUBROUTINES
1.191     harris41 14454: 
1.243     albertel 14455: =head2 Session Environment Functions
1.191     harris41 14456: 
1.243     albertel 14457: =over 4
1.191     harris41 14458: 
1.394     bowersj2 14459: =item * 
                   14460: X<appenv()>
1.949     raeburn  14461: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14462: the user envirnoment file, and will be restored for each access this
1.620     albertel 14463: user makes during this session, also modifies the %env for the current
1.949     raeburn  14464: process. Optional rolesarrayref - if defined contains a reference to an array
                   14465: of roles which are exempt from the restriction on modifying user.role entries 
                   14466: in the user's environment.db and in %env.    
1.191     harris41 14467: 
                   14468: =item *
1.394     bowersj2 14469: X<delenv()>
1.987     raeburn  14470: B<delenv($delthis,$regexp)>: removes all items from the session
                   14471: environment file that begin with $delthis. If the 
                   14472: optional second arg - $regexp - is true, $delthis is treated as a 
                   14473: regular expression, otherwise \Q$delthis\E is used. 
                   14474: The values are also deleted from the current processes %env.
1.191     harris41 14475: 
1.795     albertel 14476: =item * get_env_multiple($name) 
                   14477: 
                   14478: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14479: values may be defined and end up as an array ref.
                   14480: 
                   14481: returns an array of values
                   14482: 
1.243     albertel 14483: =back
                   14484: 
                   14485: =head2 User Information
1.191     harris41 14486: 
1.243     albertel 14487: =over 4
1.191     harris41 14488: 
                   14489: =item *
1.394     bowersj2 14490: X<queryauthenticate()>
                   14491: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14492: authentication scheme
                   14493: 
                   14494: =item *
1.394     bowersj2 14495: X<authenticate()>
1.1073    raeburn  14496: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14497: authenticate user from domain's lib servers (first use the current
                   14498: one). C<$upass> should be the users password.
1.1073    raeburn  14499: $checkdefauth is optional (value is 1 if a check should be made to
                   14500:    authenticate user using default authentication method, and allow
                   14501:    account creation if username does not have account in the domain).
                   14502: $clientcancheckhost is optional (value is 1 if checking whether the
                   14503:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14504: 
                   14505: =item *
1.394     bowersj2 14506: X<homeserver()>
                   14507: B<homeserver($uname,$udom)>: find the server which has
                   14508: the user's directory and files (there must be only one), this caches
                   14509: the answer, and also caches if there is a borken connection.
1.191     harris41 14510: 
                   14511: =item *
1.394     bowersj2 14512: X<idget()>
                   14513: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   14514: (IDs are a unique resource in a domain, there must be only 1 ID per
                   14515: username, and only 1 username per ID in a specific domain) (returns
                   14516: hash: id=>name,id=>name)
1.191     harris41 14517: 
                   14518: =item *
1.394     bowersj2 14519: X<idrget()>
                   14520: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14521: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14522: 
                   14523: =item *
1.394     bowersj2 14524: X<idput()>
                   14525: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 14526: 
                   14527: =item *
1.394     bowersj2 14528: X<rolesinit()>
1.1169    droeschl 14529: B<rolesinit($udom,$username)>: get user privileges.
                   14530: returns user role, first access and timer interval hashes
1.243     albertel 14531: 
                   14532: =item *
1.1171    droeschl 14533: X<privileged()>
                   14534: B<privileged($username,$domain)>: returns a true if user has a
                   14535: privileged and active role (i.e. su or dc), false otherwise.
                   14536: 
                   14537: =item *
1.551     albertel 14538: X<getsection()>
                   14539: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14540: course $cname, return section name/number or '' for "not in course"
                   14541: and '-1' for "no section"
                   14542: 
                   14543: =item *
1.394     bowersj2 14544: X<userenvironment()>
                   14545: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14546: passed in @what from the requested user's environment, returns a hash
                   14547: 
1.858     raeburn  14548: =item * 
                   14549: X<userlog_query()>
1.859     albertel 14550: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14551: activity.log file. %filters defines filters applied when parsing the
                   14552: log file. These can be start or end timestamps, or the type of action
                   14553: - log to look for Login or Logout events, check for Checkin or
                   14554: Checkout, role for role selection. The response is in the form
                   14555: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14556: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14557: 
1.243     albertel 14558: =back
                   14559: 
                   14560: =head2 User Roles
                   14561: 
                   14562: =over 4
                   14563: 
                   14564: =item *
                   14565: 
1.1172.2.65  raeburn  14566: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14567: returns codes for allowed actions.
                   14568: 
                   14569: The first argument is required, all others are optional.
                   14570: 
                   14571: $priv is the privilege being checked.
                   14572: $uri contains additional information about what is being checked for access (e.g.,
                   14573: URL, course ID etc.).
                   14574: $symb is the unique resource instance identifier in a course; if needed,
                   14575: but not provided, it will be retrieved via a call to &symbread().
                   14576: $role is the role for which a priv is being checked (only used if priv is evb).
                   14577: $clientip is the user's IP address (only used when checking for access to portfolio
                   14578: files).
                   14579: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   14580: prevents recursive calls to &allowed.
                   14581: 
1.243     albertel 14582:  F: full access
                   14583:  U,I,K: authentication modes (cxx only)
                   14584:  '': forbidden
                   14585:  1: user needs to choose course
                   14586:  2: browse allowed
1.766     albertel 14587:  A: passphrase authentication needed
1.1172.2.65  raeburn  14588:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14589: 
                   14590: =item *
                   14591: 
1.1172.2.13  raeburn  14592: constructaccess($url,$setpriv) : check for access to construction space URL
                   14593: 
                   14594: See if the owner domain and name in the URL match those in the
                   14595: expected environment.  If so, return three element list
                   14596: ($ownername,$ownerdomain,$ownerhome).
                   14597: 
                   14598: Otherwise return the null string.
                   14599: 
                   14600: If second argument 'setpriv' is true, it assigns the privileges,
                   14601: and returns the same three element list, unless the owner has
                   14602: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14603: in which case the null string is returned.
                   14604: 
                   14605: =item *
                   14606: 
1.1172.2.84  raeburn  14607: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14608: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14609: for system, domain, and course level. $uname and $udom are optional (current
                   14610: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14611: 
                   14612: =item *
                   14613: 
1.988     raeburn  14614: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14615: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14616: $type is Course (default) or Community.
1.988     raeburn  14617: If $forcedefault evaluates to true, text returned will be default 
                   14618: text for $type. Otherwise, if this is a course, the text returned 
                   14619: will be a custom name for the role (if defined in the course's 
                   14620: environment).  If no custom name is defined the default is returned.
                   14621:    
1.832     raeburn  14622: =item *
                   14623: 
1.1172.2.23  raeburn  14624: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14625: All arguments are optional. Returns a hash of a roles, either for
                   14626: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14627: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14628: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14629: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14630: For each key, value is set to colon-separated start and end times for
                   14631: the role.  If no username and domain are specified, will default to
1.934     raeburn  14632: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14633: of role statuses (active, future or previous), roles 
                   14634: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14635: to restrict the list of roles reported. If no array ref is 
                   14636: provided for types, will default to return only active roles.
1.834     albertel 14637: 
1.1172.2.13  raeburn  14638: =item *
                   14639: 
                   14640: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   14641: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   14642: 
                   14643: Additional optional arguments are: $type (if role checking is to be restricted
                   14644: to certain user status types -- previous (expired roles), active (currently
                   14645: available roles) or future (roles available in the future), and
                   14646: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  14647: have active Domain Coordinator role in course's domain or in additional
                   14648: domains (specified in 'Domains to check for privileged users' in course
                   14649: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14650: 
                   14651: =item *
                   14652: 
                   14653: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14654: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14655: $possdomains and $possroles are optional array refs -- to domains to check and
                   14656: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14657: users' roles.db to check for a dc or su role in any domain. This can be
                   14658: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14659: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14660: this then allows &privileged_by_domain() to be used, which caches the identity
                   14661: of privileged users, eliminating the need for repeated calls to &dump().
                   14662: 
                   14663: =item *
                   14664: 
                   14665: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14666: where the outer hash keys are domains specified in the $possdomains array ref,
                   14667: next inner hash keys are privileged roles specified in the $roles array ref,
                   14668: and the innermost hash contains key = value pairs for username:domain = end:start
                   14669: for active or future "privileged" users with that role in that domain. To avoid
                   14670: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14671: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  14672: 
1.243     albertel 14673: =back
                   14674: 
                   14675: =head2 User Modification
                   14676: 
                   14677: =over 4
                   14678: 
                   14679: =item *
                   14680: 
1.957     raeburn  14681: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14682: user for the level given by URL.  Optional start and end dates (leave empty
                   14683: string or zero for "no date")
1.191     harris41 14684: 
                   14685: =item *
                   14686: 
1.243     albertel 14687: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14688: change a users, password, possible return values are: ok,
                   14689: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14690: refused
1.191     harris41 14691: 
                   14692: =item *
                   14693: 
1.243     albertel 14694: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14695: 
                   14696: =item *
                   14697: 
1.1058    raeburn  14698: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14699:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14700: 
                   14701: will update user information (firstname,middlename,lastname,generation,
                   14702: permanentemail), and if forceid is true, student/employee ID also.
                   14703: A user's institutional affiliation(s) can also be updated.
                   14704: User information fields will not be overwritten with empty entries 
                   14705: unless the field is included in the $candelete array reference.
                   14706: This array is included when a single user is modified via "Manage Users",
                   14707: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14708: 
                   14709: =item *
                   14710: 
1.286     matthew  14711: modifystudent
                   14712: 
1.957     raeburn  14713: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  14714: The course id is resolved based on the current user's environment.  
                   14715: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14716: associated with a course.
                   14717: 
1.297     matthew  14718: This call is essentially a wrapper for lonnet::modifyuser and
                   14719: lonnet::modify_student_enrollment
1.286     matthew  14720: 
                   14721: Inputs: 
                   14722: 
                   14723: =over 4
                   14724: 
1.957     raeburn  14725: =item B<$udom> Student's loncapa domain
1.286     matthew  14726: 
1.957     raeburn  14727: =item B<$uname> Student's loncapa login name
1.286     matthew  14728: 
1.964     bisitz   14729: =item B<$uid> Student/Employee ID
1.286     matthew  14730: 
1.957     raeburn  14731: =item B<$umode> Student's authentication mode
1.286     matthew  14732: 
1.957     raeburn  14733: =item B<$upass> Student's password
1.286     matthew  14734: 
1.957     raeburn  14735: =item B<$first> Student's first name
1.286     matthew  14736: 
1.957     raeburn  14737: =item B<$middle> Student's middle name
1.286     matthew  14738: 
1.957     raeburn  14739: =item B<$last> Student's last name
1.286     matthew  14740: 
1.957     raeburn  14741: =item B<$gene> Student's generation
1.286     matthew  14742: 
1.957     raeburn  14743: =item B<$usec> Student's section in course
1.286     matthew  14744: 
                   14745: =item B<$end> Unix time of the roles expiration
                   14746: 
                   14747: =item B<$start> Unix time of the roles start date
                   14748: 
                   14749: =item B<$forceid> If defined, allow $uid to be changed
                   14750: 
                   14751: =item B<$desiredhome> server to use as home server for student
                   14752: 
1.957     raeburn  14753: =item B<$email> Student's permanent e-mail address
                   14754: 
                   14755: =item B<$type> Type of enrollment (auto or manual)
                   14756: 
1.963     raeburn  14757: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14758: 
                   14759: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14760: 
1.963     raeburn  14761: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14762: 
1.963     raeburn  14763: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14764: 
1.1172.2.19  raeburn  14765: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14766: 
                   14767: =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  14768: 
1.286     matthew  14769: =back
1.297     matthew  14770: 
                   14771: =item *
                   14772: 
                   14773: modify_student_enrollment
                   14774: 
1.1172.2.31  raeburn  14775: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14776: 'role.request.course' must be defined for this function to proceed.
                   14777: 
                   14778: Inputs:
                   14779: 
                   14780: =over 4
                   14781: 
1.1172.2.31  raeburn  14782: =item $udom, student's domain
1.297     matthew  14783: 
1.1172.2.31  raeburn  14784: =item $uname, student's name
1.297     matthew  14785: 
1.1172.2.31  raeburn  14786: =item $uid, student's user id
1.297     matthew  14787: 
1.1172.2.31  raeburn  14788: =item $first, student's first name
1.297     matthew  14789: 
                   14790: =item $middle
                   14791: 
                   14792: =item $last
                   14793: 
                   14794: =item $gene
                   14795: 
                   14796: =item $usec
                   14797: 
                   14798: =item $end
                   14799: 
                   14800: =item $start
                   14801: 
1.957     raeburn  14802: =item $type
                   14803: 
                   14804: =item $locktype
                   14805: 
                   14806: =item $cid
                   14807: 
                   14808: =item $selfenroll
                   14809: 
                   14810: =item $context
                   14811: 
1.1172.2.19  raeburn  14812: =item $credits, number of credits student will earn from this class
                   14813: 
1.1172.2.76  raeburn  14814: =item $instsec, institutional course section code for student
                   14815: 
1.297     matthew  14816: =back
                   14817: 
1.191     harris41 14818: 
                   14819: =item *
                   14820: 
1.243     albertel 14821: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14822: custom role; give a custom role to a user for the level given by URL.  Specify
                   14823: name and domain of role author, and role name
1.191     harris41 14824: 
                   14825: =item *
                   14826: 
1.243     albertel 14827: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14828: 
                   14829: =item *
                   14830: 
1.243     albertel 14831: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14832: 
                   14833: =back
                   14834: 
                   14835: =head2 Course Infomation
                   14836: 
                   14837: =over 4
1.191     harris41 14838: 
                   14839: =item *
                   14840: 
1.1118    foxr     14841: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14842: specified course id, including all environment settings for the
                   14843: course, the description of the course will be in the hash under the
                   14844: key 'description'
1.191     harris41 14845: 
1.1118    foxr     14846: $options is an optional parameter that if supplied is a hash reference that controls
                   14847: what how this function works.  It has the following key/values:
                   14848: 
                   14849: =over 4
                   14850: 
                   14851: =item freshen_cache
                   14852: 
                   14853: If defined, and the environment cache for the course is valid, it is 
                   14854: returned in the returned hash.
                   14855: 
                   14856: =item one_time
                   14857: 
                   14858: If defined, the last cache time is set to _now_
                   14859: 
                   14860: =item user
                   14861: 
                   14862: If defined, the supplied username is used instead of the current user.
                   14863: 
                   14864: 
                   14865: =back
                   14866: 
1.191     harris41 14867: =item *
                   14868: 
1.624     albertel 14869: resdata($name,$domain,$type,@which) : request for current parameter
                   14870: setting for a specific $type, where $type is either 'course' or 'user',
                   14871: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  14872: answers for 10 minutes.
1.243     albertel 14873: 
1.877     foxr     14874: =item *
                   14875: 
                   14876: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14877: data base, returning a hash that is keyed by the resource name and has
                   14878: values that are the resource value.  I believe that the timestamps and
                   14879: versions are also returned.
                   14880: 
1.1172.2.31  raeburn  14881: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14882: supplemental content area. This routine caches the number of files for
                   14883: 10 minutes.
                   14884: 
1.243     albertel 14885: =back
                   14886: 
                   14887: =head2 Course Modification
                   14888: 
                   14889: =over 4
1.191     harris41 14890: 
                   14891: =item *
                   14892: 
1.243     albertel 14893: writecoursepref($courseid,%prefs) : write preferences (environment
                   14894: database) for a course
1.191     harris41 14895: 
                   14896: =item *
                   14897: 
1.1011    raeburn  14898: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14899: 
                   14900: =item *
                   14901: 
1.1038    raeburn  14902: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14903: 
1.1167    droeschl 14904: =item *
                   14905: 
                   14906: is_course($courseid), is_course($cdom, $cnum)
                   14907: 
                   14908: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14909: two component version $cdom, $cnum. It checks if the specified course exists.
                   14910: 
                   14911: Returns:
                   14912:     undef if the course doesn't exist, otherwise
                   14913:     in scalar context the combined courseid.
                   14914:     in list context the two components of the course identifier, domain and 
                   14915:     courseid.    
                   14916: 
1.243     albertel 14917: =back
                   14918: 
1.1172.2.109  raeburn  14919: =head2 Bubblesheet Configuration
                   14920: 
                   14921: =over 4
                   14922: 
                   14923: =item *
                   14924: 
                   14925: get_scantron_config($which)
                   14926: 
                   14927: $which - the name of the configuration to parse from the file.
                   14928: 
                   14929: Parses and returns the bubblesheet configuration line selected as a
                   14930: hash of configuration file fields.
                   14931: 
                   14932: 
                   14933: Returns:
                   14934:     If the named configuration is not in the file, an empty
                   14935:     hash is returned.
                   14936: 
                   14937:     a hash with the fields
                   14938:       name         - internal name for the this configuration setup
                   14939:       description  - text to display to operator that describes this config
                   14940:       CODElocation - if 0 or the string 'none'
                   14941:                           - no CODE exists for this config
                   14942:                      if -1 || the string 'letter'
                   14943:                           - a CODE exists for this config and is
                   14944:                             a string of letters
                   14945:                      Unsupported value (but planned for future support)
                   14946:                           if a positive integer
                   14947:                                - The CODE exists as the first n items from
                   14948:                                  the question section of the form
                   14949:                           if the string 'number'
                   14950:                                - The CODE exists for this config and is
                   14951:                                  a string of numbers
                   14952:       CODEstart   - (only matter if a CODE exists) column in the line where
                   14953:                      the CODE starts
                   14954:       CODElength  - length of the CODE
                   14955:       IDstart     - column where the student/employee ID starts
                   14956:       IDlength    - length of the student/employee ID info
                   14957:       Qstart      - column where the information from the bubbled
                   14958:                     'questions' start
                   14959:       Qlength     - number of columns comprising a single bubble line from
                   14960:                     the sheet. (usually either 1 or 10)
                   14961:       Qon         - either a single character representing the character used
                   14962:                     to signal a bubble was chosen in the positional setup, or
                   14963:                     the string 'letter' if the letter of the chosen bubble is
                   14964:                     in the final, or 'number' if a number representing the
                   14965:                     chosen bubble is in the file (1->A 0->J)
                   14966:       Qoff        - the character used to represent that a bubble was
                   14967:                     left blank
                   14968:       PaperID     - if the scanning process generates a unique number for each
                   14969:                     sheet scanned the column that this ID number starts in
                   14970:       PaperIDlength - number of columns that comprise the unique ID number
                   14971:                       for the sheet of paper
                   14972:       FirstName   - column that the first name starts in
                   14973:       FirstNameLength - number of columns that the first name spans
                   14974:       LastName    - column that the last name starts in
                   14975:       LastNameLength - number of columns that the last name spans
                   14976:       BubblesPerRow - number of bubbles available in each row used to
                   14977:                       bubble an answer. (If not specified, 10 assumed).
                   14978: 
                   14979: 
                   14980: =item *
                   14981: 
                   14982: get_scantronformat_file($cdom)
                   14983: 
                   14984: $cdom - the course's domain (optional); if not supplied, uses
                   14985: domain for current $env{'request.course.id'}.
                   14986: 
                   14987: Returns an array containing lines from the scantron format file for
                   14988: the domain of the course.
                   14989: 
                   14990: If a url for a custom.tab file is listed in domain's configuration.db,
                   14991: lines are from this file.
                   14992: 
                   14993: Otherwise, if a default.tab has been published in RES space by the
                   14994: domainconfig user, lines are from this file.
                   14995: 
                   14996: Otherwise, fall back to getting lines from the legacy file on the
                   14997: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   14998: 
                   14999: =back
                   15000: 
1.243     albertel 15001: =head2 Resource Subroutines
                   15002: 
                   15003: =over 4
1.191     harris41 15004: 
                   15005: =item *
                   15006: 
1.243     albertel 15007: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 15008: 
                   15009: =item *
                   15010: 
1.243     albertel 15011: repcopy($filename) : subscribes to the requested file, and attempts to
                   15012: replicate from the owning library server, Might return
1.607     raeburn  15013: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   15014: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 15015: resource. Expects the local filesystem pathname
                   15016: (/home/httpd/html/res/....)
                   15017: 
                   15018: =back
                   15019: 
                   15020: =head2 Resource Information
                   15021: 
                   15022: =over 4
1.191     harris41 15023: 
                   15024: =item *
                   15025: 
1.1172.2.28  raeburn  15026: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   15027: and returns the value of a variety of different possible values,
                   15028: $varname should be a request string, and the other parameters can be
                   15029: used to specify who and what one is asking about. Ordinarily, $cid 
                   15030: does not need to be specified, as it is retrived from 
                   15031: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   15032: within lonuserstate::loadmap() when initializing a course, before
                   15033: $env{'request.course.id'} has been set, so it needs to be provided
                   15034: in that one case.
1.243     albertel 15035: 
                   15036: Possible values for $varname are environment.lastname (or other item
                   15037: from the envirnment hash), user.name (or someother aspect about the
                   15038: user), resource.0.maxtries (or some other part and parameter of a
                   15039: resource)
1.204     albertel 15040: 
                   15041: =item *
                   15042: 
1.243     albertel 15043: directcondval($number) : get current value of a condition; reads from a state
                   15044: string
1.204     albertel 15045: 
                   15046: =item *
                   15047: 
1.243     albertel 15048: condval($condidx) : value of condition index based on state
1.204     albertel 15049: 
                   15050: =item *
                   15051: 
1.243     albertel 15052: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   15053: resource's metadata, $what should be either a specific key, or either
                   15054: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   15055: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   15056: 
                   15057: this function automatically caches all requests
1.191     harris41 15058: 
                   15059: =item *
                   15060: 
1.243     albertel 15061: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15062: network of library servers; returns file handle of where SQL and regex results
                   15063: will be stored for query
1.191     harris41 15064: 
                   15065: =item *
                   15066: 
1.1172.2.66  raeburn  15067: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   15068: return symbolic list entry (all arguments optional).
                   15069: 
                   15070: Args: filename is the filename (including path) for the file for which a symb
                   15071: is required; donotrecurse, if true will prevent calls to allowed() being made
                   15072: to check access status if more than one resource was found in the bighash
                   15073: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   15074: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   15075: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15076: cause possible symbs to be checked to determine if they are subject to content
                   15077: blocking, if so they will not be included as possible symbs; possibles is a
                   15078: ref to a hash, which, as a side effect, will be populated with all possible
                   15079: symbs (content blocking not tested).
                   15080: 
1.243     albertel 15081: returns the data handle
1.191     harris41 15082: 
                   15083: =item *
                   15084: 
1.1172.2.17  raeburn  15085: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  15086: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15087: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  15088: on failure, user must be in a course, as it assumes the existence of
                   15089: the course initial hash, and uses $env('request.course.id'}.  The third
                   15090: arg is an optional reference to a scalar.  If this arg is passed in the
                   15091: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15092: encrypted; otherwise it will be null.
1.243     albertel 15093: 
1.191     harris41 15094: =item *
                   15095: 
1.243     albertel 15096: symbclean($symb) : removes versions numbers from a symb, returns the
                   15097: cleaned symb
1.191     harris41 15098: 
                   15099: =item *
                   15100: 
1.243     albertel 15101: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15102: course map, user must be in a course for it to work.
1.191     harris41 15103: 
                   15104: =item *
                   15105: 
1.243     albertel 15106: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15107: 
                   15108: =item *
                   15109: 
1.243     albertel 15110: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15111: a random seed, all arguments are optional, if they aren't sent it uses the
                   15112: environment to derive them. Note: if symb isn't sent and it can't get one
                   15113: from &symbread it will use the current time as its return value
1.191     harris41 15114: 
                   15115: =item *
                   15116: 
1.243     albertel 15117: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15118: unfakeable, receipt
1.191     harris41 15119: 
                   15120: =item *
                   15121: 
1.620     albertel 15122: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15123: 
                   15124: =item *
                   15125: 
1.243     albertel 15126: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15127: 
                   15128: =item *
                   15129: 
1.243     albertel 15130: 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 15131: 
                   15132: =item *
                   15133: 
1.243     albertel 15134: 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 15135: 
                   15136: =item *
                   15137: 
1.243     albertel 15138: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15139: 
                   15140: =item *
                   15141: 
1.243     albertel 15142: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15143: forcing spreadsheet to reevaluate the resource scores next time.
                   15144: 
1.1172.2.13  raeburn  15145: =item *
                   15146: 
                   15147: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15148: when viewing in course context.
                   15149: 
                   15150:  input: six args -- filename (decluttered), course number, course domain,
                   15151:                     url, symb (if registered) and group (if this is a
                   15152:                     group item -- e.g., bulletin board, group page etc.).
                   15153: 
                   15154:  output: array of five scalars --
                   15155:          $cfile -- url for file editing if editable on current server
                   15156:          $home -- homeserver of resource (i.e., for author if published,
                   15157:                                           or course if uploaded.).
                   15158:          $switchserver --  1 if server switch will be needed.
                   15159:          $forceedit -- 1 if icon/link should be to go to edit mode
                   15160:          $forceview -- 1 if icon/link should be to go to view mode
                   15161: 
                   15162: =item *
                   15163: 
                   15164: is_course_upload($file,$cnum,$cdom)
                   15165: 
                   15166: Used in course context to determine if current file was uploaded to
                   15167: the course (i.e., would be found in /userfiles/docs on the course's
                   15168: homeserver.
                   15169: 
                   15170:   input: 3 args -- filename (decluttered), course number and course domain.
                   15171:   output: boolean -- 1 if file was uploaded.
                   15172: 
1.243     albertel 15173: =back
                   15174: 
                   15175: =head2 Storing/Retreiving Data
                   15176: 
                   15177: =over 4
1.191     harris41 15178: 
                   15179: =item *
                   15180: 
1.1172.2.64  raeburn  15181: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   15182: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15183: the remaining args aren't required and if they aren't passed or are '' they will
                   15184: be derived from the env (with the exception of $laststore, which is an
                   15185: optional arg used when a user's submission is stored in grading).
                   15186: $laststore is $version=$timestamp, where $version is the most recent version
                   15187: number retrieved for the corresponding $symb in the $namespace db file, and
                   15188: $timestamp is the timestamp for that transaction (UNIX time).
                   15189: $laststore is currently only passed when cstore() is called by
                   15190: structuretags::finalize_storage().
1.191     harris41 15191: 
                   15192: =item *
                   15193: 
1.1172.2.64  raeburn  15194: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   15195: but uses critical subroutine
1.191     harris41 15196: 
                   15197: =item *
                   15198: 
1.243     albertel 15199: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15200: all args are optional
1.191     harris41 15201: 
                   15202: =item *
                   15203: 
1.717     albertel 15204: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15205: dumps the complete (or key matching regexp) namespace into a hash
                   15206: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15207: normally &store()ed into
                   15208: 
                   15209: $range should be either an integer '100' (give me the first 100
                   15210:                                            matching records)
                   15211:               or be  two integers sperated by a - with no spaces
                   15212:                  '30-50' (give me the 30th through the 50th matching
                   15213:                           records)
                   15214: 
                   15215: 
                   15216: =item *
                   15217: 
1.1172.2.59  raeburn  15218: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15219: replaces a &store() version of data with a replacement set of data
                   15220: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  15221: reference. If $tolog is true, the transaction is logged in the courselog
                   15222: with an action=PUTSTORE.
1.717     albertel 15223: 
                   15224: =item *
                   15225: 
1.243     albertel 15226: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15227: works very similar to store/cstore, but all data is stored in a
                   15228: temporary location and can be reset using tmpreset, $storehash should
                   15229: be a hash reference, returns nothing on success
1.191     harris41 15230: 
                   15231: =item *
                   15232: 
1.243     albertel 15233: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15234: similar to restore, but all data is stored in a temporary location and
                   15235: can be reset using tmpreset. Returns a hash of values on success,
                   15236: error string otherwise.
1.191     harris41 15237: 
                   15238: =item *
                   15239: 
1.243     albertel 15240: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15241: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15242: 
                   15243: =item *
                   15244: 
1.243     albertel 15245: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15246: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15247: 
                   15248: =item *
                   15249: 
1.243     albertel 15250: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15251: namesp ($udom and $uname are optional)
1.191     harris41 15252: 
                   15253: =item *
                   15254: 
1.702     albertel 15255: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15256: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15257: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15258: 
1.702     albertel 15259: $range should be either an integer '100' (give me the first 100
                   15260:                                            matching records)
                   15261:               or be  two integers sperated by a - with no spaces
                   15262:                  '30-50' (give me the 30th through the 50th matching
                   15263:                           records)
1.449     matthew  15264: =item *
                   15265: 
                   15266: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15267: $store can be a scalar, an array reference, or if the amount to be 
                   15268: incremented is > 1, a hash reference.
                   15269: 
                   15270: ($udom and $uname are optional)
1.191     harris41 15271: 
                   15272: =item *
                   15273: 
1.243     albertel 15274: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15275: ($udom and $uname are optional)
1.191     harris41 15276: 
                   15277: =item *
                   15278: 
1.243     albertel 15279: cput($namespace,$storehash,$udom,$uname) : critical put
                   15280: ($udom and $uname are optional)
1.191     harris41 15281: 
                   15282: =item *
                   15283: 
1.748     albertel 15284: newput($namespace,$storehash,$udom,$uname) :
                   15285: 
                   15286: Attempts to store the items in the $storehash, but only if they don't
                   15287: currently exist, if this succeeds you can be certain that you have 
                   15288: successfully created a new key value pair in the $namespace db.
                   15289: 
                   15290: 
                   15291: Args:
                   15292:  $namespace: name of database to store values to
                   15293:  $storehash: hashref to store to the db
                   15294:  $udom: (optional) domain of user containing the db
                   15295:  $uname: (optional) name of user caontaining the db
                   15296: 
                   15297: Returns:
                   15298:  'ok' -> succeeded in storing all keys of $storehash
                   15299:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15300:                         least <key> already existed in the db (other
                   15301:                         requested keys may also already exist)
1.967     bisitz   15302:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15303:  'con_lost' -> unable to contact request server
                   15304:  'refused' -> action was not allowed by remote machine
                   15305: 
                   15306: 
                   15307: =item *
                   15308: 
1.243     albertel 15309: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15310: reference filled in from namesp (encrypts the return communication)
                   15311: ($udom and $uname are optional)
1.191     harris41 15312: 
                   15313: =item *
                   15314: 
1.243     albertel 15315: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15316: critical subroutine
                   15317: 
1.806     raeburn  15318: =item *
                   15319: 
1.860     raeburn  15320: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15321: array reference filled in from namespace found in domain level on either
                   15322: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15323: 
                   15324: =item *
                   15325: 
1.860     raeburn  15326: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15327: domain level either on specified domain server ($uhome) or primary domain 
                   15328: server ($udom and $uhome are optional)
1.806     raeburn  15329: 
1.943     raeburn  15330: =item * 
                   15331: 
1.1172.2.35  raeburn  15332: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   15333: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15334: the target domain.
                   15335: 
                   15336: May also include additional key => value pairs for the following groups:
                   15337: 
                   15338: =over
                   15339: 
                   15340: =item
                   15341: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15342: 
                   15343: =over
                   15344: 
                   15345: =item defaultquota, authorquota
                   15346: 
                   15347: =back
                   15348: 
                   15349: =item
                   15350: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15351: portfolio for users).
                   15352: 
                   15353: =over
                   15354: 
                   15355: =item
                   15356: aboutme, blog, webdav, portfolio
                   15357: 
                   15358: =back
                   15359: 
                   15360: =item
                   15361: requestcourses: ability to request courses, and how requests are processed.
                   15362: 
                   15363: =over
                   15364: 
                   15365: =item
1.1172.2.37  raeburn  15366: official, unofficial, community, textbook
1.1172.2.35  raeburn  15367: 
                   15368: =back
                   15369: 
                   15370: =item
                   15371: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15372: 
                   15373: =over
                   15374: 
                   15375: =item
1.1172.2.44  raeburn  15376: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  15377: 
                   15378: =back
                   15379: 
                   15380: =item
                   15381: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15382: for course's uploaded content.
                   15383: 
                   15384: =over
                   15385: 
                   15386: =item
1.1172.2.68  raeburn  15387: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   15388: communityquota, textbookquota
1.1172.2.35  raeburn  15389: 
                   15390: =back
                   15391: 
                   15392: =item
                   15393: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15394: on your servers.
                   15395: 
                   15396: =over
                   15397: 
                   15398: =item
                   15399: remotesessions, hostedsessions
                   15400: 
                   15401: =back
                   15402: 
                   15403: =back
                   15404: 
                   15405: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15406: utility to create a configuration.db file on a domain's primary library server
                   15407: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15408: -- corresponding values are authentication type (internal, krb4, krb5,
                   15409: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   15410: will be available. Values are retrieved from cache (if current), unless the
                   15411: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15412: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15413: 
                   15414: Typical usage:
1.943     raeburn  15415: 
1.1172.2.35  raeburn  15416: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15417: 
1.243     albertel 15418: =back
                   15419: 
                   15420: =head2 Network Status Functions
                   15421: 
                   15422: =over 4
1.191     harris41 15423: 
                   15424: =item *
                   15425: 
1.1137    raeburn  15426: dirlist() : return directory list based on URI (first arg).
                   15427: 
                   15428: Inputs: 1 required, 5 optional.
                   15429: 
                   15430: =over
                   15431: 
                   15432: =item 
                   15433: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15434: 
                   15435: =item
                   15436: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15437: 
                   15438: =item
                   15439: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15440: 
                   15441: =item
                   15442: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15443: 
                   15444: =item
                   15445: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15446: 
                   15447: =item 
                   15448: $alternateRoot - path to prepend in place of path from $uri.
                   15449: 
                   15450: =back
                   15451: 
                   15452: Returns: Array of up to two items.
                   15453: 
                   15454: =over
                   15455: 
                   15456: a reference to an array of files/subdirectories
                   15457: 
                   15458: =over
                   15459: 
                   15460: Each element in the array of files/subdirectories is a & separated list of
                   15461: item name and the result of running stat on the item.  If dirlist was requested
                   15462: for a file instead of a directory, the item name will be ''. For a directory 
                   15463: listing, if the item is a metadata file, the element will end &N&M 
                   15464: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15465: default copyright set (1).  
                   15466: 
                   15467: =back
                   15468: 
                   15469: a scalar containing error condition (if encountered).
                   15470: 
                   15471: =over
                   15472: 
                   15473: =item 
                   15474: no_host (no homeserver identified for $username:$domain).
                   15475: 
                   15476: =item 
                   15477: no_such_host (server contacted for listing not identified as valid host).
                   15478: 
                   15479: =item 
                   15480: con_lost (connection to remote server failed).
                   15481: 
                   15482: =item 
                   15483: refused (invalid $username:$domain received on lond side).
                   15484: 
                   15485: =item 
                   15486: no_such_dir (directory at specified path on lond side does not exist). 
                   15487: 
                   15488: =item 
                   15489: empty (directory at specified path on lond side is empty).
                   15490: 
                   15491: =over
                   15492: 
                   15493: This is currently not encountered because the &ls3, &ls2, 
                   15494: &ls (_handler) routines on the lond side do not filter out
                   15495: . and .. from a directory listing. 
                   15496: 
                   15497: =back
                   15498: 
                   15499: =back
                   15500: 
                   15501: =back
1.191     harris41 15502: 
                   15503: =item *
                   15504: 
1.243     albertel 15505: spareserver() : find server with least workload from spare.tab
                   15506: 
1.986     foxr     15507: 
                   15508: =item *
                   15509: 
                   15510: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15511: if there is no corresponding loncapa host.
                   15512: 
1.243     albertel 15513: =back
                   15514: 
1.986     foxr     15515: 
1.243     albertel 15516: =head2 Apache Request
                   15517: 
                   15518: =over 4
1.191     harris41 15519: 
                   15520: =item *
                   15521: 
1.243     albertel 15522: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15523: localhost, posts hash
                   15524: 
                   15525: =back
                   15526: 
                   15527: =head2 Data to String to Data
                   15528: 
                   15529: =over 4
1.191     harris41 15530: 
                   15531: =item *
                   15532: 
1.243     albertel 15533: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15534: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15535: 
                   15536: =item *
                   15537: 
1.243     albertel 15538: hashref2str($hashref) : convert a hashref into a string complete with
                   15539: escaping and '=' and '&' separators, supports elements that are
                   15540: arrayrefs and hashrefs
1.191     harris41 15541: 
                   15542: =item *
                   15543: 
1.243     albertel 15544: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15545: with escaping and '&' separators, supports elements that are arrayrefs
                   15546: and hashrefs
1.191     harris41 15547: 
                   15548: =item *
                   15549: 
1.243     albertel 15550: str2hash($string) : convert string to hash using unescaping and
                   15551: splitting on '=' and '&', supports elements that are arrayrefs and
                   15552: hashrefs
1.191     harris41 15553: 
                   15554: =item *
                   15555: 
1.243     albertel 15556: str2array($string) : convert string to hash using unescaping and
                   15557: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15558: 
                   15559: =back
                   15560: 
                   15561: =head2 Logging Routines
                   15562: 
                   15563: 
                   15564: These routines allow one to make log messages in the lonnet.log and
                   15565: lonnet.perm logfiles.
1.191     harris41 15566: 
1.1119    foxr     15567: =over 4
                   15568: 
1.191     harris41 15569: =item *
                   15570: 
1.243     albertel 15571: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15572: 
                   15573: =item *
                   15574: 
1.243     albertel 15575: logthis() : append message to the normal lonnet.log file, it gets
                   15576: preiodically rolled over and deleted.
1.191     harris41 15577: 
                   15578: =item *
                   15579: 
1.243     albertel 15580: logperm() : append a permanent message to lonnet.perm.log, this log
                   15581: file never gets deleted by any automated portion of the system, only
                   15582: messages of critical importance should go in here.
                   15583: 
1.1119    foxr     15584: 
1.243     albertel 15585: =back
                   15586: 
                   15587: =head2 General File Helper Routines
                   15588: 
                   15589: =over 4
1.191     harris41 15590: 
                   15591: =item *
                   15592: 
1.481     raeburn  15593: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15594: (a) files in /uploaded
                   15595:   (i) If a local copy of the file exists - 
                   15596:       compares modification date of local copy with last-modified date for 
                   15597:       definitive version stored on home server for course. If local copy is 
                   15598:       stale, requests a new version from the home server and stores it. 
                   15599:       If the original has been removed from the home server, then local copy 
                   15600:       is unlinked.
                   15601:   (ii) If local copy does not exist -
                   15602:       requests the file from the home server and stores it. 
                   15603:   
                   15604:   If $caller is 'uploadrep':  
                   15605:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15606:     for request for files originally uploaded via DOCS. 
                   15607:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15608:   
                   15609:   Otherwise:
                   15610:      This indicates a call from the content generation phase of the request.
                   15611:      -  returns the entire contents of the file or -1.
                   15612:      
                   15613: (b) files in /res
                   15614:    - returns the entire contents of a file or -1; 
                   15615:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15616: 
1.712     albertel 15617: 
                   15618: =item *
                   15619: 
                   15620: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15621:                   reference
                   15622: 
                   15623: returns either a stat() list of data about the file or an empty list
                   15624: if the file doesn't exist or couldn't find out about it (connection
                   15625: problems or user unknown)
                   15626: 
1.191     harris41 15627: =item *
                   15628: 
1.243     albertel 15629: filelocation($dir,$file) : returns file system location of a file
                   15630: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15631: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15632: and a file of ../bob will become /a/bob)
1.191     harris41 15633: 
                   15634: =item *
                   15635: 
                   15636: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15637: filelocation except for hrefs
                   15638: 
                   15639: =item *
                   15640: 
1.1172.2.49  raeburn  15641: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15642: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15643: 
1.243     albertel 15644: =back
                   15645: 
1.608     albertel 15646: =head2 Usererfile file routines (/uploaded*)
                   15647: 
                   15648: =over 4
                   15649: 
                   15650: =item *
                   15651: 
                   15652: userfileupload(): main rotine for putting a file in a user or course's
                   15653:                   filespace, arguments are,
                   15654: 
1.620     albertel 15655:  formname - required - this is the name of the element in $env where the
1.608     albertel 15656:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15657:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15658:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15659:  context - if coursedoc, store the file in the course of the active role
                   15660:              of the current user; 
                   15661:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15662:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15663:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15664:          if undefined, it will be placed in "unknown"
                   15665: 
                   15666:  (This routine calls clean_filename() to remove any dangerous
                   15667:  characters from the filename, and then calls finuserfileupload() to
                   15668:  complete the transaction)
                   15669: 
                   15670:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15671:  and /adm/notfound.html if unsuccessful
                   15672: 
                   15673: =item *
                   15674: 
                   15675: clean_filename(): routine for cleaing a filename up for storage in
                   15676:                  userfile space, argument is:
                   15677: 
                   15678:  filename - proposed filename
                   15679: 
                   15680: returns: the new clean filename
                   15681: 
                   15682: =item *
                   15683: 
1.1090    raeburn  15684: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15685: userspace, probably shouldn't be called directly
                   15686: 
                   15687:   docuname: username or courseid of destination for the file
                   15688:   docudom: domain of user/course of destination for the file
                   15689:   formname: same as for userfileupload()
1.1090    raeburn  15690:   fname: filename (including subdirectories) for the file
                   15691:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  15692:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  15693:   allfiles: reference to hash used to store objects found by parser
                   15694:   codebase: reference to hash used for codebases of java objects found by parser
                   15695:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15696:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15697:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15698:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15699:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15700:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15701:   mimetype: reference to scalar to accommodate mime type determined
                   15702:             from File::MMagic if $parser = parse.
1.608     albertel 15703: 
                   15704:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15705:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15706:  was 'overwrite').
                   15707:  
1.608     albertel 15708: 
                   15709: =item *
                   15710: 
                   15711: renameuserfile(): renames an existing userfile to a new name
                   15712: 
                   15713:   Args:
                   15714:    docuname: username or courseid of destination for the file
                   15715:    docudom: domain of user/course of destination for the file
                   15716:    old: current file name (including any subdirs under userfiles)
                   15717:    new: desired file name (including any subdirs under userfiles)
                   15718: 
                   15719: =item *
                   15720: 
                   15721: mkdiruserfile(): creates a directory is a userfiles dir
                   15722: 
                   15723:   Args:
                   15724:    docuname: username or courseid of destination for the file
                   15725:    docudom: domain of user/course of destination for the file
                   15726:    dir: dir to create (including any subdirs under userfiles)
                   15727: 
                   15728: =item *
                   15729: 
                   15730: removeuserfile(): removes a file that exists in userfiles
                   15731: 
                   15732:   Args:
                   15733:    docuname: username or courseid of destination for the file
                   15734:    docudom: domain of user/course of destination for the file
                   15735:    fname: filname to delete (including any subdirs under userfiles)
                   15736: 
                   15737: =item *
                   15738: 
                   15739: removeuploadedurl(): convience function for removeuserfile()
                   15740: 
                   15741:   Args:
                   15742:    url:  a full /uploaded/... url to delete
                   15743: 
1.747     albertel 15744: =item * 
                   15745: 
                   15746: get_portfile_permissions():
                   15747:   Args:
                   15748:     domain: domain of user or course contain the portfolio files
                   15749:     user: name of user or num of course contain the portfolio files
                   15750:   Returns:
                   15751:     hashref of a dump of the proper file_permissions.db
                   15752:    
                   15753: 
                   15754: =item * 
                   15755: 
                   15756: get_access_controls():
                   15757: 
                   15758: Args:
                   15759:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15760:   group: (optional) the group you want the files associated with
                   15761:   file: (optional) the file you want access info on
                   15762: 
                   15763: Returns:
1.749     raeburn  15764:     a hash (keys are file names) of hashes containing
                   15765:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15766:         values are XML containing access control settings (see below) 
1.747     albertel 15767: 
                   15768: Internal notes:
                   15769: 
1.749     raeburn  15770:  access controls are stored in file_permissions.db as key=value pairs.
                   15771:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15772:         where scope -> public,guest,course,group,domains or users.
                   15773:               end -> UNIX time for end of access (0 -> no end date)
                   15774:               start -> UNIX time for start of access
                   15775: 
                   15776:     value -> XML description of access control
                   15777:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15778:             <start></start>
                   15779:             <end></end>
                   15780: 
                   15781:             <password></password>  for scope type = guest
                   15782: 
                   15783:             <domain></domain>     for scope type = course or group
                   15784:             <number></number>
                   15785:             <roles id="">
                   15786:              <role></role>
                   15787:              <access></access>
                   15788:              <section></section>
                   15789:              <group></group>
                   15790:             </roles>
                   15791: 
                   15792:             <dom></dom>         for scope type = domains
                   15793: 
                   15794:             <users>             for scope type = users
                   15795:              <user>
                   15796:               <uname></uname>
                   15797:               <udom></udom>
                   15798:              </user>
                   15799:             </users>
                   15800:            </scope> 
                   15801:               
                   15802:  Access data is also aggregated for each file in an additional key=value pair:
                   15803:  key -> path to file/file_name\0accesscontrol 
                   15804:  value -> reference to hash
                   15805:           hash contains key = value pairs
                   15806:           where key = uniqueID:scope_end_start
                   15807:                 value = UNIX time record was last updated
                   15808: 
                   15809:           Used to improve speed of look-ups of access controls for each file.  
                   15810:  
                   15811:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15812: 
1.1172.2.13  raeburn  15813: =item *
                   15814: 
1.749     raeburn  15815: modify_access_controls():
                   15816: 
                   15817: Modifies access controls for a portfolio file
                   15818: Args
                   15819: 1. file name
                   15820: 2. reference to hash of required changes,
                   15821: 3. domain
                   15822: 4. username
                   15823:   where domain,username are the domain of the portfolio owner 
                   15824:   (either a user or a course) 
                   15825: 
                   15826: Returns:
                   15827: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15828: 2. result of deletions ('ok' or 'error', with error message).
                   15829: 3. reference to hash of any new or updated access controls.
                   15830: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15831:    key = integer (inbound ID)
1.1172.2.13  raeburn  15832:    value = uniqueID
                   15833: 
                   15834: =item *
                   15835: 
                   15836: get_timebased_id():
                   15837: 
                   15838: Attempts to get a unique timestamp-based suffix for use with items added to a
                   15839: course via the Course Editor (e.g., folders, composite pages,
                   15840: group bulletin boards).
                   15841: 
                   15842: Args: (first three required; six others optional)
                   15843: 
                   15844: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15845:    docssequence, or name of group
                   15846: 
                   15847: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15848:    e.g., num, boardids
                   15849: 
                   15850: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   15851:    file will be named nohist_namespace.db
                   15852: 
                   15853: 4. cdom: domain of course; default is current course domain from %env
                   15854: 
                   15855: 5. cnum: course number; default is current course number from %env
                   15856: 
                   15857: 6. idtype: set to concat if an additional digit is to be appended to the
                   15858:    unix timestamp to form the suffix, if the plain timestamp is already
                   15859:    in use.  Default is to not do this, but simply increment the unix
                   15860:    timestamp by 1 until a unique key is obtained.
                   15861: 
                   15862: 7. who: holder of locking key; defaults to user:domain for user.
                   15863: 
                   15864: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   15865:    retrying); default is 3.
                   15866: 
                   15867: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   15868: 
                   15869: Returns:
                   15870: 
                   15871: 1. suffix obtained (numeric)
                   15872: 
                   15873: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15874: 
                   15875: 3. error: contains (localized) error message if an error occurred.
                   15876: 
1.747     albertel 15877: 
1.608     albertel 15878: =back
                   15879: 
1.243     albertel 15880: =head2 HTTP Helper Routines
                   15881: 
                   15882: =over 4
                   15883: 
1.191     harris41 15884: =item *
                   15885: 
                   15886: escape() : unpack non-word characters into CGI-compatible hex codes
                   15887: 
                   15888: =item *
                   15889: 
                   15890: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15891: 
1.243     albertel 15892: =back
                   15893: 
                   15894: =head1 PRIVATE SUBROUTINES
                   15895: 
                   15896: =head2 Underlying communication routines (Shouldn't call)
                   15897: 
                   15898: =over 4
                   15899: 
                   15900: =item *
                   15901: 
                   15902: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15903: 
                   15904: =item *
                   15905: 
                   15906: reply() : uses subreply to send a message to remote machine, logs all failures
                   15907: 
                   15908: =item *
                   15909: 
                   15910: critical() : passes a critical message to another server; if cannot
                   15911: get through then place message in connection buffer directory and
                   15912: returns con_delayed, if incapable of saving message, returns
                   15913: con_failed
                   15914: 
                   15915: =item *
                   15916: 
                   15917: reconlonc() : tries to reconnect lonc client processes.
                   15918: 
                   15919: =back
                   15920: 
                   15921: =head2 Resource Access Logging
                   15922: 
                   15923: =over 4
                   15924: 
                   15925: =item *
                   15926: 
                   15927: flushcourselogs() : flush (save) buffer logs and access logs
                   15928: 
                   15929: =item *
                   15930: 
                   15931: courselog($what) : save message for course in hash
                   15932: 
                   15933: =item *
                   15934: 
                   15935: courseacclog($what) : save message for course using &courselog().  Perform
                   15936: special processing for specific resource types (problems, exams, quizzes, etc).
                   15937: 
1.191     harris41 15938: =item *
                   15939: 
                   15940: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15941: as a PerlChildExitHandler
1.243     albertel 15942: 
                   15943: =back
                   15944: 
                   15945: =head2 Other
                   15946: 
                   15947: =over 4
                   15948: 
                   15949: =item *
                   15950: 
                   15951: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15952: 
                   15953: =back
                   15954: 
                   15955: =cut
1.877     foxr     15956: 

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