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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.118.  .15(raeb    4:-21): # $Id: lonnet.pm,v 1.1172.2.118.2.14 2021/01/04 13:41:25 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.118.  .14(raeb  128:-21):         my $ip = &get_requestor_ip();
1.1172.2.9  raeburn   129:         my $logentry = {
                    130:                          $id => {
                    131:                                   'exe_uname' => $env{'user.name'},
                    132:                                   'exe_udom'  => $env{'user.domain'},
                    133:                                   'exe_time'  => $now,
1.1172.2.118.  .14(raeb  134:-21):                                   'exe_ip'    => $ip,
1.1172.2.9  raeburn   135:                                   'delflag'   => $delflag,
                    136:                                   'logentry'  => $storehash,
                    137:                                   'uname'     => $uname,
                    138:                                   'udom'      => $udom,
                    139:                                 }
                    140:                        };
                    141:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       142:     }
                    143: }
1.1       albertel  144: 
1.163     harris41  145: sub logtouch {
                    146:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  147:     unless (-e "$execdir/logs/lonnet.log") {	
1.1172.2.96  raeburn   148: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  149: 	close $fh;
                    150:     }
                    151:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    152:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    153: }
                    154: 
1.1       albertel  155: sub logthis {
                    156:     my $message=shift;
                    157:     my $execdir=$perlvar{'lonDaemons'};
                    158:     my $now=time;
                    159:     my $local=localtime($now);
1.1172.2.96  raeburn   160:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      161: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    162: 	print $fh $logstring;
1.448     albertel  163: 	close($fh);
                    164:     }
1.1       albertel  165:     return 1;
                    166: }
                    167: 
                    168: sub logperm {
                    169:     my $message=shift;
                    170:     my $execdir=$perlvar{'lonDaemons'};
                    171:     my $now=time;
                    172:     my $local=localtime($now);
1.1172.2.96  raeburn   173:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  174: 	print $fh "$now:$message:$local\n";
                    175: 	close($fh);
                    176:     }
1.1       albertel  177:     return 1;
                    178: }
                    179: 
1.850     albertel  180: sub create_connection {
1.853     albertel  181:     my ($hostname,$lonid) = @_;
1.851     albertel  182:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  183: 				     Type    => SOCK_STREAM,
                    184: 				     Timeout => 10);
                    185:     return 0 if (!$client);
1.890     albertel  186:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  187:     my $result = <$client>;
                    188:     chomp($result);
                    189:     return 1 if ($result eq 'done');
                    190:     return 0;
                    191: }
                    192: 
1.983     raeburn   193: sub get_server_timezone {
                    194:     my ($cnum,$cdom) = @_;
                    195:     my $home=&homeserver($cnum,$cdom);
                    196:     if ($home ne 'no_host') {
                    197:         my $cachetime = 24*3600;
                    198:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    199:         if (defined($cached)) {
                    200:             return $timezone;
                    201:         } else {
                    202:             my $timezone = &reply('servertimezone',$home);
                    203:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    204:         }
                    205:     }
                    206: }
1.850     albertel  207: 
1.1106    raeburn   208: sub get_server_distarch {
                    209:     my ($lonhost,$ignore_cache) = @_;
                    210:     if (defined($lonhost)) {
                    211:         if (!defined(&hostname($lonhost))) {
                    212:             return;
                    213:         }
                    214:         my $cachetime = 12*3600;
                    215:         if (!$ignore_cache) {
                    216:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    217:             if (defined($cached)) {
                    218:                 return $distarch;
                    219:             }
                    220:         }
                    221:         my $rep = &reply('serverdistarch',$lonhost);
                    222:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    223:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    224:                 $rep eq '') {
                    225:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    226:         }
                    227:     }
                    228:     return;
                    229: }
                    230: 
1.993     raeburn   231: sub get_server_loncaparev {
1.1073    raeburn   232:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   233:     if (defined($lonhost)) {
                    234:         if (!defined(&hostname($lonhost))) {
                    235:             undef($lonhost);
                    236:         }
                    237:     }
                    238:     if (!defined($lonhost)) {
                    239:         if (defined(&domain($dom,'primary'))) {
                    240:             $lonhost=&domain($dom,'primary');
                    241:             if ($lonhost eq 'no_host') {
                    242:                 undef($lonhost);
                    243:             }
                    244:         }
                    245:     }
                    246:     if (defined($lonhost)) {
1.1073    raeburn   247:         my $cachetime = 12*3600;
                    248:         if (!$ignore_cache) {
                    249:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    250:             if (defined($cached)) {
                    251:                 return $loncaparev;
                    252:             }
                    253:         }
                    254:         my ($answer,$loncaparev);
                    255:         my @ids=&current_machine_ids();
                    256:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    257:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   258:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   259:                 $loncaparev = $1;
                    260:             }
                    261:         } else {
                    262:             $answer = &reply('serverloncaparev',$lonhost);
                    263:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    264:                 if ($caller eq 'loncron') {
                    265:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   266:                     $ua->timeout(4);
1.1172.2.118.  .3(raebu  267:20):                     my $hostname = &hostname($lonhost);
1.1073    raeburn   268:                     my $protocol = $protocol{$lonhost};
                    269:                     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu  270:20):                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073    raeburn   271:                     my $request=new HTTP::Request('GET',$url);
                    272:                     my $response=$ua->request($request);
                    273:                     unless ($response->is_error()) {
                    274:                         my $content = $response->content;
1.1081    raeburn   275:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   276:                             $loncaparev = $1;
                    277:                         }
                    278:                     }
                    279:                 } else {
                    280:                     $loncaparev = $loncaparevs{$lonhost};
                    281:                 }
1.1081    raeburn   282:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   283:                 $loncaparev = $1;
                    284:             }
1.993     raeburn   285:         }
1.1073    raeburn   286:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   287:     }
                    288: }
                    289: 
1.1074    raeburn   290: sub get_server_homeID {
                    291:     my ($hostname,$ignore_cache,$caller) = @_;
                    292:     unless ($ignore_cache) {
                    293:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    294:         if (defined($cached)) {
                    295:             return $serverhomeID;
                    296:         }
                    297:     }
                    298:     my $cachetime = 12*3600;
                    299:     my $serverhomeID;
                    300:     if ($caller eq 'loncron') { 
                    301:         my @machine_ids = &machine_ids($hostname);
                    302:         foreach my $id (@machine_ids) {
                    303:             my $response = &reply('serverhomeID',$id);
                    304:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    305:                 $serverhomeID = $response;
                    306:                 last;
                    307:             }
                    308:         }
                    309:         if ($serverhomeID eq '') {
                    310:             $serverhomeID = $machine_ids[-1];
                    311:         }
                    312:     } else {
                    313:         $serverhomeID = $serverhomeIDs{$hostname};
                    314:     }
                    315:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    316: }
                    317: 
1.1121    raeburn   318: sub get_remote_globals {
                    319:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   320:     my ($result,%returnhash,%whatneeded);
                    321:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   322:         foreach my $what (sort(keys(%{$whathash}))) {
                    323:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   324:             my ($response,$cached);
1.1121    raeburn   325:             unless ($ignore_cache) {
1.1125    raeburn   326:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   327:             }
                    328:             if (defined($cached)) {
1.1125    raeburn   329:                 $returnhash{$what} = $response;
1.1121    raeburn   330:             } else {
1.1125    raeburn   331:                 $whatneeded{$what} = 1;
1.1121    raeburn   332:             }
                    333:         }
1.1125    raeburn   334:         if (keys(%whatneeded) == 0) {
                    335:             $result = 'ok';
                    336:         } else {
1.1121    raeburn   337:             my $requested = &freeze_escape(\%whatneeded);
                    338:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   339:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    340:                 ($rep eq 'unknown_cmd')) {
                    341:                 $result = $rep;
                    342:             } else {
                    343:                 $result = 'ok';
1.1121    raeburn   344:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   345:                 foreach my $item (@pairs) {
                    346:                     my ($key,$value)=split(/=/,$item,2);
                    347:                     my $what = &unescape($key);
                    348:                     my $hashid = $lonhost.'-'.$what;
                    349:                     $returnhash{$what}=&thaw_unescape($value);
                    350:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   351:                 }
                    352:             }
                    353:         }
                    354:     }
1.1125    raeburn   355:     return ($result,\%returnhash);
1.1121    raeburn   356: }
                    357: 
1.1124    raeburn   358: sub remote_devalidate_cache {
1.1172.2.35  raeburn   359:     my ($lonhost,$cachekeys) = @_;
                    360:     my $items;
                    361:     return unless (ref($cachekeys) eq 'ARRAY');
                    362:     my $cachestr = join('&',@{$cachekeys});
                    363:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   364: }
                    365: 
1.1       albertel  366: # -------------------------------------------------- Non-critical communication
                    367: sub subreply {
                    368:     my ($cmd,$server)=@_;
1.838     albertel  369:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      370:     #
                    371:     #  With loncnew process trimming, there's a timing hole between lonc server
                    372:     #  process exit and the master server picking up the listen on the AF_UNIX
                    373:     #  socket.  In that time interval, a lock file will exist:
                    374: 
                    375:     my $lockfile=$peerfile.".lock";
                    376:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1172.2.79  raeburn   377: 	sleep(0.1);
1.549     foxr      378:     }
                    379:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      380:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      381:     #
1.550     foxr      382:     #   We'll give the connection a few tries before abandoning it.  If
                    383:     #   connection is not possible, we'll con_lost back to the client.
                    384:     #   
                    385:     my $client;
                    386:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    387: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    388: 				      Type    => SOCK_STREAM,
                    389: 				      Timeout => 10);
1.869     albertel  390: 	if ($client) {
1.550     foxr      391: 	    last;		# Connected!
1.850     albertel  392: 	} else {
1.853     albertel  393: 	    &create_connection(&hostname($server),$server);
1.550     foxr      394: 	}
1.1172.2.79  raeburn   395:         sleep(0.1);		# Try again later if failed connection.
1.550     foxr      396:     }
                    397:     my $answer;
                    398:     if ($client) {
1.704     albertel  399: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      400: 	$answer=<$client>;
                    401: 	if (!$answer) { $answer="con_lost"; }
                    402: 	chomp($answer);
                    403:     } else {
                    404: 	$answer = 'con_lost';	# Failed connection.
                    405:     }
1.1       albertel  406:     return $answer;
                    407: }
                    408: 
                    409: sub reply {
                    410:     my ($cmd,$server)=@_;
1.838     albertel  411:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  412:     my $answer=subreply($cmd,$server);
1.65      www       413:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1172.2.111  raeburn   414:         my $logged = $cmd;
                    415:         if ($cmd =~ /^encrypt:([^:]+):/) {
                    416:             my $subcmd = $1;
                    417:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
                    418:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    419:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
                    420:                 (undef,undef,my @rest) = split(/:/,$cmd);
                    421:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
                    422:                     splice(@rest,2,1,'Hidden');
                    423:                 } elsif ($subcmd eq 'passwd') {
                    424:                     splice(@rest,2,2,('Hidden','Hidden'));
                    425:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    426:                          ($subcmd eq 'autoexportgrades')) {
                    427:                     splice(@rest,3,1,'Hidden');
                    428:                 }
                    429:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
                    430:             }
                    431:         }
                    432:         &logthis("<font color=\"blue\">WARNING:".
                    433:                  " $logged to $server returned $answer</font>");
1.12      www       434:     }
1.1       albertel  435:     return $answer;
                    436: }
                    437: 
                    438: # ----------------------------------------------------------- Send USR1 to lonc
                    439: 
                    440: sub reconlonc {
1.891     albertel  441:     my ($lonid) = @_;
                    442:     if ($lonid) {
1.1172.2.72  raeburn   443:         my $hostname = &hostname($lonid);
1.891     albertel  444: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    445: 	if ($hostname && -e $peerfile) {
                    446: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    447: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    448: 					     Type    => SOCK_STREAM,
                    449: 					     Timeout => 10);
                    450: 	    if ($client) {
                    451: 		print $client ("reset_retries\n");
                    452: 		my $answer=<$client>;
                    453: 		#reset just this one.
                    454: 	    }
                    455: 	}
                    456: 	return;
                    457:     }
                    458: 
1.836     www       459:     &logthis("Trying to reconnect lonc");
1.1       albertel  460:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96  raeburn   461:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  462: 	my $loncpid=<$fh>;
                    463:         chomp($loncpid);
                    464:         if (kill 0 => $loncpid) {
                    465: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    466:             kill USR1 => $loncpid;
                    467:             sleep 1;
1.836     www       468:          } else {
1.12      www       469: 	    &logthis(
1.672     albertel  470:                "<font color=\"blue\">WARNING:".
1.12      www       471:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  472:         }
                    473:     } else {
1.836     www       474: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  475:     }
                    476: }
                    477: 
                    478: # ------------------------------------------------------ Critical communication
1.12      www       479: 
1.1       albertel  480: sub critical {
                    481:     my ($cmd,$server)=@_;
1.838     albertel  482:     unless (&hostname($server)) {
1.672     albertel  483:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       484:                " Critical message to unknown server ($server)</font>");
                    485:         return 'no_such_host';
                    486:     }
1.1       albertel  487:     my $answer=reply($cmd,$server);
                    488:     if ($answer eq 'con_lost') {
1.1172.2.72  raeburn   489: 	&reconlonc($server);
1.589     albertel  490: 	my $answer=reply($cmd,$server);
1.1       albertel  491:         if ($answer eq 'con_lost') {
                    492:             my $now=time;
                    493:             my $middlename=$cmd;
1.5       www       494:             $middlename=substr($middlename,0,16);
1.1       albertel  495:             $middlename=~s/\W//g;
                    496:             my $dfilename=
1.305     www       497:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    498:             $dumpcount++;
1.1       albertel  499:             {
1.448     albertel  500: 		my $dfh;
1.1172.2.96  raeburn   501: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  502: 		    print $dfh "$cmd\n"; 
                    503: 		    close($dfh);
                    504: 		}
1.1       albertel  505:             }
1.1172.2.79  raeburn   506:             sleep 1;
1.1       albertel  507:             my $wcmd='';
                    508:             {
1.448     albertel  509: 		my $dfh;
1.1172.2.96  raeburn   510: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  511: 		    $wcmd=<$dfh>; 
                    512: 		    close($dfh);
                    513: 		}
1.1       albertel  514:             }
                    515:             chomp($wcmd);
1.7       www       516:             if ($wcmd eq $cmd) {
1.672     albertel  517: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       518:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  519:                 &logperm("D:$server:$cmd");
                    520: 	        return 'con_delayed';
                    521:             } else {
1.672     albertel  522:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       523:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  524:                 &logperm("F:$server:$cmd");
                    525:                 return 'con_failed';
                    526:             }
                    527:         }
                    528:     }
                    529:     return $answer;
1.405     albertel  530: }
                    531: 
1.755     albertel  532: # ------------------------------------------- check if return value is an error
                    533: 
                    534: sub error {
                    535:     my ($result) = @_;
1.756     albertel  536:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  537: 	if ($2 == 2) { return undef; }
                    538: 	return $1;
                    539:     }
                    540:     return undef;
                    541: }
                    542: 
1.783     albertel  543: sub convert_and_load_session_env {
                    544:     my ($lonidsdir,$handle)=@_;
                    545:     my @profile;
                    546:     {
1.917     albertel  547: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    548: 	if (!$opened) {
1.915     albertel  549: 	    return 0;
                    550: 	}
1.783     albertel  551: 	flock($idf,LOCK_SH);
                    552: 	@profile=<$idf>;
                    553: 	close($idf);
                    554:     }
                    555:     my %temp_env;
                    556:     foreach my $line (@profile) {
1.786     albertel  557: 	if ($line !~ m/=/) {
                    558: 	    return 0;
                    559: 	}
1.783     albertel  560: 	chomp($line);
                    561: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    562: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    563:     }
                    564:     unlink("$lonidsdir/$handle.id");
                    565:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    566: 	    0640)) {
                    567: 	%disk_env = %temp_env;
                    568: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    569: 	untie(%disk_env);
                    570:     }
1.786     albertel  571:     return 1;
1.783     albertel  572: }
                    573: 
1.374     www       574: # ------------------------------------------- Transfer profile into environment
1.780     albertel  575: my $env_loaded;
                    576: sub transfer_profile_to_env {
1.788     albertel  577:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    578:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       579: 
1.720     albertel  580:     if (!defined($lonidsdir)) {
                    581: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    582:     }
                    583:     if (!defined($handle)) {
                    584:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    585:     }
                    586: 
1.786     albertel  587:     my $convert;
                    588:     {
1.917     albertel  589:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    590: 	if (!$opened) {
1.915     albertel  591: 	    return;
                    592: 	}
1.786     albertel  593: 	flock($idf,LOCK_SH);
                    594: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    595: 		&GDBM_READER(),0640)) {
                    596: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    597: 	    untie(%disk_env);
                    598: 	} else {
                    599: 	    $convert = 1;
                    600: 	}
                    601:     }
                    602:     if ($convert) {
                    603: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    604: 	    &logthis("Failed to load session, or convert session.");
                    605: 	}
1.374     www       606:     }
1.783     albertel  607: 
1.786     albertel  608:     my %remove;
1.783     albertel  609:     while ( my $envname = each(%env) ) {
1.433     matthew   610:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    611:             if ($time < time-300) {
1.783     albertel  612:                 $remove{$key}++;
1.433     matthew   613:             }
                    614:         }
                    615:     }
1.783     albertel  616: 
1.619     albertel  617:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  618:     $env_loaded=1;
1.783     albertel  619:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   620:         &delenv($expired_key);
1.374     www       621:     }
1.1       albertel  622: }
                    623: 
1.916     albertel  624: # ---------------------------------------------------- Check for valid session 
                    625: sub check_for_valid_session {
1.1172.2.96  raeburn   626:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  627:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1172.2.108  raeburn   628:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
1.1155    raeburn   629:     if ($name eq 'lonDAV') {
                    630:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    631:     } else {
                    632:         $lonidsdir=$r->dir_config('lonIDsDir');
1.1172.2.108  raeburn   633:         if ($name eq '') {
                    634:             $name = 'lonID';
                    635:         }
                    636:     }
                    637:     if ($name eq 'lonID') {
                    638:         $secure = 'lonSID';
                    639:         $linkname = 'lonLinkID';
                    640:         $pubname = 'lonPubID';
                    641:         if (exists($cookies{$secure})) {
                    642:             $lonid=$cookies{$secure};
                    643:         } elsif (exists($cookies{$name})) {
                    644:             $lonid=$cookies{$name};
                    645:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
                    646:             $lonid=$cookies{$linkname};
                    647:         } elsif (exists($cookies{$pubname})) {
                    648:             $lonid=$cookies{$pubname};
                    649:         }
                    650:     } else {
                    651:         $lonid=$cookies{$name};
                    652:     }
                    653:     return undef if (!$lonid);
                    654: 
                    655:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    656:     if (-l "$lonidsdir/$handle.id") {
                    657:         my $link = readlink("$lonidsdir/$handle.id");
                    658:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    659:             $handle = $1;
                    660:         }
1.1155    raeburn   661:     }
1.1172.2.96  raeburn   662:     if (!-e "$lonidsdir/$handle.id") {
                    663:         if ((ref($domref)) && ($name eq 'lonID') &&
                    664:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    665:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    666:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    667:                 $$domref = $possudom;
                    668:             }
                    669:         }
                    670:         return undef;
                    671:     }
1.916     albertel  672: 
1.917     albertel  673:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    674:     return undef if (!$opened);
1.916     albertel  675: 
                    676:     flock($idf,LOCK_SH);
                    677:     my %disk_env;
                    678:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    679: 	    &GDBM_READER(),0640)) {
                    680: 	return undef;	
                    681:     }
                    682: 
                    683:     if (!defined($disk_env{'user.name'})
                    684: 	|| !defined($disk_env{'user.domain'})) {
1.1172.2.107  raeburn   685:         untie(%disk_env);
1.916     albertel  686: 	return undef;
                    687:     }
1.1172.2.18  raeburn   688: 
1.1172.2.36  raeburn   689:     if (ref($userhashref) eq 'HASH') {
                    690:         $userhashref->{'name'} = $disk_env{'user.name'};
                    691:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.18  raeburn   692:     }
1.1172.2.107  raeburn   693:     untie(%disk_env);
1.1172.2.18  raeburn   694: 
1.916     albertel  695:     return $handle;
                    696: }
                    697: 
1.830     albertel  698: sub timed_flock {
                    699:     my ($file,$lock_type) = @_;
                    700:     my $failed=0;
                    701:     eval {
                    702: 	local $SIG{__DIE__}='DEFAULT';
                    703: 	local $SIG{ALRM}=sub {
                    704: 	    $failed=1;
                    705: 	    die("failed lock");
                    706: 	};
                    707: 	alarm(13);
                    708: 	flock($file,$lock_type);
                    709: 	alarm(0);
                    710:     };
                    711:     if ($failed) {
                    712: 	return undef;
                    713:     } else {
                    714: 	return 1;
                    715:     }
                    716: }
                    717: 
1.1172.2.107  raeburn   718: sub get_sessionfile_vars {
                    719:     my ($handle,$lonidsdir,$storearr) = @_;
                    720:     my %returnhash;
                    721:     unless (ref($storearr) eq 'ARRAY') {
                    722:         return %returnhash;
                    723:     }
                    724:     if (-l "$lonidsdir/$handle.id") {
                    725:         my $link = readlink("$lonidsdir/$handle.id");
                    726:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    727:             $handle = $1;
                    728:         }
                    729:     }
                    730:     if ((-e "$lonidsdir/$handle.id") &&
                    731:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    732:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    733:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    734:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    735:                 flock($idf,LOCK_SH);
                    736:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    737:                         &GDBM_READER(),0640)) {
                    738:                     foreach my $item (@{$storearr}) {
                    739:                         $returnhash{$item} = $disk_env{$item};
                    740:                     }
                    741:                     untie(%disk_env);
                    742:                 }
                    743:             }
                    744:         }
                    745:     }
                    746:     return %returnhash;
                    747: }
                    748: 
1.5       www       749: # ---------------------------------------------------------- Append Environment
                    750: 
                    751: sub appenv {
1.949     raeburn   752:     my ($newenv,$roles) = @_;
                    753:     if (ref($newenv) eq 'HASH') {
                    754:         foreach my $key (keys(%{$newenv})) {
                    755:             my $refused = 0;
                    756: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    757:                 $refused = 1;
                    758:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   759:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   760:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    761:                         $refused = 0;
                    762:                     }
                    763:                 }
                    764:             }
                    765:             if ($refused) {
                    766:                 &logthis("<font color=\"blue\">WARNING: ".
                    767:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    768:                          .'</font>');
                    769: 	        delete($newenv->{$key});
                    770:             } else {
                    771:                 $env{$key}=$newenv->{$key};
                    772:             }
                    773:         }
1.1172.2.96  raeburn   774:         my $lonids = $perlvar{'lonIDsDir'};
                    775:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    776:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    777:             if ($opened
                    778: 	        && &timed_flock($env_file,LOCK_EX)
                    779: 	        &&
                    780: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    781: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    782: 	        while (my ($key,$value) = each(%{$newenv})) {
                    783: 	            $disk_env{$key} = $value;
                    784: 	        }
                    785: 	        untie(%disk_env);
                    786:             }
1.35      www       787:         }
1.191     harris41  788:     }
1.56      www       789:     return 'ok';
                    790: }
                    791: # ----------------------------------------------------- Delete from Environment
                    792: 
                    793: sub delenv {
1.1104    raeburn   794:     my ($delthis,$regexp,$roles) = @_;
                    795:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    796:         my $refused = 1;
                    797:         if (ref($roles) eq 'ARRAY') {
                    798:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    799:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    800:                 $refused = 0;
                    801:             }
                    802:         }
                    803:         if ($refused) {
                    804:             &logthis("<font color=\"blue\">WARNING: ".
                    805:                      "Attempt to delete from environment ".$delthis);
                    806:             return 'error';
                    807:         }
1.56      www       808:     }
1.917     albertel  809:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    810:     if ($opened
1.915     albertel  811: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  812: 	&&
                    813: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    814: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  815: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   816: 	    if ($regexp) {
                    817:                 if ($key=~/^$delthis/) {
                    818:                     delete($env{$key});
                    819:                     delete($disk_env{$key});
                    820:                 } 
                    821:             } else {
                    822:                 if ($key=~/^\Q$delthis\E/) {
                    823: 		    delete($env{$key});
                    824: 		    delete($disk_env{$key});
                    825: 	        }
                    826:             }
1.448     albertel  827: 	}
1.783     albertel  828: 	untie(%disk_env);
1.5       www       829:     }
                    830:     return 'ok';
1.369     albertel  831: }
                    832: 
1.790     albertel  833: sub get_env_multiple {
                    834:     my ($name) = @_;
                    835:     my @values;
                    836:     if (defined($env{$name})) {
                    837:         # exists is it an array
                    838:         if (ref($env{$name})) {
                    839:             @values=@{ $env{$name} };
                    840:         } else {
                    841:             $values[0]=$env{$name};
                    842:         }
                    843:     }
                    844:     return(@values);
                    845: }
                    846: 
1.958     www       847: # ------------------------------------------------------------------- Locking
                    848: 
                    849: sub set_lock {
                    850:     my ($text)=@_;
                    851:     $locknum++;
                    852:     my $id=$$.'-'.$locknum;
                    853:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    854:              'session.lock.'.$id => $text});
                    855:     return $id;
                    856: }
                    857: 
                    858: sub get_locks {
                    859:     my $num=0;
                    860:     my %texts=();
                    861:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    862:        if ($lock=~/\w/) {
                    863:           $num++;
                    864:           $texts{$lock}=$env{'session.lock.'.$lock};
                    865:        }
                    866:    }
                    867:    return ($num,%texts);
                    868: }
                    869: 
                    870: sub remove_lock {
                    871:     my ($id)=@_;
                    872:     my $newlocks='';
                    873:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    874:        if (($lock=~/\w/) && ($lock ne $id)) {
                    875:           $newlocks.=','.$lock;
                    876:        }
                    877:     }
                    878:     &appenv({'session.locks' => $newlocks});
                    879:     &delenv('session.lock.'.$id);
                    880: }
                    881: 
                    882: sub remove_all_locks {
                    883:     my $activelocks=$env{'session.locks'};
                    884:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    885:        if ($lock=~/\w/) {
                    886:           &remove_lock($lock);
                    887:        }
                    888:     }
                    889: }
                    890: 
                    891: 
1.369     albertel  892: # ------------------------------------------ Find out current server userload
                    893: sub userload {
                    894:     my $numusers=0;
                    895:     {
                    896: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    897: 	my $filename;
                    898: 	my $curtime=time;
                    899: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  900: 	    next if ($filename eq '.' || $filename eq '..');
                    901: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1172.2.112  raeburn   902:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel  903: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  904: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  905: 	}
                    906: 	closedir(LONIDS);
                    907:     }
                    908:     my $userloadpercent=0;
                    909:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    910:     if ($maxuserload) {
1.371     albertel  911: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  912:     }
1.372     albertel  913:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  914:     return $userloadpercent;
1.283     www       915: }
                    916: 
1.1       albertel  917: # ------------------------------ Find server with least workload from spare.tab
1.11      www       918: 
1.1       albertel  919: sub spareserver {
1.1083    raeburn   920:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  921:     my $spare_server;
1.370     albertel  922:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  923:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    924:                                                      :  $userloadpercent;
1.1083    raeburn   925:     my ($uint_dom,$remotesessions);
                    926:     if (($udom ne '') && (&domain($udom) ne '')) {
                    927:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    928:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    929:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    930:         $remotesessions = $udomdefaults{'remotesessions'};
                    931:     }
1.1123    raeburn   932:     my $spareshash = &this_host_spares($udom);
                    933:     if (ref($spareshash) eq 'HASH') {
                    934:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    935:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62  raeburn   936:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    937:                                              $try_server));
1.1123    raeburn   938: 	        ($spare_server, $lowest_load) =
                    939: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    940:             }
1.1083    raeburn   941:         }
1.784     albertel  942: 
1.1123    raeburn   943:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    944: 
                    945:         if (!$found_server) {
                    946:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    947: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62  raeburn   948:                     next unless (&spare_can_host($udom,$uint_dom,
                    949:                                                  $remotesessions,$try_server));
1.1123    raeburn   950: 	            ($spare_server, $lowest_load) =
                    951: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    952:                 }
                    953: 	    }
                    954:         }
1.784     albertel  955:     }
                    956: 
                    957:     if (!$want_server_name) {
1.1001    raeburn   958:         if (defined($spare_server)) {
                    959:             my $hostname = &hostname($spare_server);
1.1083    raeburn   960:             if (defined($hostname)) {
1.1172.2.118.  .3(raebu  961:20):                 my $protocol = 'http';
                    962:20):                 if ($protocol{$spare_server} eq 'https') {
                    963:20):                     $protocol = $protocol{$spare_server};
                    964:20):                 }
1.1001    raeburn   965: 	        $spare_server = $protocol.'://'.$hostname;
                    966:             }
                    967:         }
1.784     albertel  968:     }
                    969:     return $spare_server;
                    970: }
                    971: 
                    972: sub compare_server_load {
1.1172.2.41  raeburn   973:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    974: 
                    975:     if ($required) {
                    976:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    977:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    978:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    979:         if (($major eq '' && $minor eq '') ||
                    980:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    981:             return ($spare_server,$lowest_load);
                    982:         }
                    983:     }
1.784     albertel  984: 
                    985:     my $loadans     = &reply('load',    $try_server);
                    986:     my $userloadans = &reply('userload',$try_server);
                    987: 
                    988:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   989: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  990:     }
                    991: 
                    992:     my $load;
                    993:     if ($loadans =~ /\d/) {
                    994: 	if ($userloadans =~ /\d/) {
                    995: 	    #both are numbers, pick the bigger one
                    996: 	    $load = ($loadans > $userloadans) ? $loadans 
                    997: 		                              : $userloadans;
1.411     albertel  998: 	} else {
1.784     albertel  999: 	    $load = $loadans;
1.411     albertel 1000: 	}
1.784     albertel 1001:     } else {
                   1002: 	$load = $userloadans;
                   1003:     }
                   1004: 
                   1005:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1006: 	$spare_server = $try_server;
                   1007: 	$lowest_load  = $load;
1.370     albertel 1008:     }
1.784     albertel 1009:     return ($spare_server,$lowest_load);
1.202     matthew  1010: }
1.914     albertel 1011: 
                   1012: # --------------------------- ask offload servers if user already has a session
                   1013: sub find_existing_session {
                   1014:     my ($udom,$uname) = @_;
1.1123    raeburn  1015:     my $spareshash = &this_host_spares($udom);
                   1016:     if (ref($spareshash) eq 'HASH') {
                   1017:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1018:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1019:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1020:             }
                   1021:         }
                   1022:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1023:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1024:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1025:             }
                   1026:         }
1.914     albertel 1027:     }
                   1028:     return;
                   1029: }
                   1030: 
1.1172.2.107  raeburn  1031: # check if user's browser sent load balancer cookie and server still has session
                   1032: # and is not overloaded.
                   1033: sub check_for_balancer_cookie {
                   1034:     my ($r,$update_mtime) = @_;
                   1035:     my ($otherserver,$cookie);
                   1036:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1037:     if (exists($cookies{'balanceID'})) {
                   1038:         my $balid = $cookies{'balanceID'};
                   1039:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1040:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1041:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1042:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1043:                 my ($possudom,$possuname) = ($1,$2);
                   1044:                 my $has_session = 0;
                   1045:                 if ((&domain($possudom) ne '') &&
                   1046:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1047:                     my $try_server;
                   1048:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1049:                     if ($opened) {
                   1050:                         flock($idf,LOCK_SH);
                   1051:                         while (my $line = <$idf>) {
                   1052:                             chomp($line);
                   1053:                             if (&hostname($line) ne '') {
                   1054:                                 $try_server = $line;
                   1055:                                 last;
                   1056:                             }
                   1057:                         }
                   1058:                         close($idf);
                   1059:                         if (($try_server) &&
                   1060:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1061:                             my $lowest_load = 30000;
                   1062:                             ($otherserver,$lowest_load) =
                   1063:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1064:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1065:                                 $has_session = 1;
                   1066:                             } else {
                   1067:                                 undef($otherserver);
                   1068:                             }
                   1069:                         }
                   1070:                     }
                   1071:                 }
                   1072:                 if ($has_session) {
                   1073:                     if ($update_mtime) {
                   1074:                         my $atime = my $mtime = time;
                   1075:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1076:                     }
                   1077:                 } else {
                   1078:                     unlink("$balancedir/$cookie.id");
                   1079:                 }
                   1080:             }
                   1081:         }
                   1082:     }
                   1083:     return ($otherserver,$cookie);
                   1084: }
                   1085: 
1.1172.2.118.  .11(raeb 1086:-20): sub updatebalcookie {
                   1087:-20):     my ($cookie,$balancer,$lastentry)=@_;
                   1088:-20):     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1089:-20):         my ($udom,$uname) = ($1,$2);
                   1090:-20):         my $uprimary_id = &domain($udom,'primary');
                   1091:-20):         my $uintdom = &internet_dom($uprimary_id);
                   1092:-20):         my $intdom = &internet_dom($balancer);
                   1093:-20):         my $serverhomedom = &host_domain($balancer);
                   1094:-20):         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1095:-20):             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
                   1096:-20):         }
                   1097:-20):     }
                   1098:-20):     return;
                   1099:-20): }
                   1100:-20): 
1.1172.2.107  raeburn  1101: sub delbalcookie {
                   1102:     my ($cookie,$balancer) =@_;
                   1103:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1104:         my ($udom,$uname) = ($1,$2);
                   1105:         my $uprimary_id = &domain($udom,'primary');
                   1106:         my $uintdom = &internet_dom($uprimary_id);
                   1107:         my $intdom = &internet_dom($balancer);
                   1108:         my $serverhomedom = &host_domain($balancer);
                   1109:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1172.2.118.  .11(raeb 1110:-20):             return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1172.2.107  raeburn  1111:         }
                   1112:     }
                   1113: }
                   1114: 
1.914     albertel 1115: # -------------------------------- ask if server already has a session for user
                   1116: sub has_user_session {
                   1117:     my ($lonid,$udom,$uname) = @_;
                   1118:     my $result = &reply(join(':','userhassession',
                   1119: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1120:     return 1 if ($result eq 'ok');
                   1121: 
                   1122:     return 0;
                   1123: }
                   1124: 
1.1076    raeburn  1125: # --------- determine least loaded server in a user's domain which allows login
                   1126: 
                   1127: sub choose_server {
1.1172.2.47  raeburn  1128:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1129:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1130:     my %servers = &get_servers($udom);
1.1076    raeburn  1131:     my $lowest_load = 30000;
1.1172.2.47  raeburn  1132:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1133:     if ($skiploadbal) {
                   1134:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1135:         unless (defined($cached)) {
                   1136:             my $cachetime = 60*60*24;
                   1137:             my %domconfig =
                   1138:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1139:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1140:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1141:                                            $cachetime);
                   1142:             }
                   1143:         }
                   1144:     }
1.1076    raeburn  1145:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn  1146:         my $loginvia;
1.1172.2.47  raeburn  1147:         if ($skiploadbal) {
                   1148:             if (ref($balancers) eq 'HASH') {
                   1149:                 next if (exists($balancers->{$lonhost}));
                   1150:             }
                   1151:         }
1.1115    raeburn  1152:         if ($checkloginvia) {
                   1153:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1154:             if ($loginvia) {
                   1155:                 my ($server,$path) = split(/:/,$loginvia);
                   1156:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1157:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1158:                 if ($login_host eq $server) {
                   1159:                     $portal_path = $path;
1.1151    raeburn  1160:                     $isredirect = 1;
1.1116    raeburn  1161:                 }
                   1162:             } else {
                   1163:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1164:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1165:                 if ($login_host eq $lonhost) {
                   1166:                     $portal_path = '';
1.1151    raeburn  1167:                     $isredirect = ''; 
1.1116    raeburn  1168:                 }
                   1169:             }
                   1170:         } else {
1.1076    raeburn  1171:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1172:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1173:         }
                   1174:     }
                   1175:     if ($login_host ne '') {
1.1116    raeburn  1176:         $hostname = &hostname($login_host);
1.1076    raeburn  1177:     }
1.1172.2.88  raeburn  1178:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1179: }
                   1180: 
1.1172.2.118.  .5(raebu 1181:20): sub get_course_sessions {
                   1182:20):     my ($cnum,$cdom,$lastactivity) = @_;
                   1183:20):     my %servers = &internet_dom_servers($cdom);
                   1184:20):     my %returnhash;
                   1185:20):     foreach my $server (sort(keys(%servers))) {
                   1186:20):         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
                   1187:20):         my @pairs=split(/\&/,$rep);
                   1188:20):         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
                   1189:20):             foreach my $item (@pairs) {
                   1190:20):                 my ($key,$value)=split(/=/,$item,2);
                   1191:20):                 $key = &unescape($key);
                   1192:20):                 next if ($key =~ /^error: 2 /);
                   1193:20):                 if (exists($returnhash{$key})) {
                   1194:20):                     next if ($value < $returnhash{$key});
                   1195:20):                 }
                   1196:20):                 $returnhash{$key}=$value;
                   1197:20):             }
                   1198:20):         }
                   1199:20):     }
                   1200:20):     return %returnhash;
                   1201:20): }
                   1202:20): 
1.202     matthew  1203: # --------------------------------------------- Try to change a user's password
                   1204: 
                   1205: sub changepass {
1.799     raeburn  1206:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1207:     $currentpass = &escape($currentpass);
                   1208:     $newpass     = &escape($newpass);
1.1030    raeburn  1209:     my $lonhost = $perlvar{'lonHostID'};
                   1210:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1211: 		       $server);
                   1212:     if (! $answer) {
                   1213: 	&logthis("No reply on password change request to $server ".
                   1214: 		 "by $uname in domain $udom.");
                   1215:     } elsif ($answer =~ "^ok") {
                   1216:         &logthis("$uname in $udom successfully changed their password ".
                   1217: 		 "on $server.");
                   1218:     } elsif ($answer =~ "^pwchange_failure") {
                   1219: 	&logthis("$uname in $udom was unable to change their password ".
                   1220: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1221: 		 "or pwchange");
                   1222:     } elsif ($answer =~ "^non_authorized") {
                   1223:         &logthis("$uname in $udom did not get their password correct when ".
                   1224: 		 "attempting to change it on $server.");
                   1225:     } elsif ($answer =~ "^auth_mode_error") {
                   1226:         &logthis("$uname in $udom attempted to change their password despite ".
                   1227: 		 "not being locally or internally authenticated on $server.");
                   1228:     } elsif ($answer =~ "^unknown_user") {
                   1229:         &logthis("$uname in $udom attempted to change their password ".
                   1230: 		 "on $server but were unable to because $server is not ".
                   1231: 		 "their home server.");
                   1232:     } elsif ($answer =~ "^refused") {
                   1233: 	&logthis("$server refused to change $uname in $udom password because ".
                   1234: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1235:     } elsif ($answer =~ "invalid_client") {
                   1236:         &logthis("$server refused to change $uname in $udom password because ".
                   1237:                  "it was a reset by e-mail originating from an invalid server.");
1.1172.2.113  raeburn  1238:     } elsif ($answer =~ "^prioruse") {
                   1239:        &logthis("$server refused to change $uname in $udom password because ".
                   1240:                 "the password had been used before");
1.202     matthew  1241:     }
                   1242:     return $answer;
1.1       albertel 1243: }
                   1244: 
1.169     harris41 1245: # ----------------------- Try to determine user's current authentication scheme
                   1246: 
                   1247: sub queryauthenticate {
                   1248:     my ($uname,$udom)=@_;
1.456     albertel 1249:     my $uhome=&homeserver($uname,$udom);
                   1250:     if (!$uhome) {
                   1251: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1252: 	return 'no_host';
                   1253:     }
                   1254:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1255:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1256: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1257:     }
1.456     albertel 1258:     return $answer;
1.169     harris41 1259: }
                   1260: 
1.1       albertel 1261: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1262: 
1.1       albertel 1263: sub authenticate {
1.1073    raeburn  1264:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1265:     $upass=&escape($upass);
                   1266:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1267:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1268:     my $newhome;
1.836     www      1269:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1270: # Maybe the machine was offline and only re-appeared again recently?
                   1271:         &reconlonc();
                   1272: # One more
1.952     raeburn  1273: 	$uhome=&homeserver($uname,$udom,1);
                   1274:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1275:             if (defined(&domain($udom,'primary'))) {
                   1276:                 $newhome=&domain($udom,'primary');
                   1277:             }
                   1278:             if ($newhome ne '') {
                   1279:                 $uhome = $newhome;
                   1280:             }
                   1281:         }
1.836     www      1282: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1283: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1284: 	    return 'no_host';
                   1285:         }
1.1       albertel 1286:     }
1.1073    raeburn  1287:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1288:     if ($answer eq 'authorized') {
1.952     raeburn  1289:         if ($newhome) {
                   1290:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1291:             return 'no_account_on_host'; 
                   1292:         } else {
                   1293:             &logthis("User $uname at $udom authorized by $uhome");
                   1294:             return $uhome;
                   1295:         }
1.471     albertel 1296:     }
                   1297:     if ($answer eq 'non_authorized') {
                   1298: 	&logthis("User $uname at $udom rejected by $uhome");
                   1299: 	return 'no_host'; 
1.9       www      1300:     }
1.471     albertel 1301:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1302:     return 'no_host';
                   1303: }
                   1304: 
1.1073    raeburn  1305: sub can_host_session {
1.1074    raeburn  1306:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1307:     my $canhost = 1;
1.1074    raeburn  1308:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1309:     if (ref($remotesessions) eq 'HASH') {
                   1310:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1311:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1312:                 $canhost = 0;
                   1313:             } else {
                   1314:                 $canhost = 1;
                   1315:             }
                   1316:         }
                   1317:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1318:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1319:                 $canhost = 1;
                   1320:             } else {
                   1321:                 $canhost = 0;
                   1322:             }
                   1323:         }
                   1324:         if ($canhost) {
                   1325:             if ($remotesessions->{'version'} ne '') {
                   1326:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1327:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1328:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1329:                         my $major = $1;
                   1330:                         my $minor = $2;
                   1331:                         if (($major < $reqmajor ) ||
                   1332:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1333:                             $canhost = 0;
                   1334:                         }
                   1335:                     } else {
                   1336:                         $canhost = 0;
                   1337:                     }
                   1338:                 }
                   1339:             }
                   1340:         }
                   1341:     }
                   1342:     if ($canhost) {
                   1343:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1344:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1345:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1346:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1347:                 if (($uint_dom ne '') && 
                   1348:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1349:                     $canhost = 0;
                   1350:                 } else {
                   1351:                     $canhost = 1;
                   1352:                 }
                   1353:             }
                   1354:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1355:                 if (($uint_dom ne '') && 
                   1356:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1357:                     $canhost = 1;
                   1358:                 } else {
                   1359:                     $canhost = 0;
                   1360:                 }
                   1361:             }
                   1362:         }
                   1363:     }
                   1364:     return $canhost;
                   1365: }
                   1366: 
1.1083    raeburn  1367: sub spare_can_host {
                   1368:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1369:     my $canhost=1;
1.1172.2.62  raeburn  1370:     my $try_server_hostname = &hostname($try_server);
                   1371:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1372:     my $serverhomedom = &host_domain($serverhomeID);
                   1373:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1374:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1375:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1376:             $canhost = 0;
                   1377:         }
                   1378:     }
1.1172.2.118.  .15(raeb 1379:-21):     if ($canhost) {
                   1380:-21):         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
                   1381:-21):             if ($defdomdefaults{'offloadoth'}{$try_server}) {
                   1382:-21):                 unless (&shared_institution($udom,$try_server)) {
                   1383:-21):                     $canhost = 0;
                   1384:-21):                 }
                   1385:-21):             }
                   1386:-21):         }
                   1387:-21):     }
1.1172.2.62  raeburn  1388:     if (($canhost) && ($uint_dom)) {
                   1389:         my @intdoms;
                   1390:         my $internet_names = &get_internet_names($try_server);
                   1391:         if (ref($internet_names) eq 'ARRAY') {
                   1392:             @intdoms = @{$internet_names};
                   1393:         }
                   1394:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1395:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1396:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1397:                                          $remotesessions,
                   1398:                                          $defdomdefaults{'hostedsessions'});
                   1399:         }
1.1083    raeburn  1400:     }
                   1401:     return $canhost;
                   1402: }
                   1403: 
1.1123    raeburn  1404: sub this_host_spares {
                   1405:     my ($dom) = @_;
1.1126    raeburn  1406:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1407:     my @hosts = &current_machine_ids();
                   1408:     foreach my $lonhost (@hosts) {
                   1409:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1410:             $dom_in_use = $dom;
                   1411:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1412:             last;
                   1413:         }
                   1414:     }
1.1126    raeburn  1415:     if ($dom_in_use ne '') {
                   1416:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1417:     }
                   1418:     if (ref($result) ne 'HASH') {
                   1419:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1420:         $dom_in_use = &host_domain($lonhost_in_use);
                   1421:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1422:         if (ref($result) ne 'HASH') {
                   1423:             $result = \%spareid;
                   1424:         }
                   1425:     }
                   1426:     return $result;
                   1427: }
                   1428: 
                   1429: sub spares_for_offload  {
                   1430:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1431:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1432:     if (defined($cached)) {
                   1433:         return $result;
                   1434:     } else {
1.1126    raeburn  1435:         my $cachetime = 60*60*24;
                   1436:         my %domconfig =
                   1437:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1438:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1439:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1440:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1441:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1442:                 }
                   1443:             }
                   1444:         }
                   1445:     }
1.1126    raeburn  1446:     return;
1.1123    raeburn  1447: }
                   1448: 
1.1129    raeburn  1449: sub get_lonbalancer_config {
                   1450:     my ($servers) = @_;
                   1451:     my ($currbalancer,$currtargets);
                   1452:     if (ref($servers) eq 'HASH') {
                   1453:         foreach my $server (keys(%{$servers})) {
                   1454:             my %what = (
                   1455:                          spareid => 1,
                   1456:                          perlvar => 1,
                   1457:                        );
                   1458:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1459:             if ($result eq 'ok') {
                   1460:                 if (ref($returnhash) eq 'HASH') {
                   1461:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1462:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1463:                             $currbalancer = $server;
                   1464:                             $currtargets = {};
                   1465:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1466:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1467:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1468:                                 }
                   1469:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1470:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1471:                                 }
                   1472:                             }
                   1473:                             last;
                   1474:                         }
                   1475:                     }
                   1476:                 }
                   1477:             }
                   1478:         }
                   1479:     }
                   1480:     return ($currbalancer,$currtargets);
                   1481: }
                   1482: 
                   1483: sub check_loadbalancing {
1.1172.2.88  raeburn  1484:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1485:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107  raeburn  1486:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129    raeburn  1487:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1488:     my @hosts = &current_machine_ids();
1.1129    raeburn  1489:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1490:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1491:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1492:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1493:     my $domneedscache; 
1.1129    raeburn  1494:     my $cachetime = 60*60*24;
                   1495: 
                   1496:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1497:         $dom_in_use = $udom;
                   1498:         $homeintdom = 1;
                   1499:     } else {
                   1500:         $dom_in_use = $serverhomedom;
                   1501:     }
                   1502:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1503:     unless (defined($cached)) {
                   1504:         my %domconfig =
                   1505:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1506:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1507:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1508:         } else {
                   1509:             $domneedscache = $dom_in_use;
1.1129    raeburn  1510:         }
                   1511:     }
                   1512:     if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1513:         ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1514:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1515:         if ($is_balancer) {
                   1516:             if (ref($currrules) eq 'HASH') {
                   1517:                 if ($homeintdom) {
                   1518:                     if ($uname ne '') {
                   1519:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1520:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1521:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1522:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1523:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1524:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1525:                             }
                   1526:                         }
                   1527:                         if ($rule_in_effect eq '') {
                   1528:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1529:                             if ($userenv{'inststatus'} ne '') {
                   1530:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1531:                                 my ($othertitle,$usertypes,$types) =
                   1532:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1533:                                 if (ref($types) eq 'ARRAY') {
                   1534:                                     foreach my $type (@{$types}) {
                   1535:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1536:                                             if (exists($currrules->{$type})) {
                   1537:                                                 $rule_in_effect = $currrules->{$type};
                   1538:                                             }
                   1539:                                         }
                   1540:                                     }
                   1541:                                 }
                   1542:                             } else {
                   1543:                                 if (exists($currrules->{'default'})) {
                   1544:                                     $rule_in_effect = $currrules->{'default'};
                   1545:                                 }
                   1546:                             }
                   1547:                         }
                   1548:                     } else {
                   1549:                         if (exists($currrules->{'default'})) {
                   1550:                             $rule_in_effect = $currrules->{'default'};
                   1551:                         }
                   1552:                     }
                   1553:                 } else {
                   1554:                     if ($currrules->{'_LC_external'} ne '') {
                   1555:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1556:                     }
                   1557:                 }
                   1558:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1559:                                                        $uname,$udom);
                   1560:             }
                   1561:         }
                   1562:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1563:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1564:         unless (defined($cached)) {
                   1565:             my %domconfig =
                   1566:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1567:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1568:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1569:             } else {
                   1570:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1571:             }
                   1572:         }
                   1573:         if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1574:             ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1575:                 &check_balancer_result($result,@hosts);
                   1576:             if ($is_balancer) {
1.1129    raeburn  1577:                 if (ref($currrules) eq 'HASH') {
                   1578:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1579:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1580:                     }
                   1581:                 }
                   1582:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1583:                                                        $uname,$udom);
                   1584:             }
                   1585:         } else {
                   1586:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1587:                 $is_balancer = 1;
                   1588:                 $offloadto = &this_host_spares($dom_in_use);
                   1589:             }
1.1172.2.75  raeburn  1590:             unless (defined($cached)) {
                   1591:                 $domneedscache = $serverhomedom;
                   1592:             }
1.1129    raeburn  1593:         }
                   1594:     } else {
                   1595:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1596:             $is_balancer = 1;
                   1597:             $offloadto = &this_host_spares($dom_in_use);
                   1598:         }
1.1172.2.75  raeburn  1599:         unless (defined($cached)) {
                   1600:             $domneedscache = $serverhomedom;
                   1601:         }
                   1602:     }
                   1603:     if ($domneedscache) {
                   1604:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1605:     }
1.1172.2.118.  .11(raeb 1606:-20):     if (($is_balancer) && ($caller ne 'switchserver')) {
1.1172.2.5  raeburn  1607:         my $lowest_load = 30000;
                   1608:         if (ref($offloadto) eq 'HASH') {
                   1609:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1610:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1611:                     ($otherserver,$lowest_load) =
                   1612:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1613:                 }
1.1129    raeburn  1614:             }
1.1172.2.5  raeburn  1615:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1616: 
1.1172.2.5  raeburn  1617:             if (!$found_server) {
                   1618:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1619:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1620:                         ($otherserver,$lowest_load) =
                   1621:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1622:                     }
                   1623:                 }
                   1624:             }
                   1625:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1626:             if (@{$offloadto} == 1) {
                   1627:                 $otherserver = $offloadto->[0];
                   1628:             } elsif (@{$offloadto} > 1) {
                   1629:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1630:                     ($otherserver,$lowest_load) =
                   1631:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1632:                 }
                   1633:             }
                   1634:         }
1.1172.2.88  raeburn  1635:         unless ($caller eq 'login') {
                   1636:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1637:                 $is_balancer = 0;
                   1638:                 if ($uname ne '' && $udom ne '') {
                   1639:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1640:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1641:                                  'user.loadbalcheck.time' => time});
                   1642:                     }
1.1172.2.5  raeburn  1643:                 }
1.1129    raeburn  1644:             }
                   1645:         }
1.1172.2.118.  .11(raeb 1646:-20):     }
                   1647:-20):     if (($is_balancer) && (!$homeintdom)) {
                   1648:-20):         undef($setcookie);
1.1129    raeburn  1649:     }
1.1172.2.107  raeburn  1650:     return ($is_balancer,$otherserver,$setcookie);
1.1129    raeburn  1651: }
                   1652: 
1.1172.2.12  raeburn  1653: sub check_balancer_result {
                   1654:     my ($result,@hosts) = @_;
1.1172.2.107  raeburn  1655:     my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1656:     if (ref($result) eq 'HASH') {
                   1657:         if ($result->{'lonhost'} ne '') {
                   1658:             my $currbalancer = $result->{'lonhost'};
                   1659:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1660:                 $is_balancer = 1;
                   1661:                 $currtargets = $result->{'targets'};
                   1662:                 $currrules = $result->{'rules'};
                   1663:             }
                   1664:         } else {
                   1665:             foreach my $key (keys(%{$result})) {
                   1666:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1667:                     (ref($result->{$key}) eq 'HASH')) {
                   1668:                     $is_balancer = 1;
                   1669:                     $currrules = $result->{$key}{'rules'};
                   1670:                     $currtargets = $result->{$key}{'targets'};
1.1172.2.107  raeburn  1671:                     $setcookie = $result->{$key}{'cookie'};
1.1172.2.12  raeburn  1672:                     last;
                   1673:                 }
                   1674:             }
                   1675:         }
                   1676:     }
1.1172.2.107  raeburn  1677:     return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1678: }
                   1679: 
1.1129    raeburn  1680: sub get_loadbalancer_targets {
                   1681:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1682:     my $offloadto;
1.1172.2.4  raeburn  1683:     if ($rule_in_effect eq 'none') {
                   1684:         return [$perlvar{'lonHostID'}];
                   1685:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1686:         $offloadto = $currtargets;
                   1687:     } else {
                   1688:         if ($rule_in_effect eq 'homeserver') {
                   1689:             my $homeserver = &homeserver($uname,$udom);
                   1690:             if ($homeserver ne 'no_host') {
                   1691:                 $offloadto = [$homeserver];
                   1692:             }
                   1693:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1694:             my %domconfig =
                   1695:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1696:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1697:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1698:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1699:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1700:                     }
                   1701:                 }
                   1702:             } else {
1.1172.2.7  raeburn  1703:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1704:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1705:                 if (&hostname($remotebalancer) ne '') {
                   1706:                     $offloadto = [$remotebalancer];
                   1707:                 }
                   1708:             }
                   1709:         } elsif (&hostname($rule_in_effect) ne '') {
                   1710:             $offloadto = [$rule_in_effect];
                   1711:         }
                   1712:     }
                   1713:     return $offloadto;
                   1714: }
                   1715: 
1.1127    raeburn  1716: sub internet_dom_servers {
                   1717:     my ($dom) = @_;
                   1718:     my (%uniqservers,%servers);
                   1719:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1720:     my @machinedoms = &machine_domains($primaryserver);
                   1721:     foreach my $mdom (@machinedoms) {
                   1722:         my %currservers = %servers;
                   1723:         my %server = &get_servers($mdom);
                   1724:         %servers = (%currservers,%server);
                   1725:     }
                   1726:     my %by_hostname;
                   1727:     foreach my $id (keys(%servers)) {
                   1728:         push(@{$by_hostname{$servers{$id}}},$id);
                   1729:     }
                   1730:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1731:         if (@{$by_hostname{$hostname}} > 1) {
                   1732:             my $match = 0;
                   1733:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1734:                 if (&host_domain($id) eq $dom) {
                   1735:                     $uniqservers{$id} = $hostname;
                   1736:                     $match = 1;
                   1737:                 }
                   1738:             }
                   1739:             unless ($match) {
                   1740:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1741:             }
                   1742:         } else {
                   1743:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1744:         }
                   1745:     }
                   1746:     return %uniqservers;
                   1747: }
                   1748: 
1.1       albertel 1749: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1750: 
1.599     albertel 1751: my %homecache;
1.1       albertel 1752: sub homeserver {
1.230     stredwic 1753:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1754:     my $index="$uname:$udom";
1.426     albertel 1755: 
1.599     albertel 1756:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1757: 
                   1758:     my %servers = &get_servers($udom,'library');
                   1759:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1760:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1761: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1762: 
                   1763: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1764: 	if ($answer eq 'found') {
                   1765: 	    delete($badServerCache{$tryserver}); 
                   1766: 	    return $homecache{$index}=$tryserver;
                   1767: 	} elsif ($answer eq 'no_host') {
                   1768: 	    $badServerCache{$tryserver}=1;
                   1769: 	}
1.1       albertel 1770:     }    
                   1771:     return 'no_host';
1.70      www      1772: }
                   1773: 
                   1774: # ------------------------------------- Find the usernames behind a list of IDs
                   1775: 
                   1776: sub idget {
                   1777:     my ($udom,@ids)=@_;
                   1778:     my %returnhash=();
                   1779:     
1.841     albertel 1780:     my %servers = &get_servers($udom,'library');
                   1781:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1782: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1783: 	$idlist=~tr/A-Z/a-z/; 
                   1784: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1785: 	my @answer=();
                   1786: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1787: 	    @answer=split(/\&/,$reply);
                   1788: 	}                    ;
                   1789: 	my $i;
                   1790: 	for ($i=0;$i<=$#ids;$i++) {
                   1791: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1792: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1793: 	    } 
                   1794: 	}
                   1795:     } 
1.70      www      1796:     return %returnhash;
                   1797: }
                   1798: 
                   1799: # ------------------------------------- Find the IDs behind a list of usernames
                   1800: 
                   1801: sub idrget {
                   1802:     my ($udom,@unames)=@_;
                   1803:     my %returnhash=();
1.800     albertel 1804:     foreach my $uname (@unames) {
                   1805:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1806:     }
1.70      www      1807:     return %returnhash;
                   1808: }
                   1809: 
                   1810: # ------------------------------- Store away a list of names and associated IDs
                   1811: 
                   1812: sub idput {
                   1813:     my ($udom,%ids)=@_;
                   1814:     my %servers=();
1.800     albertel 1815:     foreach my $uname (keys(%ids)) {
                   1816: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1817:         my $uhom=&homeserver($uname,$udom);
1.70      www      1818:         if ($uhom ne 'no_host') {
1.800     albertel 1819:             my $id=&escape($ids{$uname});
1.70      www      1820:             $id=~tr/A-Z/a-z/;
1.800     albertel 1821:             my $esc_unam=&escape($uname);
1.70      www      1822: 	    if ($servers{$uhom}) {
1.800     albertel 1823: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1824:             } else {
1.800     albertel 1825:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1826:             }
                   1827:         }
1.191     harris41 1828:     }
1.800     albertel 1829:     foreach my $server (keys(%servers)) {
                   1830:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1831:     }
1.344     www      1832: }
                   1833: 
1.1172.2.30  raeburn  1834: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1835: 
                   1836: sub iddel {
                   1837:     my ($udom,$idshashref,$uhome)=@_;
                   1838:     my %result=();
                   1839:     unless (ref($idshashref) eq 'HASH') {
                   1840:         return %result;
                   1841:     }
                   1842:     my %servers=();
                   1843:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1844:         my $uhom;
                   1845:         if ($uhome) {
                   1846:             $uhom = $uhome;
                   1847:         } else {
                   1848:             $uhom=&homeserver($uname,$udom);
                   1849:         }
                   1850:         if ($uhom ne 'no_host') {
                   1851:             if ($servers{$uhom}) {
                   1852:                 $servers{$uhom}.='&'.&escape($id);
                   1853:             } else {
                   1854:                 $servers{$uhom}=&escape($id);
                   1855:             }
                   1856:         }
                   1857:     }
                   1858:     foreach my $server (keys(%servers)) {
                   1859:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1860:     }
                   1861:     return %result;
                   1862: }
                   1863: 
1.1023    raeburn  1864: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1865: sub dump_dom {
1.1165    droeschl 1866:     my ($namespace, $udom, $regexp) = @_;
                   1867: 
                   1868:     $udom ||= $env{'user.domain'};
                   1869: 
                   1870:     return () unless $udom;
                   1871: 
                   1872:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1873: }
                   1874: 
1.1023    raeburn  1875: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1876: 
                   1877: sub get_dom {
1.860     raeburn  1878:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1172.2.57  raeburn  1879:     return if ($udom eq 'public');
1.806     raeburn  1880:     my $items='';
                   1881:     foreach my $item (@$storearr) {
                   1882:         $items.=&escape($item).'&';
                   1883:     }
                   1884:     $items=~s/\&$//;
1.860     raeburn  1885:     if (!$udom) {
                   1886:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1887:         return if ($udom eq 'public');
1.860     raeburn  1888:         if (defined(&domain($udom,'primary'))) {
                   1889:             $uhome=&domain($udom,'primary');
                   1890:         } else {
1.874     albertel 1891:             undef($uhome);
1.860     raeburn  1892:         }
                   1893:     } else {
                   1894:         if (!$uhome) {
                   1895:             if (defined(&domain($udom,'primary'))) {
                   1896:                 $uhome=&domain($udom,'primary');
                   1897:             }
                   1898:         }
                   1899:     }
                   1900:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1172.2.118.  .1(raebu 1901:20):         my $rep;
                   1902:20):         if ($namespace =~ /^enc/) {
                   1903:20):             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   1904:20):         } else {
                   1905:20):             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   1906:20):         }
1.866     raeburn  1907:         my %returnhash;
1.875     albertel 1908:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1909:             return %returnhash;
                   1910:         }
1.806     raeburn  1911:         my @pairs=split(/\&/,$rep);
                   1912:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1913:             return @pairs;
                   1914:         }
                   1915:         my $i=0;
                   1916:         foreach my $item (@$storearr) {
                   1917:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1918:             $i++;
                   1919:         }
                   1920:         return %returnhash;
                   1921:     } else {
1.880     banghart 1922:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1923:     }
                   1924: }
                   1925: 
                   1926: # -------------------------------------------- put items in domain db files 
                   1927: 
                   1928: sub put_dom {
1.860     raeburn  1929:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1930:     if (!$udom) {
                   1931:         $udom=$env{'user.domain'};
                   1932:         if (defined(&domain($udom,'primary'))) {
                   1933:             $uhome=&domain($udom,'primary');
                   1934:         } else {
1.874     albertel 1935:             undef($uhome);
1.860     raeburn  1936:         }
                   1937:     } else {
                   1938:         if (!$uhome) {
                   1939:             if (defined(&domain($udom,'primary'))) {
                   1940:                 $uhome=&domain($udom,'primary');
                   1941:             }
                   1942:         }
                   1943:     } 
                   1944:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1945:         my $items='';
                   1946:         foreach my $item (keys(%$storehash)) {
                   1947:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1948:         }
                   1949:         $items=~s/\&$//;
1.1172.2.118.  .1(raebu 1950:20):         if ($namespace =~ /^enc/) {
                   1951:20):             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   1952:20):         } else {
                   1953:20):             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1954:20):         }
1.806     raeburn  1955:     } else {
1.860     raeburn  1956:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1957:     }
                   1958: }
                   1959: 
1.1023    raeburn  1960: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1961: sub newput_dom {
1.1023    raeburn  1962:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1963:     my $result;
                   1964:     if (!$udom) {
                   1965:         $udom=$env{'user.domain'};
                   1966:     }
1.1023    raeburn  1967:     if ($udom) {
                   1968:         my $uname = &get_domainconfiguser($udom);
                   1969:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1970:     }
                   1971:     return $result;
                   1972: }
                   1973: 
1.1023    raeburn  1974: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1975: sub del_dom {
1.1023    raeburn  1976:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1977:     if (ref($storearr) eq 'ARRAY') {
                   1978:         if (!$udom) {
                   1979:             $udom=$env{'user.domain'};
                   1980:         }
1.1023    raeburn  1981:         if ($udom) {
                   1982:             my $uname = &get_domainconfiguser($udom); 
                   1983:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1984:         }
                   1985:     }
                   1986: }
                   1987: 
1.1023    raeburn  1988: # ----------------------------------construct domainconfig user for a domain 
                   1989: sub get_domainconfiguser {
                   1990:     my ($udom) = @_;
                   1991:     return $udom.'-domainconfig';
                   1992: }
                   1993: 
1.837     raeburn  1994: sub retrieve_inst_usertypes {
                   1995:     my ($udom) = @_;
                   1996:     my (%returnhash,@order);
1.989     raeburn  1997:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1998:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1999:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  2000:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2001:     } else {
                   2002:         if (defined(&domain($udom,'primary'))) {
                   2003:             my $uhome=&domain($udom,'primary');
                   2004:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2005:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  2006:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2007:                 return (\%returnhash,\@order);
                   2008:             }
                   2009:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2010:             my @pairs=split(/\&/,$hashitems);
                   2011:             foreach my $item (@pairs) {
                   2012:                 my ($key,$value)=split(/=/,$item,2);
                   2013:                 $key = &unescape($key);
                   2014:                 next if ($key =~ /^error: 2 /);
                   2015:                 $returnhash{$key}=&thaw_unescape($value);
                   2016:             }
                   2017:             my @esc_order = split(/\&/,$orderitems);
                   2018:             foreach my $item (@esc_order) {
                   2019:                 push(@order,&unescape($item));
                   2020:             }
                   2021:         } else {
1.1172.2.44  raeburn  2022:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2023:         }
1.1172.2.44  raeburn  2024:         return (\%returnhash,\@order);
1.837     raeburn  2025:     }
                   2026: }
                   2027: 
1.868     raeburn  2028: sub is_domainimage {
                   2029:     my ($url) = @_;
1.1172.2.74  raeburn  2030:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2031:         if (&domain($1) ne '') {
                   2032:             return '1';
                   2033:         }
                   2034:     }
                   2035:     return;
                   2036: }
                   2037: 
1.899     raeburn  2038: sub inst_directory_query {
                   2039:     my ($srch) = @_;
                   2040:     my $udom = $srch->{'srchdomain'};
                   2041:     my %results;
                   2042:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2043:     my $outcome;
1.899     raeburn  2044:     if ($homeserver ne '') {
1.1172.2.116  raeburn  2045:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2046:             if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2047:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116  raeburn  2048:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
                   2049:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2050:                     (($major == 2) && ($minor < 11)) ||
                   2051:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
                   2052:                     return;
                   2053:                 }
                   2054:             }
                   2055:         }
1.904     albertel 2056: 	my $queryid=&reply("querysend:instdirsearch:".
                   2057: 			   &escape($srch->{'srchby'}).':'.
                   2058: 			   &escape($srch->{'srchterm'}).':'.
                   2059: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2060: 	my $host=&hostname($homeserver);
                   2061: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  2062: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2063: 	    return;
                   2064: 	}
                   2065: 	my $response = &get_query_reply($queryid);
                   2066: 	my $maxtries = 5;
                   2067: 	my $tries = 1;
                   2068: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2069: 	    $response = &get_query_reply($queryid);
                   2070: 	    $tries ++;
                   2071: 	}
                   2072: 
                   2073:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2074:             if ($response eq 'unavailable') {
                   2075:                 $outcome = $response;
                   2076:             } else {
                   2077:                 $outcome = 'ok';
                   2078:                 my @matches = split(/\n/,$response);
                   2079:                 foreach my $match (@matches) {
                   2080:                     my ($key,$value) = split(/=/,$match);
                   2081:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2082:                 }
1.899     raeburn  2083:             }
                   2084:         }
                   2085:     }
1.909     raeburn  2086:     return ($outcome,%results);
1.899     raeburn  2087: }
                   2088: 
                   2089: sub usersearch {
                   2090:     my ($srch) = @_;
                   2091:     my $dom = $srch->{'srchdomain'};
                   2092:     my %results;
                   2093:     my %libserv = &all_library();
                   2094:     my $query = 'usersearch';
                   2095:     foreach my $tryserver (keys(%libserv)) {
                   2096:         if (&host_domain($tryserver) eq $dom) {
1.1172.2.116  raeburn  2097:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2098:                 if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2099:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.118.  .2(raebu 2100:20):                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116  raeburn  2101:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2102:                              (($major == 2) && ($minor < 11)) ||
                   2103:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
                   2104:                 }
                   2105:             }
1.899     raeburn  2106:             my $host=&hostname($tryserver);
                   2107:             my $queryid=
1.911     raeburn  2108:                 &reply("querysend:".&escape($query).':'.
                   2109:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2110:                        &escape($srch->{'srchtype'}).':'.
                   2111:                        &escape($srch->{'srchterm'}),$tryserver);
                   2112:             if ($queryid !~/^\Q$host\E\_/) {
                   2113:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2114:                 next;
1.899     raeburn  2115:             }
                   2116:             my $reply = &get_query_reply($queryid);
                   2117:             my $maxtries = 1;
                   2118:             my $tries = 1;
                   2119:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2120:                 $reply = &get_query_reply($queryid);
                   2121:                 $tries ++;
                   2122:             }
                   2123:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2124:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2125:             } else {
1.911     raeburn  2126:                 my @matches;
                   2127:                 if ($reply =~ /\n/) {
                   2128:                     @matches = split(/\n/,$reply);
                   2129:                 } else {
                   2130:                     @matches = split(/\&/,$reply);
                   2131:                 }
1.899     raeburn  2132:                 foreach my $match (@matches) {
                   2133:                     my ($uname,$udom,%userhash);
1.911     raeburn  2134:                     foreach my $entry (split(/:/,$match)) {
                   2135:                         my ($key,$value) =
                   2136:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2137:                         $userhash{$key} = $value;
                   2138:                         if ($key eq 'username') {
                   2139:                             $uname = $value;
                   2140:                         } elsif ($key eq 'domain') {
                   2141:                             $udom = $value;
1.911     raeburn  2142:                         }
1.899     raeburn  2143:                     }
                   2144:                     $results{$uname.':'.$udom} = \%userhash;
                   2145:                 }
                   2146:             }
                   2147:         }
                   2148:     }
                   2149:     return %results;
                   2150: }
                   2151: 
1.912     raeburn  2152: sub get_instuser {
                   2153:     my ($udom,$uname,$id) = @_;
                   2154:     my $homeserver = &domain($udom,'primary');
                   2155:     my ($outcome,%results);
                   2156:     if ($homeserver ne '') {
                   2157:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2158:                            &escape($id).':'.&escape($udom),$homeserver);
                   2159:         my $host=&hostname($homeserver);
                   2160:         if ($queryid !~/^\Q$host\E\_/) {
                   2161:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2162:             return;
                   2163:         }
                   2164:         my $response = &get_query_reply($queryid);
                   2165:         my $maxtries = 5;
                   2166:         my $tries = 1;
                   2167:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2168:             $response = &get_query_reply($queryid);
                   2169:             $tries ++;
                   2170:         }
                   2171:         if (!&error($response) && $response ne 'refused') {
                   2172:             if ($response eq 'unavailable') {
                   2173:                 $outcome = $response;
                   2174:             } else {
                   2175:                 $outcome = 'ok';
                   2176:                 my @matches = split(/\n/,$response);
                   2177:                 foreach my $match (@matches) {
                   2178:                     my ($key,$value) = split(/=/,$match);
                   2179:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2180:                 }
                   2181:             }
                   2182:         }
                   2183:     }
                   2184:     my %userinfo;
                   2185:     if (ref($results{$uname}) eq 'HASH') {
                   2186:         %userinfo = %{$results{$uname}};
                   2187:     } 
                   2188:     return ($outcome,%userinfo);
                   2189: }
                   2190: 
1.1172.2.69  raeburn  2191: sub get_multiple_instusers {
                   2192:     my ($udom,$users,$caller) = @_;
                   2193:     my ($outcome,$results);
                   2194:     if (ref($users) eq 'HASH') {
                   2195:         my $count = keys(%{$users});
                   2196:         my $requested = &freeze_escape($users);
                   2197:         my $homeserver = &domain($udom,'primary');
                   2198:         if ($homeserver ne '') {
                   2199:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2200:             my $host=&hostname($homeserver);
                   2201:             if ($queryid !~/^\Q$host\E\_/) {
                   2202:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2203:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2204:                 return ($outcome,$results);
                   2205:             }
                   2206:             my $response = &get_query_reply($queryid);
                   2207:             my $maxtries = 5;
                   2208:             if ($count > 100) {
                   2209:                 $maxtries = 1+int($count/20);
                   2210:             }
                   2211:             my $tries = 1;
                   2212:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2213:                 $response = &get_query_reply($queryid);
                   2214:                 $tries ++;
                   2215:             }
                   2216:             if ($response eq '') {
                   2217:                 $results = {};
                   2218:                 foreach my $key (keys(%{$users})) {
                   2219:                     my ($uname,$id);
                   2220:                     if ($caller eq 'id') {
                   2221:                         $id = $key;
                   2222:                     } else {
                   2223:                         $uname = $key;
                   2224:                     }
                   2225:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2226:                     $outcome = $resp;
                   2227:                     if ($resp eq 'ok') {
                   2228:                         %{$results} = (%{$results}, %info);
                   2229:                     } else {
                   2230:                         last;
                   2231:                     }
                   2232:                 }
                   2233:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2234:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2235:                     $outcome = $response;
                   2236:                 } else {
                   2237:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2238:                     if ($outcome eq 'ok') {
                   2239:                         $results = &thaw_unescape($userdata);
                   2240:                     }
                   2241:                 }
                   2242:             }
                   2243:         }
                   2244:     }
                   2245:     return ($outcome,$results);
                   2246: }
                   2247: 
1.912     raeburn  2248: sub inst_rulecheck {
1.923     raeburn  2249:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2250:     my %returnhash;
                   2251:     if ($udom ne '') {
                   2252:         if (ref($rules) eq 'ARRAY') {
                   2253:             @{$rules} = map {&escape($_);} (@{$rules});
                   2254:             my $rulestr = join(':',@{$rules});
                   2255:             my $homeserver=&domain($udom,'primary');
                   2256:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2257:                 my $response;
                   2258:                 if ($item eq 'username') {                
                   2259:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2260:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2261:                                               $homeserver));
1.923     raeburn  2262:                 } elsif ($item eq 'id') {
                   2263:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2264:                                               ':'.&escape($id).':'.$rulestr,
                   2265:                                               $homeserver));
1.945     raeburn  2266:                 } elsif ($item eq 'selfcreate') {
                   2267:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2268:                                                &escape($udom).':'.&escape($uname).
                   2269:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2270:                 }
1.912     raeburn  2271:                 if ($response ne 'refused') {
                   2272:                     my @pairs=split(/\&/,$response);
                   2273:                     foreach my $item (@pairs) {
                   2274:                         my ($key,$value)=split(/=/,$item,2);
                   2275:                         $key = &unescape($key);
                   2276:                         next if ($key =~ /^error: 2 /);
                   2277:                         $returnhash{$key}=&thaw_unescape($value);
                   2278:                     }
                   2279:                 }
                   2280:             }
                   2281:         }
                   2282:     }
                   2283:     return %returnhash;
                   2284: }
                   2285: 
                   2286: sub inst_userrules {
1.923     raeburn  2287:     my ($udom,$check) = @_;
1.912     raeburn  2288:     my (%ruleshash,@ruleorder);
                   2289:     if ($udom ne '') {
                   2290:         my $homeserver=&domain($udom,'primary');
                   2291:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2292:             my $response;
                   2293:             if ($check eq 'id') {
                   2294:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2295:                                  $homeserver);
1.943     raeburn  2296:             } elsif ($check eq 'email') {
                   2297:                 $response=&reply('instemailrules:'.&escape($udom),
                   2298:                                  $homeserver);
1.923     raeburn  2299:             } else {
                   2300:                 $response=&reply('instuserrules:'.&escape($udom),
                   2301:                                  $homeserver);
                   2302:             }
1.912     raeburn  2303:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2304:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2305:                 ($response ne 'no_such_host')) {
                   2306:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2307:                 my @pairs=split(/\&/,$hashitems);
                   2308:                 foreach my $item (@pairs) {
                   2309:                     my ($key,$value)=split(/=/,$item,2);
                   2310:                     $key = &unescape($key);
                   2311:                     next if ($key =~ /^error: 2 /);
                   2312:                     $ruleshash{$key}=&thaw_unescape($value);
                   2313:                 }
                   2314:                 my @esc_order = split(/\&/,$orderitems);
                   2315:                 foreach my $item (@esc_order) {
                   2316:                     push(@ruleorder,&unescape($item));
                   2317:                 }
                   2318:             }
                   2319:         }
                   2320:     }
                   2321:     return (\%ruleshash,\@ruleorder);
                   2322: }
                   2323: 
1.976     raeburn  2324: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2325: 
                   2326: sub get_domain_defaults {
1.1172.2.35  raeburn  2327:     my ($domain,$ignore_cache) = @_;
                   2328:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2329:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2330:     unless ($ignore_cache) {
                   2331:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2332:         if (defined($cached)) {
                   2333:             if (ref($result) eq 'HASH') {
                   2334:                 return %{$result};
                   2335:             }
1.943     raeburn  2336:         }
                   2337:     }
                   2338:     my %domdefaults;
                   2339:     my %domconfig =
1.989     raeburn  2340:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2341:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2342:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2343:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2344:                                   'coursecategories','autoenroll',
                   2345:                                   'helpsettings'],$domain);
1.1172.2.41  raeburn  2346:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2347:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2348:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2349:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2350:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2351:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2352:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2353:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2354:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2355:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2356:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2357:     } else {
                   2358:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2359:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2360:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2361:     }
1.976     raeburn  2362:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2363:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2364:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2365:         } else {
                   2366:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2367:         }
1.1172.2.6  raeburn  2368:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2369:         foreach my $item (@usertools) {
                   2370:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2371:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2372:             }
                   2373:         }
1.1172.2.29  raeburn  2374:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2375:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2376:         }
1.976     raeburn  2377:     }
1.985     raeburn  2378:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2379:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2380:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2381:         }
                   2382:     }
1.1172.2.9  raeburn  2383:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2384:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2385:     }
1.989     raeburn  2386:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2387:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2388:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2389:         }
                   2390:     }
1.1047    raeburn  2391:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2392:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2393:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2394:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2395:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2396:         }
1.1172.2.41  raeburn  2397:         foreach my $type (@coursetypes) {
                   2398:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2399:                 unless ($type eq 'community') {
                   2400:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2401:                 }
                   2402:             }
                   2403:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2404:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2405:             }
1.1172.2.60  raeburn  2406:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2407:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2408:                     $domdefaults{$type.'postsubtimeout'} =
                   2409:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2410:                 }
                   2411:             }
1.1172.2.30  raeburn  2412:         }
1.1172.2.67  raeburn  2413:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2414:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2415:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2416:                 if (@clonecodes) {
                   2417:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2418:                 }
                   2419:             }
                   2420:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2421:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2422:         }
1.1172.2.103  raeburn  2423:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2424:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2425:         }
1.1047    raeburn  2426:     }
1.1073    raeburn  2427:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2428:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2429:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2430:         }
                   2431:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2432:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2433:         }
1.1172.2.62  raeburn  2434:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2435:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2436:         }
1.1172.2.118.  .15(raeb 2437:-21):         if (ref($domconfig{'usersessions'}{offloadoth'} eq 'HASH') {
                   2438:-21):             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
                   2439:-21):         }
1.1073    raeburn  2440:     }
1.1172.2.41  raeburn  2441:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2442:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2443:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2444:                             'approval','limit');
                   2445:             foreach my $type (@coursetypes) {
                   2446:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2447:                     my @mgrdc = ();
                   2448:                     foreach my $item (@settings) {
                   2449:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2450:                             push(@mgrdc,$item);
                   2451:                         }
                   2452:                     }
                   2453:                     if (@mgrdc) {
                   2454:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2455:                     }
                   2456:                 }
                   2457:             }
                   2458:         }
                   2459:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2460:             foreach my $type (@coursetypes) {
                   2461:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2462:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2463:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2464:                     }
                   2465:                 }
                   2466:             }
                   2467:         }
                   2468:     }
1.1172.2.46  raeburn  2469:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2470:         $domdefaults{'catauth'} = 'std';
                   2471:         $domdefaults{'catunauth'} = 'std';
                   2472:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2473:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2474:         }
                   2475:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2476:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2477:         }
                   2478:     }
1.1172.2.76  raeburn  2479:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2480:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2481:     }
1.1172.2.89  raeburn  2482:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2483:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2484:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2485:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2486:         }
                   2487:     }
1.1172.2.23  raeburn  2488:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2489:     return %domdefaults;
                   2490: }
                   2491: 
1.1172.2.106  raeburn  2492: sub get_dom_cats {
                   2493:     my ($dom) = @_;
                   2494:     return unless (&domain($dom));
                   2495:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2496:     unless (defined($cached)) {
                   2497:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2498:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2499:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2500:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2501:             } else {
                   2502:                 $cats = {};
                   2503:             }
                   2504:         } else {
                   2505:             $cats = {};
                   2506:         }
                   2507:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2508:     }
                   2509:     return $cats;
                   2510: }
                   2511: 
                   2512: sub get_dom_instcats {
                   2513:     my ($dom) = @_;
                   2514:     return unless (&domain($dom));
                   2515:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2516:     unless (defined($cached)) {
                   2517:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2518:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2519:         if ($totcodes > 0) {
                   2520:             my $caller = 'global';
                   2521:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2522:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2523:                 $instcats = {
                   2524:                                 codes => \%codes,
                   2525:                                 codetitles => \@codetitles,
                   2526:                                 cat_titles => \%cat_titles,
                   2527:                                 cat_order => \%cat_order,
                   2528:                             };
                   2529:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2530:             }
                   2531:         }
                   2532:     }
                   2533:     return $instcats;
                   2534: }
                   2535: 
                   2536: sub retrieve_instcodes {
                   2537:     my ($coursecodes,$dom) = @_;
                   2538:     my $totcodes;
                   2539:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2540:     foreach my $course (keys(%courses)) {
                   2541:         if (ref($courses{$course}) eq 'HASH') {
                   2542:             if ($courses{$course}{'inst_code'} ne '') {
                   2543:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2544:                 $totcodes ++;
                   2545:             }
                   2546:         }
                   2547:     }
                   2548:     return $totcodes;
                   2549: }
                   2550: 
1.1172.2.113  raeburn  2551: # --------------------------------------------- Get domain config for passwords
                   2552: 
                   2553: sub get_passwdconf {
                   2554:     my ($dom) = @_;
                   2555:     my (%passwdconf,$gotconf,$lookup);
                   2556:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2557:     if (defined($cached)) {
                   2558:         if (ref($result) eq 'HASH') {
                   2559:             %passwdconf = %{$result};
                   2560:             $gotconf = 1;
                   2561:         }
                   2562:     }
                   2563:     unless ($gotconf) {
                   2564:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2565:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2566:             %passwdconf = %{$domconfig{'passwords'}};
                   2567:         }
                   2568:         my $cachetime = 24*60*60;
                   2569:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2570:     }
                   2571:     return %passwdconf;
                   2572: }
                   2573: 
1.1172.2.118.  .1(raebu 2574:20): sub course_portal_url {
                   2575:20):     my ($cnum,$cdom) = @_;
                   2576:20):     my $chome = &homeserver($cnum,$cdom);
                   2577:20):     my $hostname = &hostname($chome);
                   2578:20):     my $protocol = $protocol{$chome};
                   2579:20):     $protocol = 'http' if ($protocol ne 'https');
                   2580:20):     my %domdefaults = &get_domain_defaults($cdom);
                   2581:20):     my $firsturl;
                   2582:20):     if ($domdefaults{'portal_def'}) {
                   2583:20):         $firsturl = $domdefaults{'portal_def'};
                   2584:20):     } else {
                   2585:20):         $firsturl = $protocol.'://'.$hostname;
                   2586:20):     }
                   2587:20):     return $firsturl;
                   2588:20): }
                   2589:20): 
1.344     www      2590: # --------------------------------------------------- Assign a key to a student
                   2591: 
                   2592: sub assign_access_key {
1.364     www      2593: #
                   2594: # a valid key looks like uname:udom#comments
                   2595: # comments are being appended
                   2596: #
1.498     www      2597:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2598:     $kdom=
1.620     albertel 2599:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2600:     $knum=
1.620     albertel 2601:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2602:     $cdom=
1.620     albertel 2603:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2604:     $cnum=
1.620     albertel 2605:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2606:     $udom=$env{'user.name'} unless (defined($udom));
                   2607:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2608:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2609:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2610:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2611:                                                   # assigned to this person
                   2612:                                                   # - this should not happen,
1.345     www      2613:                                                   # unless something went wrong
                   2614:                                                   # the first time around
                   2615: # ready to assign
1.364     www      2616:         $logentry=$1.'; '.$logentry;
1.496     www      2617:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2618:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2619: # key now belongs to user
1.346     www      2620: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2621:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2622:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2623:                 return 'ok';
                   2624:             } else {
                   2625:                 return 
                   2626:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2627: 	    }
                   2628:         } else {
                   2629:             return 'error: Could not assign key, try again later.';
                   2630:         }
1.364     www      2631:     } elsif (!$existing{$ckey}) {
1.345     www      2632: # the key does not exist
                   2633: 	return 'error: The key does not exist';
                   2634:     } else {
                   2635: # the key is somebody else's
                   2636: 	return 'error: The key is already in use';
                   2637:     }
1.344     www      2638: }
                   2639: 
1.364     www      2640: # ------------------------------------------ put an additional comment on a key
                   2641: 
                   2642: sub comment_access_key {
                   2643: #
                   2644: # a valid key looks like uname:udom#comments
                   2645: # comments are being appended
                   2646: #
                   2647:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2648:     $cdom=
1.620     albertel 2649:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2650:     $cnum=
1.620     albertel 2651:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2652:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2653:     if ($existing{$ckey}) {
                   2654:         $existing{$ckey}.='; '.$logentry;
                   2655: # ready to assign
1.367     www      2656:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2657:                                                  $cdom,$cnum) eq 'ok') {
                   2658: 	    return 'ok';
                   2659:         } else {
                   2660: 	    return 'error: Count not store comment.';
                   2661:         }
                   2662:     } else {
                   2663: # the key does not exist
                   2664: 	return 'error: The key does not exist';
                   2665:     }
                   2666: }
                   2667: 
1.344     www      2668: # ------------------------------------------------------ Generate a set of keys
                   2669: 
                   2670: sub generate_access_keys {
1.364     www      2671:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2672:     $cdom=
1.620     albertel 2673:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2674:     $cnum=
1.620     albertel 2675:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2676:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2677:     unless (($cdom) && ($cnum)) { return 0; }
                   2678:     if ($number>10000) { return 0; }
                   2679:     sleep(2); # make sure don't get same seed twice
                   2680:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2681:     my $total=0;
                   2682:     for (my $i=1;$i<=$number;$i++) {
                   2683:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2684:                   sprintf("%lx",int(100000*rand)).'-'.
                   2685:                   sprintf("%lx",int(100000*rand));
                   2686:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2687:        $newkey=~s/0/h/g; # and also 0 and O
                   2688:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2689:        if ($existing{$newkey}) {
                   2690:            $i--;
                   2691:        } else {
1.364     www      2692: 	  if (&put('accesskeys',
                   2693:               { $newkey => '# generated '.localtime().
1.620     albertel 2694:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2695:                            '; '.$logentry },
                   2696: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2697:               $total++;
                   2698: 	  }
                   2699:        }
                   2700:     }
1.620     albertel 2701:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2702:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2703:     return $total;
                   2704: }
                   2705: 
                   2706: # ------------------------------------------------------- Validate an accesskey
                   2707: 
                   2708: sub validate_access_key {
                   2709:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2710:     $cdom=
1.620     albertel 2711:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2712:     $cnum=
1.620     albertel 2713:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2714:     $udom=$env{'user.domain'} unless (defined($udom));
                   2715:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2716:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2717:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2718: }
                   2719: 
                   2720: # ------------------------------------- Find the section of student in a course
1.652     albertel 2721: sub devalidate_getsection_cache {
                   2722:     my ($udom,$unam,$courseid)=@_;
                   2723:     my $hashid="$udom:$unam:$courseid";
                   2724:     &devalidate_cache_new('getsection',$hashid);
                   2725: }
1.298     matthew  2726: 
1.815     albertel 2727: sub courseid_to_courseurl {
                   2728:     my ($courseid) = @_;
                   2729:     #already url style courseid
                   2730:     return $courseid if ($courseid =~ m{^/});
                   2731: 
                   2732:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2733: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2734: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2735: 	return "/$cdom/$cnum";
                   2736:     }
                   2737: 
                   2738:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2739:     if (exists($courseinfo{'num'})) {
                   2740: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2741:     }
                   2742: 
                   2743:     return undef;
                   2744: }
                   2745: 
1.298     matthew  2746: sub getsection {
                   2747:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2748:     my $cachetime=1800;
1.551     albertel 2749: 
                   2750:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2751:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2752:     if (defined($cached)) { return $result; }
                   2753: 
1.298     matthew  2754:     my %Pending; 
                   2755:     my %Expired;
                   2756:     #
                   2757:     # Each role can either have not started yet (pending), be active, 
                   2758:     #    or have expired.
                   2759:     #
                   2760:     # If there is an active role, we are done.
                   2761:     #
                   2762:     # If there is more than one role which has not started yet, 
                   2763:     #     choose the one which will start sooner
                   2764:     # If there is one role which has not started yet, return it.
                   2765:     #
                   2766:     # If there is more than one expired role, choose the one which ended last.
                   2767:     # If there is a role which has expired, return it.
                   2768:     #
1.815     albertel 2769:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2770:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2771:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2772:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2773:         my $section=$1;
                   2774:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2775:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2776:         my $now=time;
1.548     albertel 2777:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2778:             $Expired{$end}=$section;
                   2779:             next;
                   2780:         }
1.548     albertel 2781:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2782:             $Pending{$start}=$section;
                   2783:             next;
                   2784:         }
1.599     albertel 2785:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2786:     }
                   2787:     #
                   2788:     # Presumedly there will be few matching roles from the above
                   2789:     # loop and the sorting time will be negligible.
                   2790:     if (scalar(keys(%Pending))) {
                   2791:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2792:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2793:     } 
                   2794:     if (scalar(keys(%Expired))) {
                   2795:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2796:         my $time = pop(@sorted);
1.599     albertel 2797:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2798:     }
1.599     albertel 2799:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2800: }
1.70      www      2801: 
1.599     albertel 2802: sub save_cache {
                   2803:     &purge_remembered();
1.722     albertel 2804:     #&Apache::loncommon::validate_page();
1.620     albertel 2805:     undef(%env);
1.780     albertel 2806:     undef($env_loaded);
1.599     albertel 2807: }
1.452     albertel 2808: 
1.599     albertel 2809: my $to_remember=-1;
                   2810: my %remembered;
                   2811: my %accessed;
                   2812: my $kicks=0;
                   2813: my $hits=0;
1.849     albertel 2814: sub make_key {
                   2815:     my ($name,$id) = @_;
1.872     albertel 2816:     if (length($id) > 65 
                   2817: 	&& length(&escape($id)) > 200) {
                   2818: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2819:     }
1.849     albertel 2820:     return &escape($name.':'.$id);
                   2821: }
                   2822: 
1.599     albertel 2823: sub devalidate_cache_new {
                   2824:     my ($name,$id,$debug) = @_;
                   2825:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2826:     my $remembered_id=$name.':'.$id;
1.849     albertel 2827:     $id=&make_key($name,$id);
1.599     albertel 2828:     $memcache->delete($id);
1.1172.2.81  raeburn  2829:     delete($remembered{$remembered_id});
                   2830:     delete($accessed{$remembered_id});
1.599     albertel 2831: }
                   2832: 
                   2833: sub is_cached_new {
                   2834:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2835:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2836:                                      # keys in %remembered hash, which persists for
                   2837:                                      # duration of request (no restriction on key length).
                   2838:     if (exists($remembered{$remembered_id})) {
                   2839: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2840: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2841: 	$hits++;
1.1172.2.81  raeburn  2842: 	return ($remembered{$remembered_id},1);
1.599     albertel 2843:     }
1.1172.2.81  raeburn  2844:     $id=&make_key($name,$id);
1.599     albertel 2845:     my $value = $memcache->get($id);
                   2846:     if (!(defined($value))) {
                   2847: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2848: 	return (undef,undef);
1.416     albertel 2849:     }
1.599     albertel 2850:     if ($value eq '__undef__') {
                   2851: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2852: 	$value=undef;
                   2853:     }
1.1172.2.81  raeburn  2854:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2855:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2856:     return ($value,1);
                   2857: }
                   2858: 
                   2859: sub do_cache_new {
                   2860:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2861:     my $remembered_id=$name.':'.$id;
1.849     albertel 2862:     $id=&make_key($name,$id);
1.599     albertel 2863:     my $setvalue=$value;
                   2864:     if (!defined($setvalue)) {
                   2865: 	$setvalue='__undef__';
                   2866:     }
1.623     albertel 2867:     if (!defined($time) ) {
                   2868: 	$time=600;
                   2869:     }
1.599     albertel 2870:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2871:     my $result = $memcache->set($id,$setvalue,$time);
                   2872:     if (! $result) {
1.872     albertel 2873: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2874: 	$memcache->disconnect_all();
1.872     albertel 2875:     }
1.600     albertel 2876:     # need to make a copy of $value
1.1172.2.81  raeburn  2877:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2878:     return $value;
                   2879: }
                   2880: 
                   2881: sub make_room {
1.1172.2.81  raeburn  2882:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2883: 
1.1172.2.81  raeburn  2884:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2885:                                     : $value;
1.599     albertel 2886:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2887:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2888:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2889:     my $to_kick;
                   2890:     my $max_time=0;
                   2891:     foreach my $other (keys(%accessed)) {
                   2892: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2893: 	    $to_kick=$other;
                   2894: 	    $max_time=&tv_interval($accessed{$other});
                   2895: 	}
                   2896:     }
                   2897:     delete($remembered{$to_kick});
                   2898:     delete($accessed{$to_kick});
                   2899:     $kicks++;
                   2900:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2901:     return;
                   2902: }
                   2903: 
1.599     albertel 2904: sub purge_remembered {
1.604     albertel 2905:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2906:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2907:     undef(%remembered);
                   2908:     undef(%accessed);
1.428     albertel 2909: }
1.70      www      2910: # ------------------------------------- Read an entry from a user's environment
                   2911: 
                   2912: sub userenvironment {
                   2913:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2914:     my $items;
                   2915:     foreach my $item (@what) {
                   2916:         $items.=&escape($item).'&';
                   2917:     }
                   2918:     $items=~s/\&$//;
1.70      www      2919:     my %returnhash=();
1.1009    raeburn  2920:     my $uhome = &homeserver($unam,$udom);
                   2921:     unless ($uhome eq 'no_host') {
                   2922:         my @answer=split(/\&/, 
                   2923:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2924:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2925:             return %returnhash;
                   2926:         }
1.1009    raeburn  2927:         my $i;
                   2928:         for ($i=0;$i<=$#what;$i++) {
                   2929: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2930:         }
1.70      www      2931:     }
                   2932:     return %returnhash;
1.1       albertel 2933: }
                   2934: 
1.617     albertel 2935: # ---------------------------------------------------------- Get a studentphoto
                   2936: sub studentphoto {
                   2937:     my ($udom,$unam,$ext) = @_;
                   2938:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2939:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2940:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2941:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2942:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2943:             } else {
                   2944:                 my ($result,$perm_reqd)=
1.707     albertel 2945: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2946:                 if ($result eq 'ok') {
                   2947:                     if (!($perm_reqd eq 'yes')) {
                   2948:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2949:                     }
                   2950:                 }
                   2951:             }
                   2952:         }
                   2953:     } else {
                   2954:         my ($result,$perm_reqd) = 
1.707     albertel 2955: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2956:         if ($result eq 'ok') {
                   2957:             if (!($perm_reqd eq 'yes')) {
                   2958:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2959:             }
                   2960:         }
                   2961:     }
                   2962:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2963: }
                   2964: 
                   2965: sub retrievestudentphoto {
                   2966:     my ($udom,$unam,$ext,$type) = @_;
                   2967:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2968:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2969:     if ($ret eq 'ok') {
                   2970:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2971:         if ($type eq 'thumbnail') {
                   2972:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2973:         }
                   2974:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2975:         return $tokenurl;
                   2976:     } else {
                   2977:         if ($type eq 'thumbnail') {
                   2978:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2979:         } else { 
                   2980:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2981:         }
1.617     albertel 2982:     }
                   2983: }
                   2984: 
1.263     www      2985: # -------------------------------------------------------------------- New chat
                   2986: 
                   2987: sub chatsend {
1.724     raeburn  2988:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2989:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2990:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2991:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2992:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2993: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2994: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2995: }
                   2996: 
                   2997: # ------------------------------------------ Find current version of a resource
                   2998: 
                   2999: sub getversion {
                   3000:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  3001:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3002:     return &currentversion(&filelocation('',$fname));
                   3003: }
                   3004: 
                   3005: sub currentversion {
                   3006:     my $fname=shift;
                   3007:     my $author=$fname;
                   3008:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3009:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3010:     my $home=&homeserver($uname,$udom);
1.292     www      3011:     if ($home eq 'no_host') { 
                   3012:         return -1; 
                   3013:     }
1.1112    www      3014:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3015:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3016: 	return -1;
                   3017:     }
1.1112    www      3018:     return $answer;
1.263     www      3019: }
                   3020: 
1.1111    www      3021: #
                   3022: # Return special version number of resource if set by override, empty otherwise
                   3023: #
                   3024: sub usedversion {
                   3025:     my $fname=shift;
                   3026:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3027:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3028:     if ($urlversion) { return $urlversion; }
                   3029:     return '';
                   3030: }
                   3031: 
1.1       albertel 3032: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3033: 
1.1       albertel 3034: sub subscribe {
                   3035:     my $fname=shift;
1.761     raeburn  3036:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3037:     $fname=~s/[\n\r]//g;
1.1       albertel 3038:     my $author=$fname;
                   3039:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3040:     my ($udom,$uname)=split(/\//,$author);
                   3041:     my $home=homeserver($uname,$udom);
1.335     albertel 3042:     if ($home eq 'no_host') {
                   3043:         return 'not_found';
1.1       albertel 3044:     }
                   3045:     my $answer=reply("sub:$fname",$home);
1.64      www      3046:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3047: 	$answer.=' by '.$home;
                   3048:     }
1.1       albertel 3049:     return $answer;
                   3050: }
                   3051:     
1.8       www      3052: # -------------------------------------------------------------- Replicate file
                   3053: 
                   3054: sub repcopy {
                   3055:     my $filename=shift;
1.23      www      3056:     $filename=~s/\/+/\//g;
1.1142    raeburn  3057:     my $londocroot = $perlvar{'lonDocRoot'};
                   3058:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3059:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3060:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3061: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3062: 	return &repcopy_userfile($filename);
                   3063:     }
1.532     albertel 3064:     $filename=~s/[\n\r]//g;
1.8       www      3065:     my $transname="$filename.in.transfer";
1.828     www      3066: # FIXME: this should flock
1.607     raeburn  3067:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3068:     my $remoteurl=subscribe($filename);
1.64      www      3069:     if ($remoteurl =~ /^con_lost by/) {
                   3070: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3071:            return 'unavailable';
1.8       www      3072:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3073: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3074: 	   return 'not_found';
1.64      www      3075:     } elsif ($remoteurl =~ /^rejected by/) {
                   3076: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3077:            return 'forbidden';
1.20      www      3078:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3079:            return 'ok';
1.8       www      3080:     } else {
1.290     www      3081:         my $author=$filename;
                   3082:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3083:         my ($udom,$uname)=split(/\//,$author);
                   3084:         my $home=homeserver($uname,$udom);
                   3085:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3086:            my @parts=split(/\//,$filename);
                   3087:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3088:            if ($path ne "$londocroot/res") {
1.8       www      3089:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3090: 	       return 'bad_request';
1.8       www      3091:            }
                   3092:            my $count;
                   3093:            for ($count=5;$count<$#parts;$count++) {
                   3094:                $path.="/$parts[$count]";
                   3095:                if ((-e $path)!=1) {
                   3096: 		   mkdir($path,0777);
                   3097:                }
                   3098:            }
                   3099:            my $ua=new LWP::UserAgent;
                   3100:            my $request=new HTTP::Request('GET',"$remoteurl");
                   3101:            my $response=$ua->request($request,$transname);
                   3102:            if ($response->is_error()) {
                   3103: 	       unlink($transname);
                   3104:                my $message=$response->status_line;
1.672     albertel 3105:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3106:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3107:                return 'unavailable';
1.8       www      3108:            } else {
1.16      www      3109: 	       if ($remoteurl!~/\.meta$/) {
                   3110:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   3111:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   3112:                   if ($mresponse->is_error()) {
                   3113: 		      unlink($filename.'.meta');
                   3114:                       &logthis(
1.672     albertel 3115:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3116:                   }
                   3117: 	       }
1.8       www      3118:                rename($transname,$filename);
1.607     raeburn  3119:                return 'ok';
1.8       www      3120:            }
1.290     www      3121:        }
1.8       www      3122:     }
1.330     www      3123: }
                   3124: 
1.1172.2.118.  .5(raebu 3125:20): # ------------------------------------------------- Unsubscribe from a resource
                   3126:20): 
                   3127:20): sub unsubscribe {
                   3128:20):     my ($fname) = @_;
                   3129:20):     my $answer;
                   3130:20):     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3131:20):     $fname=~s/[\n\r]//g;
                   3132:20):     my $author=$fname;
                   3133:20):     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3134:20):     my ($udom,$uname)=split(/\//,$author);
                   3135:20):     my $home=homeserver($uname,$udom);
                   3136:20):     if ($home eq 'no_host') {
                   3137:20):         $answer = 'no_host';
                   3138:20):     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3139:20):         $answer = 'home';
                   3140:20):     } else {
          .7(raebu 3141:20):         $answer = reply("unsub:$fname",$home);
          .5(raebu 3142:20):     }
                   3143:20):     return $answer;
                   3144:20): }
                   3145:20): 
1.330     www      3146: # ------------------------------------------------ Get server side include body
                   3147: sub ssi_body {
1.381     albertel 3148:     my ($filelink,%form)=@_;
1.606     matthew  3149:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3150:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3151:     }
1.953     www      3152:     my $output='';
                   3153:     my $response;
1.980     raeburn  3154:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3155:        ($output,$response)=&externalssi($filelink);
1.953     www      3156:     } else {
1.1004    droeschl 3157:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3158:        $filelink .= 'inhibitmenu=yes';
1.953     www      3159:        ($output,$response)=&ssi($filelink,%form);
                   3160:     }
1.778     albertel 3161:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3162:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3163:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3164:     if (wantarray) {
                   3165:         return ($output, $response);
                   3166:     } else {
                   3167:         return $output;
                   3168:     }
1.8       www      3169: }
                   3170: 
1.15      www      3171: # --------------------------------------------------------- Server Side Include
                   3172: 
1.782     albertel 3173: sub absolute_url {
                   3174:     my ($host_name) = @_;
                   3175:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3176:     if ($host_name eq '') {
                   3177: 	$host_name = $ENV{'SERVER_NAME'};
                   3178:     }
                   3179:     return $protocol.$host_name;
                   3180: }
                   3181: 
1.942     foxr     3182: #
                   3183: #   Server side include.
                   3184: # Parameters:
                   3185: #  fn     Possibly encrypted resource name/id.
                   3186: #  form   Hash that describes how the rendering should be done
                   3187: #         and other things.
1.944     foxr     3188: # Returns:
1.950     raeburn  3189: #   Scalar context: The content of the response.
                   3190: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3191: #     
1.15      www      3192: sub ssi {
                   3193: 
1.944     foxr     3194:     my ($fn,%form)=@_;
1.1172.2.100  raeburn  3195:     my ($request,$response);
1.711     albertel 3196: 
                   3197:     $form{'no_update_last_known'}=1;
1.895     albertel 3198:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3199:     if (%form) {
1.782     albertel 3200:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1172.2.58  raeburn  3201:       $request->content(join('&',map {
                   3202:             my $name = escape($_);
                   3203:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3204:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3205:             : &escape($form{$_}) );
                   3206:         } keys(%form)));
1.23      www      3207:     } else {
1.782     albertel 3208:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3209:     }
                   3210: 
1.15      www      3211:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3212: 
1.1172.2.101  raeburn  3213:     if (($env{'request.course.id'}) &&
                   3214:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3215:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3216:         ($form{'grade_symb'} ne '') &&
                   3217:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3218:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3219:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3220:             my $ua=new LWP::UserAgent;
                   3221:             $ua->local_address('127.0.0.1');
                   3222:             $response = $ua->request($request);
                   3223:         } else {
                   3224:             {
                   3225:                 require LWP::Protocol::http;
                   3226:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3227:                 my $ua=new LWP::UserAgent;
                   3228:                 $response = $ua->request($request);
                   3229:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3230:             }
                   3231:         }
                   3232:     } else {
                   3233:         my $ua=new LWP::UserAgent;
                   3234:         $response = $ua->request($request);
                   3235:     }
1.944     foxr     3236:     if (wantarray) {
1.1172.2.3  raeburn  3237: 	return ($response->content, $response);
1.944     foxr     3238:     } else {
1.1172.2.3  raeburn  3239: 	return $response->content;
1.942     foxr     3240:     }
1.324     www      3241: }
                   3242: 
                   3243: sub externalssi {
                   3244:     my ($url)=@_;
                   3245:     my $ua=new LWP::UserAgent;
                   3246:     my $request=new HTTP::Request('GET',$url);
                   3247:     my $response=$ua->request($request);
1.954     raeburn  3248:     if (wantarray) {
                   3249:         return ($response->content, $response);
                   3250:     } else {
                   3251:         return $response->content;
                   3252:     }
1.15      www      3253: }
1.254     www      3254: 
1.1172.2.98  raeburn  3255: # If the local copy of a replicated resource is outdated, trigger a
                   3256: # connection from the homeserver to flush the delayed queue. If no update
                   3257: # happens, remove local copies of outdated resource (and corresponding
                   3258: # metadata file).
                   3259: 
                   3260: sub remove_stale_resfile {
                   3261:     my ($url) = @_;
                   3262:     my $removed;
                   3263:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3264:         my $audom = $1;
                   3265:         my $auname = $2;
                   3266:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3267:             my $homeserver = &homeserver($auname,$audom);
                   3268:             unless (($homeserver eq 'no_host') ||
                   3269:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3270:                 my $fname = &filelocation('',$url);
                   3271:                 if (-e $fname) {
                   3272:                     my $hostname = &hostname($homeserver);
                   3273:                     if ($hostname) {
1.1172.2.118.  .3(raebu 3274:20):                         my $protocol = $protocol{$homeserver};
                   3275:20):                         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98  raeburn  3276:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.118.  .3(raebu 3277:20):                         my $ua=new LWP::UserAgent;
                   3278:20):                         $ua->timeout(5);
1.1172.2.98  raeburn  3279:                         my $request=new HTTP::Request('HEAD',$uri);
                   3280:                         my $response=$ua->request($request);
                   3281:                         if ($response->is_success()) {
                   3282:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3283:                             my $locmodtime = (stat($fname))[9];
                   3284:                             if ($locmodtime < $remmodtime) {
                   3285:                                 my $stale;
                   3286:                                 my $answer = &reply('pong',$homeserver);
                   3287:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3288:                                     sleep(0.2);
                   3289:                                     $locmodtime = (stat($fname))[9];
                   3290:                                     if ($locmodtime < $remmodtime) {
                   3291:                                         my $posstransfer = $fname.'.in.transfer';
                   3292:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3293:                                             $removed = 1;
                   3294:                                         } else {
                   3295:                                             $stale = 1;
                   3296:                                         }
                   3297:                                     } else {
                   3298:                                         $removed = 1;
                   3299:                                     }
                   3300:                                 } else {
                   3301:                                     $stale = 1;
                   3302:                                 }
                   3303:                                 if ($stale) {
1.1172.2.118.  .5(raebu 3304:20):                                     if (unlink($fname)) {
                   3305:20):                                         if ($uri!~/\.meta$/) {
                   3306:20):                                             if (-e $fname.'.meta') {
                   3307:20):                                                 unlink($fname.'.meta');
                   3308:20):                                             }
                   3309:20):                                         }
                   3310:20):                                         my $unsubresult = &unsubscribe($fname);
                   3311:20):                                         unless ($unsubresult eq 'ok') {
                   3312:20):                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3313:20):                                         }
                   3314:20):                                         $removed = 1;
1.1172.2.98  raeburn  3315:                                     }
                   3316:                                 }
                   3317:                             }
                   3318:                         }
                   3319:                     }
                   3320:                 }
                   3321:             }
                   3322:         }
                   3323:     }
                   3324:     return $removed;
                   3325: }
                   3326: 
1.492     albertel 3327: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3328: 
                   3329: sub allowuploaded {
                   3330:     my ($srcurl,$url)=@_;
                   3331:     $url=&clutter(&declutter($url));
                   3332:     my $dir=$url;
                   3333:     $dir=~s/\/[^\/]+$//;
                   3334:     my %httpref=();
                   3335:     my $httpurl=&hreflocation('',$url);
                   3336:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3337:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3338: }
1.477     raeburn  3339: 
1.1172.2.13  raeburn  3340: #
                   3341: # Determine if the current user should be able to edit a particular resource,
                   3342: # when viewing in course context.
                   3343: # (a) When viewing resource used to determine if "Edit" item is included in
                   3344: #     Functions.
                   3345: # (b) When displaying folder contents in course editor, used to determine if
                   3346: #     "Edit" link will be displayed alongside resource.
                   3347: #
                   3348: #  input: six args -- filename (decluttered), course number, course domain,
                   3349: #                   url, symb (if registered) and group (if this is a group
                   3350: #                   item -- e.g., bulletin board, group page etc.).
                   3351: #  output: array of five scalars --
                   3352: #          $cfile -- url for file editing if editable on current server
                   3353: #          $home -- homeserver of resource (i.e., for author if published,
                   3354: #                                           or course if uploaded.).
                   3355: #          $switchserver --  1 if server switch will be needed.
                   3356: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3357: #          $forceview -- 1 if icon/link should be to go to view mode
                   3358: #
                   3359: 
                   3360: sub can_edit_resource {
                   3361:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3362:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3363: #
                   3364: # For aboutme pages user can only edit his/her own.
                   3365: #
                   3366:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3367:         my ($sdom,$sname) = ($1,$2);
                   3368:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3369:             $home = $env{'user.home'};
                   3370:             $cfile = $resurl;
                   3371:             if ($env{'form.forceedit'}) {
                   3372:                 $forceview = 1;
                   3373:             } else {
                   3374:                 $forceedit = 1;
                   3375:             }
                   3376:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3377:         } else {
                   3378:             return;
                   3379:         }
                   3380:     }
                   3381: 
                   3382:     if ($env{'request.course.id'}) {
                   3383:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3384:         if ($group ne '') {
                   3385: # if this is a group homepage or group bulletin board, check group privs
                   3386:             my $allowed = 0;
                   3387:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3388:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3389:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3390:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3391:                     $allowed = 1;
                   3392:                 }
                   3393:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3394:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3395:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3396:                     $allowed = 1;
                   3397:                 }
                   3398:             }
                   3399:             if ($allowed) {
                   3400:                 $home=&homeserver($cnum,$cdom);
                   3401:                 if ($env{'form.forceedit'}) {
                   3402:                     $forceview = 1;
                   3403:                 } else {
                   3404:                     $forceedit = 1;
                   3405:                 }
                   3406:                 $cfile = $resurl;
                   3407:             } else {
                   3408:                 return;
                   3409:             }
                   3410:         } else {
1.1172.2.15  raeburn  3411:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3412:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3413:                     return;
                   3414:                 }
                   3415:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3416: #
                   3417: # No edit allowed where CC has switched to student role.
                   3418: #
                   3419:                 return;
                   3420:             }
                   3421:         }
                   3422:     }
                   3423: 
                   3424:     if ($file ne '') {
                   3425:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3426:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3427:                 $uploaded = 1;
                   3428:                 $incourse = 1;
                   3429:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3430:                     $cfile = &hreflocation('',$file);
                   3431:                     if ($env{'form.forceedit'}) {
                   3432:                         $forceview = 1;
                   3433:                     } else {
                   3434:                         $forceedit = 1;
                   3435:                     }
                   3436:                 }
                   3437:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3438:                 $incourse = 1;
                   3439:                 if ($env{'form.forceedit'}) {
                   3440:                     $forceview = 1;
                   3441:                 } else {
                   3442:                     $forceedit = 1;
                   3443:                 }
                   3444:                 $cfile = $resurl;
                   3445:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3446:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3447:                     $incourse = 1;
                   3448:                     if ($env{'form.forceedit'}) {
                   3449:                         $forceview = 1;
                   3450:                     } else {
                   3451:                         $forceedit = 1;
                   3452:                     }
                   3453:                     $cfile = $resurl;
                   3454:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3455:                     $incourse = 1;
                   3456:                     $cfile = $resurl.'/smpedit';
                   3457:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3458:                     $incourse = 1;
                   3459:                     if ($env{'form.forceedit'}) {
                   3460:                         $forceview = 1;
                   3461:                     } else {
                   3462:                         $forceedit = 1;
                   3463:                     }
                   3464:                     $cfile = $resurl;
1.1172.2.118.  .5(raebu 3465:20):                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3466:20):                     my ($map,$id,$res) = &decode_symb($symb);
                   3467:20):                     if ($map =~ /\.page$/) {
                   3468:20):                         $incourse = 1;
                   3469:20):                         if ($env{'form.forceedit'}) {
                   3470:20):                             $forceview = 1;
                   3471:20):                             $cfile = $map;
                   3472:20):                         } else {
                   3473:20):                             $forceedit = 1;
                   3474:20):                             $cfile =  '/adm/wrapper'.$resurl;
                   3475:20):                         }
                   3476:20):                     }
          .1(raebu 3477:20):                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3478:20):                     $incourse = 1;
                   3479:20):                     if ($env{'form.forceedit'}) {
                   3480:20):                         $forceview = 1;
                   3481:20):                     } else {
                   3482:20):                         $forceedit = 1;
                   3483:20):                     }
                   3484:20):                     $cfile = $resurl;
1.1172.2.15  raeburn  3485:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3486:                     $incourse = 1;
                   3487:                     if ($env{'form.forceedit'}) {
                   3488:                         $forceview = 1;
                   3489:                     } else {
                   3490:                         $forceedit = 1;
                   3491:                     }
                   3492:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3493:                 }
                   3494:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3495:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3496:                 if (&is_on_map($template)) {
                   3497:                     $incourse = 1;
                   3498:                     $forceview = 1;
                   3499:                     $cfile = $template;
                   3500:                 }
                   3501:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118  raeburn  3502:                 $incourse = 1;
                   3503:                 if ($env{'form.forceedit'}) {
                   3504:                     $forceview = 1;
                   3505:                 } else {
                   3506:                     $forceedit = 1;
                   3507:                 }
                   3508:                 $cfile = $resurl;
1.1172.2.118.  .1(raebu 3509:20):             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3510:20):                 $incourse = 1;
                   3511:20):                 if ($env{'form.forceedit'}) {
                   3512:20):                     $forceview = 1;
                   3513:20):                 } else {
                   3514:20):                     $forceedit = 1;
                   3515:20):                 }
                   3516:20):                 $cfile = $resurl;
1.1172.2.13  raeburn  3517:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3518:                 $incourse = 1;
                   3519:                 $forceview = 1;
                   3520:                 if ($symb) {
                   3521:                     my ($map,$id,$res)=&decode_symb($symb);
                   3522:                     $env{'request.symb'} = $symb;
                   3523:                     $cfile = &clutter($res);
                   3524:                 } else {
                   3525:                     $cfile = $env{'form.suppurl'};
1.1172.2.118.  .1(raebu 3526:20):                     my $escfile = &unescape($cfile);
                   3527:20):                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3528:20):                         $cfile = '/adm/wrapper'.$escfile;
                   3529:20):                     } else {
                   3530:20):                         $escfile =~ s{^http://}{};
                   3531:20):                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3532:20):                     }
1.1172.2.13  raeburn  3533:                 }
1.1172.2.31  raeburn  3534:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3535:                 if ($env{'form.forceedit'}) {
                   3536:                     $forceview = 1;
                   3537:                 } else {
                   3538:                     $forceedit = 1;
                   3539:                 }
                   3540:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3541:             }
                   3542:         }
                   3543:         if ($uploaded || $incourse) {
                   3544:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3545:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3546:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3547:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3548:             # Check that the user has permission to edit this resource
                   3549:             my $setpriv = 1;
                   3550:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3551:             if (defined($cfudom)) {
                   3552:                 $home=&homeserver($cfuname,$cfudom);
                   3553:                 $cfile=$file;
                   3554:             }
                   3555:         }
                   3556:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3557:             (($home ne '') && ($home ne 'no_host'))) {
                   3558:             my @ids=&current_machine_ids();
                   3559:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3560:                 $switchserver=1;
                   3561:             }
                   3562:         }
                   3563:     }
                   3564:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3565: }
                   3566: 
                   3567: sub is_course_upload {
                   3568:     my ($file,$cnum,$cdom) = @_;
                   3569:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3570:     $uploadpath =~ s{^\/}{};
                   3571:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3572:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3573:         return 1;
                   3574:     }
                   3575:     return;
                   3576: }
                   3577: 
                   3578: sub in_course {
                   3579:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3580:     if ($hideprivileged) {
                   3581:         my $skipuser;
1.1172.2.23  raeburn  3582:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3583:         my @possdoms = ($cdom);
                   3584:         if ($coursehash{'checkforpriv'}) {
                   3585:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3586:         }
                   3587:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3588:             $skipuser = 1;
                   3589:             if ($coursehash{'nothideprivileged'}) {
                   3590:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3591:                     my $user;
                   3592:                     if ($item =~ /:/) {
                   3593:                         $user = $item;
                   3594:                     } else {
                   3595:                         $user = join(':',split(/[\@]/,$item));
                   3596:                     }
                   3597:                     if ($user eq $uname.':'.$udom) {
                   3598:                         undef($skipuser);
                   3599:                         last;
                   3600:                     }
                   3601:                 }
                   3602:             }
                   3603:             if ($skipuser) {
                   3604:                 return 0;
                   3605:             }
                   3606:         }
                   3607:     }
                   3608:     $type ||= 'any';
                   3609:     if (!defined($cdom) || !defined($cnum)) {
                   3610:         my $cid  = $env{'request.course.id'};
                   3611:         $cdom = $env{'course.'.$cid.'.domain'};
                   3612:         $cnum = $env{'course.'.$cid.'.num'};
                   3613:     }
                   3614:     my $typesref;
                   3615:     if (($type eq 'any') || ($type eq 'all')) {
                   3616:         $typesref = ['active','previous','future'];
                   3617:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3618:         $typesref = [$type];
                   3619:     }
                   3620:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3621:                               $typesref,undef,[$cdom]);
                   3622:     my ($tmp) = keys(%roles);
                   3623:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3624:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3625:     if (@course_roles > 0) {
                   3626:         return 1;
                   3627:     }
                   3628:     return 0;
                   3629: }
                   3630: 
1.478     albertel 3631: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3632: # input: action, courseID, current domain, intended
1.637     raeburn  3633: #        path to file, source of file, instruction to parse file for objects,
                   3634: #        ref to hash for embedded objects,
                   3635: #        ref to hash for codebase of java objects.
1.1095    raeburn  3636: #        reference to scalar to accommodate mime type determined
                   3637: #          from File::MMagic if $parser = parse.
1.637     raeburn  3638: #
1.485     raeburn  3639: # output: url to file (if action was uploaddoc), 
                   3640: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3641: #
1.478     albertel 3642: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3643: # course.
1.477     raeburn  3644: #
1.478     albertel 3645: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3646: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3647: #          course's home server.
1.477     raeburn  3648: #
1.478     albertel 3649: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3650: #          be copied from $source (current location) to 
                   3651: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3652: #         and will then be copied to
                   3653: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3654: #         course's home server.
1.485     raeburn  3655: #
1.481     raeburn  3656: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3657: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3658: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3659: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3660: #         in course's home server.
1.637     raeburn  3661: #
1.477     raeburn  3662: 
                   3663: sub process_coursefile {
1.1095    raeburn  3664:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3665:         $mimetype)=@_;
1.477     raeburn  3666:     my $fetchresult;
1.638     albertel 3667:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3668:     if ($action eq 'propagate') {
1.638     albertel 3669:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3670: 			     $home);
1.481     raeburn  3671:     } else {
1.477     raeburn  3672:         my $fpath = '';
                   3673:         my $fname = $file;
1.478     albertel 3674:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3675:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3676:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3677:         if ($action eq 'copy') {
                   3678:             if ($source eq '') {
                   3679:                 $fetchresult = 'no source file';
                   3680:                 return $fetchresult;
                   3681:             } else {
                   3682:                 my $destination = $filepath.'/'.$fname;
                   3683:                 rename($source,$destination);
                   3684:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3685:                                  $home);
1.481     raeburn  3686:             }
                   3687:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3688:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3689:             print $fh $env{'form.'.$source};
1.481     raeburn  3690:             close($fh);
1.637     raeburn  3691:             if ($parser eq 'parse') {
1.1024    raeburn  3692:                 my $mm = new File::MMagic;
1.1095    raeburn  3693:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3694:                 if ($type eq 'text/html') {
1.1024    raeburn  3695:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3696:                     unless ($parse_result eq 'ok') {
                   3697:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3698:                     }
1.637     raeburn  3699:                 }
1.1095    raeburn  3700:                 if (ref($mimetype)) {
                   3701:                     $$mimetype = $type;
                   3702:                 } 
1.637     raeburn  3703:             }
1.477     raeburn  3704:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3705:                                  $home);
1.481     raeburn  3706:             if ($fetchresult eq 'ok') {
                   3707:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3708:             } else {
                   3709:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3710:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3711:                 return '/adm/notfound.html';
                   3712:             }
1.477     raeburn  3713:         }
                   3714:     }
1.485     raeburn  3715:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3716:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3717:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3718:     }
                   3719:     return $fetchresult;
                   3720: }
                   3721: 
1.637     raeburn  3722: sub build_filepath {
                   3723:     my ($fpath) = @_;
                   3724:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3725:     unless ($fpath eq '') {
                   3726:         my @parts=split('/',$fpath);
                   3727:         foreach my $part (@parts) {
                   3728:             $filepath.= '/'.$part;
                   3729:             if ((-e $filepath)!=1) {
                   3730:                 mkdir($filepath,0777);
                   3731:             }
                   3732:         }
                   3733:     }
                   3734:     return $filepath;
                   3735: }
                   3736: 
                   3737: sub store_edited_file {
1.638     albertel 3738:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3739:     my $file = $primary_url;
                   3740:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3741:     my $fpath = '';
                   3742:     my $fname = $file;
                   3743:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3744:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3745:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3746:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3747:     print $fh $content;
                   3748:     close($fh);
1.638     albertel 3749:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3750:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3751: 			  $home);
1.637     raeburn  3752:     if ($$fetchresult eq 'ok') {
                   3753:         return '/uploaded/'.$fpath.'/'.$fname;
                   3754:     } else {
1.638     albertel 3755:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3756: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3757:         return '/adm/notfound.html';
                   3758:     }
                   3759: }
                   3760: 
1.531     albertel 3761: sub clean_filename {
1.831     albertel 3762:     my ($fname,$args)=@_;
1.315     www      3763: # Replace Windows backslashes by forward slashes
1.257     www      3764:     $fname=~s/\\/\//g;
1.831     albertel 3765:     if (!$args->{'keep_path'}) {
                   3766:         # Get rid of everything but the actual filename
                   3767: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3768:     }
1.315     www      3769: # Replace spaces by underscores
                   3770:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  3771: # Transliterate non-ascii text to ascii
                   3772:     my $lang = &Apache::lonlocal::current_language();
                   3773:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3774: # Replace all other weird characters by nothing
1.831     albertel 3775:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3776: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3777: # numbers
                   3778:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3779:     return $fname;
                   3780: }
1.1172.2.110  raeburn  3781: 
1.1051    raeburn  3782: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3783: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3784: # image with the same aspect ratio as the original, but with dimensions which do 
                   3785: # not exceed $resizewidth and $resizeheight.
                   3786:  
1.984     neumanie 3787: sub resizeImage {
1.1051    raeburn  3788:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3789:     my $ima = Image::Magick->new;
                   3790:     my $resized;
                   3791:     if (-e $img_path) {
                   3792:         $ima->Read($img_path);
                   3793:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3794:             my $width = $ima->Get('width');
                   3795:             my $height = $ima->Get('height');
                   3796:             if ($width > $resizewidth) {
                   3797: 	        my $factor = $width/$resizewidth;
                   3798:                 my $newheight = $height/$factor;
                   3799:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3800:                 $resized = 1;
                   3801:             }
                   3802:         }
                   3803:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3804:             my $width = $ima->Get('width');
                   3805:             my $height = $ima->Get('height');
                   3806:             if ($height > $resizeheight) {
                   3807:                 my $factor = $height/$resizeheight;
                   3808:                 my $newwidth = $width/$factor;
                   3809:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3810:                 $resized = 1;
                   3811:             }
                   3812:         }
                   3813:         if ($resized) {
                   3814:             $ima->Write($img_path);
                   3815:         }
                   3816:     }
                   3817:     return;
1.977     amueller 3818: }
                   3819: 
1.608     albertel 3820: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3821: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3822: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3823: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.109  raeburn  3824: #                                    canceloverwrite, scantron or ''. 
1.1090    raeburn  3825: #                   if 'coursedoc': upload to the current course
                   3826: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3827: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3828: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3829: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  3830: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3831: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3832: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   3833: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3834: #        $allfiles - reference to hash for embedded objects
                   3835: #        $codebase - reference to hash for codebase of java objects
                   3836: #        $desuname - username for permanent storage of uploaded file
                   3837: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3838: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3839: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3840: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3841: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3842: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3843: #                    from File::MMagic.
1.858     raeburn  3844: # 
1.686     albertel 3845: # output: url of file in userspace, or error: <message> 
                   3846: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3847: 
1.531     albertel 3848: sub userfileupload {
1.1090    raeburn  3849:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3850:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3851:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3852:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3853:     $fname=&clean_filename($fname);
1.1090    raeburn  3854:     # See if there is anything left
1.257     www      3855:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  3856:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   3857:     if ($fname =~ /^\./) {
                   3858:         my ($s,$usec) = &gettimeofday();
                   3859:         while (length($usec) < 6) {
                   3860:             $usec = '0'.$usec;
                   3861:         }
                   3862:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   3863:     }
1.1090    raeburn  3864:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3865:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3866:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3867:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3868:         my $now = time;
1.1090    raeburn  3869:         my $filepath;
1.1095    raeburn  3870:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3871:              $filepath = 'tmp/helprequests/'.$now;
                   3872:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3873:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3874:                          '_'.$env{'user.domain'}.'/pending';
                   3875:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3876:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3877:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3878:                 $docudom = $destudom;
                   3879:             } else {
                   3880:                 $docudom = $env{'user.domain'};
                   3881:             }
1.1172.2.96  raeburn  3882:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3883:                 $docuname = $destuname;
                   3884:             } else {
                   3885:                 $docuname = $env{'user.name'};
                   3886:             }
                   3887:             if (exists($env{'form.group'})) {
                   3888:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3889:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3890:             }
                   3891:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3892:             if ($context eq 'canceloverwrite') {
                   3893:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3894:                 if (-e  $tempfile) {
                   3895:                     my @info = stat($tempfile);
                   3896:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3897:                         unlink($tempfile);
                   3898:                     }
                   3899:                 }
                   3900:                 return;
1.523     raeburn  3901:             }
                   3902:         }
1.1090    raeburn  3903:         # Create the directory if not present
1.741     raeburn  3904:         my @parts=split(/\//,$filepath);
                   3905:         my $fullpath = $perlvar{'lonDaemons'};
                   3906:         for (my $i=0;$i<@parts;$i++) {
                   3907:             $fullpath .= '/'.$parts[$i];
                   3908:             if ((-e $fullpath)!=1) {
                   3909:                 mkdir($fullpath,0777);
                   3910:             }
                   3911:         }
1.1172.2.96  raeburn  3912:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3913:         print $fh $env{'form.'.$formname};
                   3914:         close($fh);
1.1090    raeburn  3915:         if ($context eq 'existingfile') {
                   3916:             my @info = stat($fullpath.'/'.$fname);
                   3917:             return ($fullpath.'/'.$fname,$info[9]);
                   3918:         } else {
                   3919:             return $fullpath.'/'.$fname;
                   3920:         }
1.523     raeburn  3921:     }
1.995     raeburn  3922:     if ($subdir eq 'scantron') {
                   3923:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3924:     } else {
1.995     raeburn  3925:         $fname="$subdir/$fname";
                   3926:     }
1.1090    raeburn  3927:     if ($context eq 'coursedoc') {
1.638     albertel 3928: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3929: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3930:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3931:             return &finishuserfileupload($docuname,$docudom,
                   3932: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3933: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3934:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3935:         } else {
1.1172.2.21  raeburn  3936:             if ($env{'form.folder'}) {
                   3937:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3938:             }
1.638     albertel 3939:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3940: 				       $fname,$formname,$parser,
1.1095    raeburn  3941: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3942:         }
1.719     banghart 3943:     } elsif (defined($destuname)) {
                   3944:         my $docuname=$destuname;
                   3945:         my $docudom=$destudom;
1.860     raeburn  3946: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3947: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3948:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3949:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3950:     } else {
1.638     albertel 3951:         my $docuname=$env{'user.name'};
                   3952:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  3953:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3954:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3955:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3956:         }
1.860     raeburn  3957: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3958: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3959:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3960:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3961:     }
1.271     www      3962: }
                   3963: 
                   3964: sub finishuserfileupload {
1.860     raeburn  3965:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3966:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3967:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3968:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3969:   
1.860     raeburn  3970:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3971:     $file=$fname;
                   3972:     if ($fname=~m|/|) {
                   3973:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3974: 	$path.=$fnamepath.'/';
                   3975:     }
1.259     www      3976:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3977:     my $count;
                   3978:     for ($count=4;$count<=$#parts;$count++) {
                   3979:         $filepath.="/$parts[$count]";
                   3980:         if ((-e $filepath)!=1) {
                   3981: 	    mkdir($filepath,0777);
                   3982:         }
                   3983:     }
1.984     neumanie 3984: 
1.258     www      3985: # Save the file
                   3986:     {
1.1172.2.96  raeburn  3987: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3988: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3989: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3990: 	    return '/adm/notfound.html';
                   3991: 	}
1.1090    raeburn  3992:         if ($context eq 'overwrite') {
1.1117    foxr     3993:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3994:             my $target = $filepath.'/'.$file;
                   3995:             if (-e $source) {
                   3996:                 my @info = stat($source);
                   3997:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3998:                     unless (&File::Copy::move($source,$target)) {
                   3999:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4000:                         return "Moving from $source failed";
                   4001:                     }
                   4002:                 } else {
                   4003:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4004:                 }
                   4005:             } else {
                   4006:                 return "Temporary file: $source missing";
                   4007:             }
                   4008:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4009: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4010: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4011: 	    return '/adm/notfound.html';
                   4012: 	}
1.570     albertel 4013: 	close(FH);
1.1051    raeburn  4014:         if ($resizewidth && $resizeheight) {
                   4015:             my $mm = new File::MMagic;
                   4016:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4017:             if ($mime_type =~ m{^image/}) {
                   4018: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4019:             }  
1.977     amueller 4020: 	}
1.258     www      4021:     }
1.1152    raeburn  4022:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4023:         if (ref($mimetype)) {
                   4024:             if ($$mimetype eq '') {
                   4025:                 my $mm = new File::MMagic;
                   4026:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4027:                 $$mimetype = $type;
                   4028:             }
                   4029:         }
                   4030:     }
1.1172.2.109  raeburn  4031:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4032:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4033:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4034:                                                        $allfiles,$codebase);
                   4035:             unless ($parse_result eq 'ok') {
                   4036:                 &logthis('Failed to parse '.$filepath.$file.
                   4037: 	   	         ' for embedded media: '.$parse_result); 
                   4038:             }
1.637     raeburn  4039:         }
1.1172.2.109  raeburn  4040:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4041:         my $format = $env{'form.scantron_format'};
                   4042:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4043:     }
1.860     raeburn  4044:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4045:         my $input = $filepath.'/'.$file;
                   4046:         my $output = $filepath.'/'.'tn-'.$file;
                   4047:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  4048:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4049:         system({$args[0]} @args);
1.860     raeburn  4050:         if (-e $filepath.'/'.'tn-'.$file) {
                   4051:             $fetchthumb  = 1; 
                   4052:         }
                   4053:     }
1.858     raeburn  4054:  
1.259     www      4055: # Notify homeserver to grep it
                   4056: #
1.984     neumanie 4057:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4058:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4059:     if ($fetchresult eq 'ok') {
1.860     raeburn  4060:         if ($fetchthumb) {
                   4061:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4062:             if ($thumbresult ne 'ok') {
                   4063:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4064:                          $docuhome.': '.$thumbresult);
                   4065:             }
                   4066:         }
1.259     www      4067: #
1.258     www      4068: # Return the URL to it
1.494     albertel 4069:         return '/uploaded/'.$path.$file;
1.263     www      4070:     } else {
1.494     albertel 4071:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4072: 		 ': '.$fetchresult);
1.263     www      4073:         return '/adm/notfound.html';
1.858     raeburn  4074:     }
1.493     albertel 4075: }
                   4076: 
1.637     raeburn  4077: sub extract_embedded_items {
1.961     raeburn  4078:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4079:     my @state = ();
1.1164    raeburn  4080:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4081:     my %javafiles = (
                   4082:                       codebase => '',
                   4083:                       code => '',
                   4084:                       archive => ''
                   4085:                     );
                   4086:     my %mediafiles = (
                   4087:                       src => '',
                   4088:                       movie => '',
                   4089:                      );
1.648     raeburn  4090:     my $p;
                   4091:     if ($content) {
                   4092:         $p = HTML::LCParser->new($content);
                   4093:     } else {
1.961     raeburn  4094:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4095:     }
1.641     albertel 4096:     while (my $t=$p->get_token()) {
1.640     albertel 4097: 	if ($t->[0] eq 'S') {
                   4098: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4099: 	    push(@state, $tagname);
1.648     raeburn  4100:             if (lc($tagname) eq 'allow') {
                   4101:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4102:             }
1.640     albertel 4103: 	    if (lc($tagname) eq 'img') {
                   4104: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4105: 	    }
1.886     albertel 4106: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  4107:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   4108: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   4109:                 }
1.886     albertel 4110: 	    }
1.645     raeburn  4111:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4112:                 my $src;
1.645     raeburn  4113:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4114:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4115:                 } else {
1.1164    raeburn  4116:                     if ($attr->{'src'} ne '') {
                   4117:                         $src = $attr->{'src'};
                   4118:                         &add_filetype($allfiles,$src,'src');
                   4119:                     }
                   4120:                 }
                   4121:                 my $text = $p->get_trimmed_text();
                   4122:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4123:                     my @swfargs = split(/,/,$1);
                   4124:                     foreach my $item (@swfargs) {
                   4125:                         $item =~ s/["']//g;
                   4126:                         $item =~ s/^\s+//;
                   4127:                         $item =~ s/\s+$//;
                   4128:                     }
                   4129:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4130:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4131:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4132:                         } else {
                   4133:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4134:                         }
                   4135:                     }
1.645     raeburn  4136:                 }
                   4137:             }
                   4138:             if (lc($tagname) eq 'link') {
                   4139:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4140:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4141:                 }
                   4142:             }
1.640     albertel 4143: 	    if (lc($tagname) eq 'object' ||
                   4144: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4145: 		foreach my $item (keys(%javafiles)) {
                   4146: 		    $javafiles{$item} = '';
                   4147: 		}
1.1164    raeburn  4148:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4149:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4150:                 }
1.640     albertel 4151: 	    }
                   4152: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4153: 		my $name = lc($attr->{'name'});
                   4154: 		foreach my $item (keys(%javafiles)) {
                   4155: 		    if ($name eq $item) {
                   4156: 			$javafiles{$item} = $attr->{'value'};
                   4157: 			last;
                   4158: 		    }
                   4159: 		}
1.1164    raeburn  4160:                 my $pathfrom;
1.640     albertel 4161: 		foreach my $item (keys(%mediafiles)) {
                   4162: 		    if ($name eq $item) {
1.1164    raeburn  4163:                         $pathfrom = $attr->{'value'};
                   4164:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4165: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4166: 			last;
                   4167: 		    }
                   4168: 		}
1.1164    raeburn  4169:                 if ($name eq 'flashvars') {
                   4170:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4171:                 }
                   4172:                 if ($pathfrom ne '') {
                   4173:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4174:                                          $pathfrom);
                   4175:                 }
1.640     albertel 4176: 	    }
                   4177: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4178: 		foreach my $item (keys(%javafiles)) {
                   4179: 		    if ($attr->{$item}) {
                   4180: 			$javafiles{$item} = $attr->{$item};
                   4181: 			last;
                   4182: 		    }
                   4183: 		}
                   4184: 		foreach my $item (keys(%mediafiles)) {
                   4185: 		    if ($attr->{$item}) {
                   4186: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4187: 			last;
                   4188: 		    }
                   4189: 		}
1.1164    raeburn  4190:                 if (lc($tagname) eq 'embed') {
                   4191:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4192:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4193:                                              $attr->{'src'});
                   4194:                     }
                   4195:                 }
1.640     albertel 4196: 	    }
1.1172.2.35  raeburn  4197:             if (lc($tagname) eq 'iframe') {
                   4198:                 my $src = $attr->{'src'} ;
                   4199:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4200:                     &add_filetype($allfiles,$src,'src');
                   4201:                 } elsif ($src =~ m{^/}) {
                   4202:                     if ($env{'request.course.id'}) {
                   4203:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4204:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4205:                         my $url = &hreflocation('',$fullpath);
                   4206:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4207:                             my $relpath = $1;
                   4208:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4209:                                 &add_filetype($allfiles,$1,'src');
                   4210:                             }
                   4211:                         }
                   4212:                     }
                   4213:                 }
                   4214:             }
1.1164    raeburn  4215:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4216:                 pop(@state);
1.1164    raeburn  4217:             }
1.640     albertel 4218: 	} elsif ($t->[0] eq 'E') {
                   4219: 	    my ($tagname) = ($t->[1]);
                   4220: 	    if ($javafiles{'codebase'} ne '') {
                   4221: 		$javafiles{'codebase'} .= '/';
                   4222: 	    }  
                   4223: 	    if (lc($tagname) eq 'applet' ||
                   4224: 		lc($tagname) eq 'object' ||
                   4225: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4226: 		) {
                   4227: 		foreach my $item (keys(%javafiles)) {
                   4228: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4229: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4230: 			&add_filetype($allfiles,$file,$item);
                   4231: 		    }
                   4232: 		}
                   4233: 	    } 
                   4234: 	    pop @state;
                   4235: 	}
                   4236:     }
1.1164    raeburn  4237:     foreach my $id (sort(keys(%flashvars))) {
                   4238:         if ($shockwave{$id} ne '') {
                   4239:             my @pairs = split(/\&/,$flashvars{$id});
                   4240:             foreach my $pair (@pairs) {
                   4241:                 my ($key,$value) = split(/\=/,$pair);
                   4242:                 if ($key eq 'thumb') {
                   4243:                     &add_filetype($allfiles,$value,$key);
                   4244:                 } elsif ($key eq 'content') {
                   4245:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4246:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4247:                     if ($ext ne '') {
                   4248:                         &add_filetype($allfiles,$path.$value,$ext);
                   4249:                     }
                   4250:                 }
                   4251:             }
                   4252:         }
                   4253:     }
1.637     raeburn  4254:     return 'ok';
                   4255: }
                   4256: 
1.639     albertel 4257: sub add_filetype {
                   4258:     my ($allfiles,$file,$type)=@_;
                   4259:     if (exists($allfiles->{$file})) {
                   4260: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4261: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4262: 	}
                   4263:     } else {
                   4264: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4265:     }
                   4266: }
                   4267: 
1.1164    raeburn  4268: sub embedded_dependency {
                   4269:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4270:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4271:         if (($identifier ne '') &&
                   4272:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4273:             ($pathfrom ne '')) {
                   4274:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4275:             foreach my $dep (@{$related->{$identifier}}) {
                   4276:                 &add_filetype($allfiles,$path.$dep,'object');
                   4277:             }
                   4278:         }
                   4279:     }
                   4280:     return;
                   4281: }
                   4282: 
1.1172.2.109  raeburn  4283: sub bubblesheet_converter {
                   4284:     my ($cdom,$fullpath,$config,$format) = @_;
                   4285:     if ((&domain($cdom) ne '') &&
                   4286:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4287:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4288:         my (%csvcols,%csvoptions);
                   4289:         if (ref($config->{'fields'}) eq 'HASH') {
                   4290:             %csvcols = %{$config->{'fields'}};
                   4291:         }
                   4292:         if (ref($config->{'options'}) eq 'HASH') {
                   4293:             %csvoptions = %{$config->{'options'}};
                   4294:         }
                   4295:         my %csvbynum = reverse(%csvcols);
                   4296:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4297:         if (keys(%scantronconf)) {
                   4298:             my %bynum = (
                   4299:                           $scantronconf{CODEstart} => 'CODEstart',
                   4300:                           $scantronconf{IDstart}   => 'IDstart',
                   4301:                           $scantronconf{PaperID}   => 'PaperID',
                   4302:                           $scantronconf{FirstName} => 'FirstName',
                   4303:                           $scantronconf{LastName}  => 'LastName',
                   4304:                           $scantronconf{Qstart}    => 'Qstart',
                   4305:                         );
                   4306:             my @ordered;
                   4307:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4308:                 push(@ordered,$bynum{$item});
                   4309:             }
                   4310:             my %mapstart = (
                   4311:                               CODEstart => 'CODE',
                   4312:                               IDstart   => 'ID',
                   4313:                               PaperID   => 'PaperID',
                   4314:                               FirstName => 'FirstName',
                   4315:                               LastName  => 'LastName',
                   4316:                               Qstart    => 'FirstQuestion',
                   4317:                            );
                   4318:             my %maplength = (
                   4319:                               CODEstart => 'CODElength',
                   4320:                               IDstart   => 'IDlength',
                   4321:                               PaperID   => 'PaperIDlength',
                   4322:                               FirstName => 'FirstNamelength',
                   4323:                               LastName  => 'LastNamelength',
                   4324:             );
                   4325:             if (open(my $fh,'<',$fullpath)) {
                   4326:                 my $output;
                   4327:                 my %lettdig = &letter_to_digits();
                   4328:                 my %diglett = reverse(%lettdig);
                   4329:                 my $numletts = scalar(keys(%lettdig));
                   4330:                 my $num = 0;
                   4331:                 while (my $line=<$fh>) {
                   4332:                     $num ++;
                   4333:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4334:                     $line =~ s{[\r\n]+$}{};
                   4335:                     my %found;
                   4336:                     my @values = split(/,/,$line);
                   4337:                     my ($qstart,$record);
                   4338:                     for (my $i=0; $i<@values; $i++) {
                   4339:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4340:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4341:                             if ($values[$i] eq '') {
                   4342:                                 $values[$i] = $scantronconf{'Qoff'};
                   4343:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4344:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4345:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4346:                                 }
                   4347:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4348:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4349:                                     $values[$i] = $diglett{$values[$i]};
                   4350:                                 }
                   4351:                             } else {
                   4352:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4353:                                     my $digit;
                   4354:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4355:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4356:                                         if ($values[$i] eq 'J') {
                   4357:                                             $digit += $numletts;
                   4358:                                         }
                   4359:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4360:                                         $digit = $values[$i]-1;
                   4361:                                         if ($values[$i] eq '0') {
                   4362:                                             $digit += $numletts;
                   4363:                                         }
                   4364:                                     }
                   4365:                                     my $qval='';
                   4366:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4367:                                         if ($j == $digit) {
                   4368:                                             $qval .= $scantronconf{'Qon'};
                   4369:                                         } else {
                   4370:                                             $qval .= $scantronconf{'Qoff'};
                   4371:                                         }
                   4372:                                     }
                   4373:                                     $values[$i] = $qval;
                   4374:                                 }
                   4375:                             }
                   4376:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4377:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4378:                             }
                   4379:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4380:                             if ($numblank > 0) {
                   4381:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4382:                             }
                   4383:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4384:                                 $qstart = $i;
                   4385:                                 $found{$csvbynum{$i}} = $values[$i];
                   4386:                             } else {
                   4387:                                 $found{'FirstQuestion'} .= $values[$i];
                   4388:                             }
                   4389:                         } elsif (exists($csvbynum{$i})) {
                   4390:                             if ($csvoptions{'rem'}) {
                   4391:                                 $values[$i] =~ s/^\s+//;
                   4392:                             }
                   4393:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4394:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4395:                                     $values[$i] = '0'.$values[$i];
                   4396:                                 }
                   4397:                             }
                   4398:                             $found{$csvbynum{$i}} = $values[$i];
                   4399:                         }
                   4400:                     }
                   4401:                     foreach my $item (@ordered) {
                   4402:                         my $currlength = 1+length($record);
                   4403:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4404:                         if ($numspaces > 0) {
                   4405:                             $record .= (' ' x $numspaces);
                   4406:                         }
                   4407:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4408:                             unless ($item eq 'Qstart') {
                   4409:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4410:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4411:                                 }
                   4412:                             }
                   4413:                             $record .= $found{$mapstart{$item}};
                   4414:                         }
                   4415:                     }
                   4416:                     $output .= "$record\n";
                   4417:                 }
                   4418:                 close($fh);
                   4419:                 if ($output) {
                   4420:                     if (open(my $fh,'>',$fullpath)) {
                   4421:                         print $fh $output;
                   4422:                         close($fh);
                   4423:                     }
                   4424:                 }
                   4425:             }
                   4426:         }
                   4427:         return;
                   4428:     }
                   4429: }
                   4430: 
                   4431: sub letter_to_digits {
                   4432:     my %lettdig = (
                   4433:                     A => 1,
                   4434:                     B => 2,
                   4435:                     C => 3,
                   4436:                     D => 4,
                   4437:                     E => 5,
                   4438:                     F => 6,
                   4439:                     G => 7,
                   4440:                     H => 8,
                   4441:                     I => 9,
                   4442:                     J => 0,
                   4443:                   );
                   4444:     return %lettdig;
                   4445: }
                   4446: 
                   4447: sub get_scantron_config {
                   4448:     my ($which,$cdom) = @_;
                   4449:     my @lines = &get_scantronformat_file($cdom);
                   4450:     my %config;
                   4451:     #FIXME probably should move to XML it has already gotten a bit much now
                   4452:     foreach my $line (@lines) {
                   4453:         my ($name,$descrip)=split(/:/,$line);
                   4454:         if ($name ne $which ) { next; }
                   4455:         chomp($line);
                   4456:         my @config=split(/:/,$line);
                   4457:         $config{'name'}=$config[0];
                   4458:         $config{'description'}=$config[1];
                   4459:         $config{'CODElocation'}=$config[2];
                   4460:         $config{'CODEstart'}=$config[3];
                   4461:         $config{'CODElength'}=$config[4];
                   4462:         $config{'IDstart'}=$config[5];
                   4463:         $config{'IDlength'}=$config[6];
                   4464:         $config{'Qstart'}=$config[7];
                   4465:         $config{'Qlength'}=$config[8];
                   4466:         $config{'Qoff'}=$config[9];
                   4467:         $config{'Qon'}=$config[10];
                   4468:         $config{'PaperID'}=$config[11];
                   4469:         $config{'PaperIDlength'}=$config[12];
                   4470:         $config{'FirstName'}=$config[13];
                   4471:         $config{'FirstNamelength'}=$config[14];
                   4472:         $config{'LastName'}=$config[15];
                   4473:         $config{'LastNamelength'}=$config[16];
                   4474:         $config{'BubblesPerRow'}=$config[17];
                   4475:         last;
                   4476:     }
                   4477:     return %config;
                   4478: }
                   4479: 
                   4480: sub get_scantronformat_file {
                   4481:     my ($cdom) = @_;
                   4482:     if ($cdom eq '') {
                   4483:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4484:     }
                   4485:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4486:     my $gottab = 0;
                   4487:     my @lines;
                   4488:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4489:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4490:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4491:             if ($formatfile ne '-1') {
                   4492:                 @lines = split("\n",$formatfile,-1);
                   4493:                 $gottab = 1;
                   4494:             }
                   4495:         }
                   4496:     }
                   4497:     if (!$gottab) {
                   4498:         my $confname = $cdom.'-domainconfig';
                   4499:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4500:         my $formatfile = &getfile($default);
                   4501:         if ($formatfile ne '-1') {
                   4502:             @lines = split("\n",$formatfile,-1);
                   4503:             $gottab = 1;
                   4504:         }
                   4505:     }
                   4506:     if (!$gottab) {
                   4507:         my @domains = &current_machine_domains();
                   4508:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4509:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4510:                 @lines = <$fh>;
                   4511:                 close($fh);
                   4512:             }
                   4513:         } else {
                   4514:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4515:                 @lines = <$fh>;
                   4516:                 close($fh);
                   4517:             }
                   4518:         }
                   4519:     }
                   4520:     return @lines;
                   4521: }
                   4522: 
1.493     albertel 4523: sub removeuploadedurl {
1.984     neumanie 4524:     my ($url)=@_;	
                   4525:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4526:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4527: }
                   4528: 
                   4529: sub removeuserfile {
                   4530:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4531:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4532:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4533:     if ($result eq 'ok') {	
1.798     raeburn  4534:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4535:             my $metafile = $fname.'.meta';
                   4536:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4537: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4538:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4539:             my $sqlresult = 
1.823     albertel 4540:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4541:                                         'portfolio_metadata',$group,
                   4542:                                         'delete');
1.798     raeburn  4543:         }
                   4544:     }
                   4545:     return $result;
1.257     www      4546: }
1.15      www      4547: 
1.530     albertel 4548: sub mkdiruserfile {
                   4549:     my ($docuname,$docudom,$dir)=@_;
                   4550:     my $home=&homeserver($docuname,$docudom);
                   4551:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4552: }
                   4553: 
1.531     albertel 4554: sub renameuserfile {
                   4555:     my ($docuname,$docudom,$old,$new)=@_;
                   4556:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4557:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4558:                         &escape("$old").':'.&escape("$new"),$home);
                   4559:     if ($result eq 'ok') {
                   4560:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4561:             my $oldmeta = $old.'.meta';
                   4562:             my $newmeta = $new.'.meta';
                   4563:             my $metaresult = 
                   4564:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4565: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4566:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4567:             my $sqlresult = 
1.823     albertel 4568:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4569:                                         'portfolio_metadata',$group,
                   4570:                                         'delete');
1.798     raeburn  4571:         }
                   4572:     }
                   4573:     return $result;
1.531     albertel 4574: }
                   4575: 
1.14      www      4576: # ------------------------------------------------------------------------- Log
                   4577: 
                   4578: sub log {
                   4579:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4580:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4581: }
                   4582: 
                   4583: # ------------------------------------------------------------------ Course Log
1.352     www      4584: #
                   4585: # This routine flushes several buffers of non-mission-critical nature
                   4586: #
1.157     www      4587: 
                   4588: sub flushcourselogs {
1.352     www      4589:     &logthis('Flushing log buffers');
                   4590: #
                   4591: # course logs
                   4592: # This is a log of all transactions in a course, which can be used
                   4593: # for data mining purposes
                   4594: #
                   4595: # It also collects the courseid database, which lists last transaction
                   4596: # times and course titles for all courseids
                   4597: #
                   4598:     my %courseidbuffer=();
1.921     raeburn  4599:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4600:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4601: 		          &escape($courselogs{$crsid}),
                   4602: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4603: 	    delete $courselogs{$crsid};
                   4604:         } else {
                   4605:             &logthis('Failed to flush log buffer for '.$crsid);
                   4606:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4607:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4608:                         " exceeded maximum size, deleting.</font>");
                   4609:                delete $courselogs{$crsid};
                   4610:             }
1.352     www      4611:         }
1.920     raeburn  4612:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4613:             'description' => $coursedescrbuf{$crsid},
                   4614:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4615:             'type'        => $coursetypebuf{$crsid},
                   4616:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4617:         };
1.191     harris41 4618:     }
1.352     www      4619: #
                   4620: # Write course id database (reverse lookup) to homeserver of courses 
                   4621: # Is used in pickcourse
                   4622: #
1.840     albertel 4623:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4624:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4625:                                     $courseidbuffer{$crs_home},
                   4626:                                     $crs_home,'timeonly');
1.352     www      4627:     }
                   4628: #
                   4629: # File accesses
                   4630: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4631: #
1.449     matthew  4632:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4633:         if ($entry =~ /___count$/) {
                   4634:             my ($dom,$name);
1.807     albertel 4635:             ($dom,$name,undef)=
1.811     albertel 4636: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4637:             if (! defined($dom) || $dom eq '' || 
                   4638:                 ! defined($name) || $name eq '') {
1.620     albertel 4639:                 my $cid = $env{'request.course.id'};
                   4640:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4641:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4642:             }
1.450     matthew  4643:             my $value = $accesshash{$entry};
                   4644:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4645:             my %temphash=($url => $value);
1.449     matthew  4646:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4647:             if ($result eq 'ok') {
                   4648:                 delete $accesshash{$entry};
                   4649:             }
                   4650:         } else {
1.811     albertel 4651:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4652:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4653:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4654:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4655:                 delete $accesshash{$entry};
                   4656:             }
1.185     www      4657:         }
1.191     harris41 4658:     }
1.352     www      4659: #
                   4660: # Roles
                   4661: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4662: #
1.800     albertel 4663:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4664:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4665: 	    split(/\:/,$entry);
                   4666:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4667:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4668:                 $rudom,$runame) eq 'ok') {
                   4669: 	    delete $userrolehash{$entry};
                   4670:         }
                   4671:     }
1.662     raeburn  4672: #
1.1172.2.90  raeburn  4673: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4674: #
                   4675:     my %domrolebuffer = ();
1.1000    raeburn  4676:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4677:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4678:         if ($domrolebuffer{$rudom}) {
                   4679:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4680:                       '='.&escape($domainrolehash{$entry});
                   4681:         } else {
                   4682:             $domrolebuffer{$rudom}.=&escape($entry).
                   4683:                       '='.&escape($domainrolehash{$entry});
                   4684:         }
                   4685:         delete $domainrolehash{$entry};
                   4686:     }
                   4687:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4688:         my %servers;
                   4689:         if (defined(&domain($dom,'primary'))) {
                   4690:             my $primary=&domain($dom,'primary');
                   4691:             my $hostname=&hostname($primary);
                   4692:             $servers{$primary} = $hostname;
                   4693:         } else {
                   4694:             %servers = &get_servers($dom,'library');
                   4695:         }
1.841     albertel 4696: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4697: 	    if (&reply('domroleput:'.$dom.':'.
                   4698: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4699: 	        last;
                   4700: 	    } else {
1.841     albertel 4701: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4702: 	    }
1.662     raeburn  4703:         }
                   4704:     }
1.186     www      4705:     $dumpcount++;
1.157     www      4706: }
                   4707: 
                   4708: sub courselog {
                   4709:     my $what=shift;
1.158     www      4710:     $what=time.':'.$what;
1.620     albertel 4711:     unless ($env{'request.course.id'}) { return ''; }
                   4712:     $coursedombuf{$env{'request.course.id'}}=
                   4713:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4714:     $coursenumbuf{$env{'request.course.id'}}=
                   4715:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4716:     $coursehombuf{$env{'request.course.id'}}=
                   4717:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4718:     $coursedescrbuf{$env{'request.course.id'}}=
                   4719:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4720:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4721:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4722:     $courseownerbuf{$env{'request.course.id'}}=
                   4723:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4724:     $coursetypebuf{$env{'request.course.id'}}=
                   4725:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4726:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4727: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4728:     } else {
1.620     albertel 4729: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4730:     }
1.620     albertel 4731:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4732: 	&flushcourselogs();
                   4733:     }
1.158     www      4734: }
                   4735: 
                   4736: sub courseacclog {
                   4737:     my $fnsymb=shift;
1.620     albertel 4738:     unless ($env{'request.course.id'}) { return ''; }
                   4739:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4740:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4741:         $what.=':POST';
1.583     matthew  4742:         # FIXME: Probably ought to escape things....
1.800     albertel 4743: 	foreach my $key (keys(%env)) {
                   4744:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4745:                 my $formitem = $1;
                   4746:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4747:                     $what.=':'.$formitem.'='.$env{$key};
                   4748:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.118.  .12(raeb 4749:-20):                     if ($formitem eq 'proctorpassword') {
                   4750:-20):                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
                   4751:-20):                     } else {
                   4752:-20):                         $what.=':'.$formitem.'='.$env{$key};
                   4753:-20):                     }
1.975     raeburn  4754:                 }
1.158     www      4755:             }
1.191     harris41 4756:         }
1.583     matthew  4757:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4758:         # FIXME: We should not be depending on a form parameter that someone
                   4759:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4760:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4761:             $what.= ':POST';
                   4762:             # FIXME: Probably ought to escape things....
                   4763:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4764:                                  'crsdiscuss') {
1.620     albertel 4765:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4766:             }
                   4767:         }
1.158     www      4768:     }
                   4769:     &courselog($what);
1.149     www      4770: }
                   4771: 
1.185     www      4772: sub countacc {
                   4773:     my $url=&declutter(shift);
1.458     matthew  4774:     return if (! defined($url) || $url eq '');
1.620     albertel 4775:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4776: #
                   4777: # Mark that this url was used in this course
                   4778: #
1.620     albertel 4779:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4780: #
                   4781: # Increase the access count for this resource in this child process
                   4782: #
1.281     www      4783:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4784:     $accesshash{$key}++;
1.185     www      4785: }
1.349     www      4786: 
1.361     www      4787: sub linklog {
                   4788:     my ($from,$to)=@_;
                   4789:     $from=&declutter($from);
                   4790:     $to=&declutter($to);
                   4791:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4792:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4793: }
1.1160    www      4794: 
                   4795: sub statslog {
                   4796:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4797:     if ($users<2) { return; }
                   4798:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4799:             'course'       => $env{'request.course.id'},
                   4800:             'sections'     => '"all"',
                   4801:             'num_students' => $users,
                   4802:             'part'         => $part,
                   4803:             'symb'         => $symb,
                   4804:             'mean_tries'   => $av_attempts,
                   4805:             'deg_of_diff'  => $degdiff});
                   4806:     foreach my $key (keys(%dynstore)) {
                   4807:         $accesshash{$key}=$dynstore{$key};
                   4808:     }
                   4809: }
1.361     www      4810:   
1.349     www      4811: sub userrolelog {
                   4812:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4813:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4814:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4815:        $userrolehash
                   4816:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4817:                     =$tend.':'.$tstart;
1.662     raeburn  4818:     }
1.1169    droeschl 4819:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4820:        $userrolehash
                   4821:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4822:                     =$tend.':'.$tstart;
                   4823:     }
1.1172.2.90  raeburn  4824:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4825:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4826:        $domainrolehash
                   4827:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4828:                     = $tend.':'.$tstart;
                   4829:     }
1.351     www      4830: }
                   4831: 
1.957     raeburn  4832: sub courserolelog {
                   4833:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4834:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4835:         my $cdom = $1;
                   4836:         my $cnum = $2;
                   4837:         my $sec = $3;
                   4838:         my $namespace = 'rolelog';
                   4839:         my %storehash = (
                   4840:                            role    => $trole,
                   4841:                            start   => $tstart,
                   4842:                            end     => $tend,
                   4843:                            selfenroll => $selfenroll,
                   4844:                            context    => $context,
                   4845:                         );
                   4846:         if ($trole eq 'gr') {
                   4847:             $namespace = 'groupslog';
                   4848:             $storehash{'group'} = $sec;
                   4849:         } else {
                   4850:             $storehash{'section'} = $sec;
                   4851:         }
                   4852:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4853:                    $domain,$cnum,$cdom);
                   4854:         if (($trole ne 'st') || ($sec ne '')) {
                   4855:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4856:         }
                   4857:     }
                   4858:     return;
                   4859: }
                   4860: 
1.1172.2.9  raeburn  4861: sub domainrolelog {
                   4862:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4863:     if ($area =~ m{^/($match_domain)/$}) {
                   4864:         my $cdom = $1;
                   4865:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4866:         my $namespace = 'rolelog';
                   4867:         my %storehash = (
                   4868:                            role    => $trole,
                   4869:                            start   => $tstart,
                   4870:                            end     => $tend,
                   4871:                            context => $context,
                   4872:                         );
                   4873:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4874:                    $domain,$domconfiguser,$cdom);
                   4875:     }
                   4876:     return;
                   4877: 
                   4878: }
                   4879: 
                   4880: sub coauthorrolelog {
                   4881:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4882:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4883:         my $audom = $1;
                   4884:         my $auname = $2;
                   4885:         my $namespace = 'rolelog';
                   4886:         my %storehash = (
                   4887:                            role    => $trole,
                   4888:                            start   => $tstart,
                   4889:                            end     => $tend,
                   4890:                            context => $context,
                   4891:                         );
                   4892:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4893:                    $domain,$auname,$audom);
                   4894:     }
                   4895:     return;
                   4896: }
                   4897: 
1.351     www      4898: sub get_course_adv_roles {
1.948     raeburn  4899:     my ($cid,$codes) = @_;
1.620     albertel 4900:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4901:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4902:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4903:     my %nothide=();
1.800     albertel 4904:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4905:         if ($user !~ /:/) {
                   4906: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4907:         } else {
                   4908:             $nothide{$user}=1;
                   4909:         }
1.470     www      4910:     }
1.1172.2.23  raeburn  4911:     my @possdoms = ($coursehash{'domain'});
                   4912:     if ($coursehash{'checkforpriv'}) {
                   4913:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4914:     }
1.351     www      4915:     my %returnhash=();
                   4916:     my %dumphash=
                   4917:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4918:     my $now=time;
1.997     raeburn  4919:     my %privileged;
1.1000    raeburn  4920:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4921: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4922:         if (($tstart) && ($tstart<0)) { next; }
                   4923:         if (($tend) && ($tend<$now)) { next; }
                   4924:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4925:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4926: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4927:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4928:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4929: 	if ($role eq 'cr') { next; }
1.948     raeburn  4930:         if ($codes) {
                   4931:             if ($section) { $role .= ':'.$section; }
                   4932:             if ($returnhash{$role}) {
                   4933:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4934:             } else {
                   4935:                 $returnhash{$role}=$username.':'.$domain;
                   4936:             }
1.351     www      4937:         } else {
1.988     raeburn  4938:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4939:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4940:             if ($returnhash{$key}) {
                   4941: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4942:             } else {
                   4943:                 $returnhash{$key}=$username.':'.$domain;
                   4944:             }
1.351     www      4945:         }
1.948     raeburn  4946:     }
1.400     www      4947:     return %returnhash;
                   4948: }
                   4949: 
                   4950: sub get_my_roles {
1.937     raeburn  4951:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4952:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4953:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4954:     my (%dumphash,%nothide);
1.1086    raeburn  4955:     if ($context eq 'userroles') {
1.1166    raeburn  4956:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4957:     } else {
1.1172.2.23  raeburn  4958:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4959:         if ($hidepriv) {
                   4960:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4961:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4962:                 if ($user !~ /:/) {
                   4963:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4964:                 } else {
                   4965:                     $nothide{$user} = 1;
                   4966:                 }
                   4967:             }
                   4968:         }
1.858     raeburn  4969:     }
1.400     www      4970:     my %returnhash=();
                   4971:     my $now=time;
1.999     raeburn  4972:     my %privileged;
1.800     albertel 4973:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4974:         my ($role,$tend,$tstart);
                   4975:         if ($context eq 'userroles') {
1.1149    raeburn  4976:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4977: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4978:         } else {
                   4979:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4980:         }
1.400     www      4981:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4982:         my $status = 'active';
1.939     raeburn  4983:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4984:             $status = 'previous';
                   4985:         } 
                   4986:         if (($tstart) && ($now<$tstart)) {
                   4987:             $status = 'future';
                   4988:         }
                   4989:         if (ref($types) eq 'ARRAY') {
                   4990:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4991:                 next;
                   4992:             } 
                   4993:         } else {
                   4994:             if ($status ne 'active') {
                   4995:                 next;
                   4996:             }
                   4997:         }
1.867     raeburn  4998:         my ($rolecode,$username,$domain,$section,$area);
                   4999:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  5000:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5001:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5002:         } else {
                   5003:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5004:         }
1.832     raeburn  5005:         if (ref($roledoms) eq 'ARRAY') {
                   5006:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5007:                 next;
                   5008:             }
                   5009:         }
                   5010:         if (ref($roles) eq 'ARRAY') {
                   5011:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5012:                 if ($role =~ /^cr\//) {
                   5013:                     if (!grep(/^cr$/,@{$roles})) {
                   5014:                         next;
                   5015:                     }
1.1104    raeburn  5016:                 } elsif ($role =~ /^gr\//) {
                   5017:                     if (!grep(/^gr$/,@{$roles})) {
                   5018:                         next;
                   5019:                     }
1.922     raeburn  5020:                 } else {
                   5021:                     next;
                   5022:                 }
1.832     raeburn  5023:             }
1.867     raeburn  5024:         }
1.937     raeburn  5025:         if ($hidepriv) {
1.1172.2.23  raeburn  5026:             my @privroles = ('dc','su');
1.999     raeburn  5027:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  5028:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5029:             } else {
1.1172.2.23  raeburn  5030:                 my $possdoms = [$domain];
                   5031:                 if (ref($roledoms) eq 'ARRAY') {
                   5032:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  5033:                 }
1.1172.2.23  raeburn  5034:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5035:                     if (!$nothide{$username.':'.$domain}) {
                   5036:                         next;
                   5037:                     }
                   5038:                 }
1.937     raeburn  5039:             }
                   5040:         }
1.933     raeburn  5041:         if ($withsec) {
                   5042:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5043:                 $tstart.':'.$tend;
                   5044:         } else {
                   5045:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5046:         }
1.832     raeburn  5047:     }
1.373     www      5048:     return %returnhash;
1.399     www      5049: }
                   5050: 
1.1172.2.89  raeburn  5051: sub get_all_adhocroles {
                   5052:     my ($dom) = @_;
                   5053:     my @roles_by_num = ();
                   5054:     my %domdefaults = &get_domain_defaults($dom);
                   5055:     my (%description,%access_in_dom,%access_info);
                   5056:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5057:         my $count = 0;
                   5058:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5059:         my %ordered;
                   5060:         foreach my $role (sort(keys(%domcurrent))) {
                   5061:             my ($order,$desc,$access_in_dom);
                   5062:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5063:                 $order = $domcurrent{$role}{'order'};
                   5064:                 $desc = $domcurrent{$role}{'desc'};
                   5065:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5066:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5067:             }
                   5068:             if ($order eq '') {
                   5069:                 $order = $count;
                   5070:             }
                   5071:             $ordered{$order} = $role;
                   5072:             if ($desc ne '') {
                   5073:                 $description{$role} = $desc;
                   5074:             } else {
                   5075:                 $description{$role}= $role;
                   5076:             }
                   5077:             $count++;
                   5078:         }
                   5079:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5080:             push(@roles_by_num,$ordered{$item});
                   5081:         }
                   5082:     }
                   5083:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5084: }
                   5085: 
                   5086: sub get_my_adhocroles {
                   5087:     my ($cid,$checkreg) = @_;
                   5088:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5089:     if ($env{'request.course.id'} eq $cid) {
                   5090:         $cdom = $env{'course.'.$cid.'.domain'};
                   5091:         $cnum = $env{'course.'.$cid.'.num'};
                   5092:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5093:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5094:         $cdom = $1;
                   5095:         $cnum = $2;
                   5096:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5097:                                      $cdom,$cnum);
                   5098:     }
                   5099:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5100:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5101:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5102:         if ($rosterhash{$user} ne '') {
                   5103:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5104:             return ([],{}) if ($type eq 'auto');
                   5105:         }
                   5106:     }
                   5107:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5108:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5109:             my $then=$env{'user.login.time'};
                   5110:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5111:             if (!$update) {
                   5112:                 $update = $then;
                   5113:             }
                   5114:             my @liveroles;
                   5115:             foreach my $role ('dh','da') {
                   5116:                 if ($env{"user.role.$role./$cdom/"}) {
                   5117:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5118:                     my $limit = $update;
                   5119:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5120:                         $limit = $then;
                   5121:                     }
                   5122:                     my $activerole = 1;
                   5123:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5124:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5125:                     if ($activerole) {
                   5126:                         push(@liveroles,$role);
                   5127:                     }
                   5128:                 }
                   5129:             }
                   5130:             if (@liveroles) {
1.1172.2.89  raeburn  5131:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5132:                     my ($accessref,$accessinfo,%access_in_dom);
                   5133:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5134:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5135:                         if (@{$roles_by_num}) {
                   5136:                             my %settings;
                   5137:                             if ($env{'request.course.id'} eq $cid) {
                   5138:                                 foreach my $envkey (keys(%env)) {
                   5139:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5140:                                         $settings{$1} = $env{$envkey};
                   5141:                                     }
                   5142:                                 }
                   5143:                             } else {
                   5144:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5145:                             }
                   5146:                             my %setincrs;
                   5147:                             if ($settings{'internal.adhocaccess'}) {
                   5148:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5149:                             }
                   5150:                             my @statuses;
                   5151:                             if ($env{'environment.inststatus'}) {
                   5152:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5153:                             }
                   5154:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5155:                             if (ref($accessref) eq 'HASH') {
                   5156:                                 %access_in_dom = %{$accessref};
                   5157:                             }
                   5158:                             foreach my $role (@{$roles_by_num}) {
                   5159:                                 my ($curraccess,@okstatus,@personnel);
                   5160:                                 if ($setincrs{$role}) {
                   5161:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5162:                                     if ($curraccess eq 'status') {
                   5163:                                         @okstatus = split(/\&/,$rest);
                   5164:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5165:                                         @personnel = split(/\&/,$rest);
                   5166:                                     }
                   5167:                                 } else {
                   5168:                                     $curraccess = $access_in_dom{$role};
                   5169:                                     if (ref($accessinfo) eq 'HASH') {
                   5170:                                         if ($curraccess eq 'status') {
                   5171:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5172:                                                 @okstatus = @{$accessinfo->{$role}};
                   5173:                                             }
                   5174:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5175:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5176:                                                 @personnel = @{$accessinfo->{$role}};
                   5177:                                             }
                   5178:                                         }
                   5179:                                     }
                   5180:                                 }
                   5181:                                 if ($curraccess eq 'none') {
                   5182:                                     next;
                   5183:                                 } elsif ($curraccess eq 'all') {
                   5184:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5185:                                 } elsif ($curraccess eq 'dh') {
                   5186:                                     if (grep(/^dh$/,@liveroles)) {
                   5187:                                         push(@possroles,$role);
                   5188:                                     } else {
                   5189:                                         next;
                   5190:                                     }
                   5191:                                 } elsif ($curraccess eq 'da') {
                   5192:                                     if (grep(/^da$/,@liveroles)) {
                   5193:                                         push(@possroles,$role);
                   5194:                                     } else {
                   5195:                                         next;
                   5196:                                     }
1.1172.2.89  raeburn  5197:                                 } elsif ($curraccess eq 'status') {
                   5198:                                     if (@okstatus) {
                   5199:                                         if (!@statuses) {
                   5200:                                             if (grep(/^default$/,@okstatus)) {
                   5201:                                                 push(@possroles,$role);
                   5202:                                             }
                   5203:                                         } else {
                   5204:                                             foreach my $status (@okstatus) {
                   5205:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5206:                                                     push(@possroles,$role);
                   5207:                                                     last;
                   5208:                                                 }
                   5209:                                             }
                   5210:                                         }
                   5211:                                     }
                   5212:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5213:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5214:                                         if ($curraccess eq 'exc') {
                   5215:                                             push(@possroles,$role);
                   5216:                                         }
                   5217:                                     } elsif ($curraccess eq 'inc') {
                   5218:                                         push(@possroles,$role);
                   5219:                                     }
                   5220:                                 }
                   5221:                             }
                   5222:                         }
                   5223:                     }
                   5224:                 }
                   5225:             }
                   5226:         }
                   5227:     }
                   5228:     unless (ref($description) eq 'HASH') {
                   5229:         if (ref($roles_by_num) eq 'ARRAY') {
                   5230:             my %desc;
                   5231:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5232:             $description = \%desc;
                   5233:         } else {
                   5234:             $description = {};
                   5235:         }
                   5236:     }
                   5237:     return (\@possroles,$description);
                   5238: }
                   5239: 
1.399     www      5240: # ----------------------------------------------------- Frontpage Announcements
                   5241: #
                   5242: #
                   5243: 
                   5244: sub postannounce {
                   5245:     my ($server,$text)=@_;
1.844     albertel 5246:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5247:     unless ($text=~/\w/) { $text=''; }
                   5248:     return &reply('setannounce:'.&escape($text),$server);
                   5249: }
                   5250: 
                   5251: sub getannounce {
1.448     albertel 5252: 
1.1172.2.96  raeburn  5253:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5254: 	my $announcement='';
1.800     albertel 5255: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5256: 	close($fh);
1.399     www      5257: 	if ($announcement=~/\w/) { 
                   5258: 	    return 
                   5259:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5260:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5261: 	} else {
                   5262: 	    return '';
                   5263: 	}
                   5264:     } else {
                   5265: 	return '';
                   5266:     }
1.351     www      5267: }
1.353     www      5268: 
                   5269: # ---------------------------------------------------------- Course ID routines
                   5270: # Deal with domain's nohist_courseid.db files
                   5271: #
                   5272: 
                   5273: sub courseidput {
1.921     raeburn  5274:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5275:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5276:     my $outcome;
                   5277:     if ($caller eq 'timeonly') {
                   5278:         my $cids = '';
                   5279:         foreach my $item (keys(%$storehash)) {
                   5280:             $cids.=&escape($item).'&';
                   5281:         }
                   5282:         $cids=~s/\&$//;
                   5283:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5284:                           $coursehome);       
                   5285:     } else {
                   5286:         my $items = '';
                   5287:         foreach my $item (keys(%$storehash)) {
                   5288:             $items.= &escape($item).'='.
                   5289:                      &freeze_escape($$storehash{$item}).'&';
                   5290:         }
                   5291:         $items=~s/\&$//;
                   5292:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5293:                           $coursehome);
1.918     raeburn  5294:     }
                   5295:     if ($outcome eq 'unknown_cmd') {
                   5296:         my $what;
                   5297:         foreach my $cid (keys(%$storehash)) {
                   5298:             $what .= &escape($cid).'=';
1.921     raeburn  5299:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5300:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5301:             }
                   5302:             $what =~ s/\:$/&/;
                   5303:         }
                   5304:         $what =~ s/\&$//;  
                   5305:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5306:     } else {
                   5307:         return $outcome;
                   5308:     }
1.353     www      5309: }
                   5310: 
                   5311: sub courseiddump {
1.921     raeburn  5312:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5313:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5314:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5315:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5316:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5317:     my $as_hash = 1;
                   5318:     my %returnhash;
                   5319:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5320:     my %libserv = &all_library();
                   5321:     foreach my $tryserver (keys(%libserv)) {
                   5322:         if ( (  $hostidflag == 1 
                   5323: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5324: 	     || (!defined($hostidflag)) ) {
                   5325: 
1.918     raeburn  5326: 	    if (($domfilter eq '') ||
                   5327: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5328:                 my $rep;
                   5329:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5330:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5331:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5332:                                 &escape($descfilter), &escape($instcodefilter),
                   5333:                                 &escape($ownerfilter), &escape($coursefilter),
                   5334:                                 &escape($typefilter), &escape($regexp_ok),
                   5335:                                 $as_hash, &escape($selfenrollonly),
                   5336:                                 &escape($catfilter), $showhidden, $caller,
                   5337:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5338:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5339:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5340:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5341:                 } else {
                   5342:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5343:                              $sincefilter.':'.&escape($descfilter).':'.
                   5344:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5345:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5346:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5347:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5348:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5349:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5350:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5351:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5352:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5353:                 }
                   5354: 
1.918     raeburn  5355:                 my @pairs=split(/\&/,$rep);
                   5356:                 foreach my $item (@pairs) {
                   5357:                     my ($key,$value)=split(/\=/,$item,2);
                   5358:                     $key = &unescape($key);
                   5359:                     next if ($key =~ /^error: 2 /);
                   5360:                     my $result = &thaw_unescape($value);
                   5361:                     if (ref($result) eq 'HASH') {
                   5362:                         $returnhash{$key}=$result;
                   5363:                     } else {
1.921     raeburn  5364:                         my @responses = split(/:/,$value);
                   5365:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5366:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5367:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5368:                         }
1.1008    raeburn  5369:                     }
1.353     www      5370:                 }
                   5371:             }
                   5372:         }
                   5373:     }
                   5374:     return %returnhash;
                   5375: }
                   5376: 
1.1055    raeburn  5377: sub courselastaccess {
                   5378:     my ($cdom,$cnum,$hostidref) = @_;
                   5379:     my %returnhash;
                   5380:     if ($cdom && $cnum) {
                   5381:         my $chome = &homeserver($cnum,$cdom);
                   5382:         if ($chome ne 'no_host') {
                   5383:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5384:             &extract_lastaccess(\%returnhash,$rep);
                   5385:         }
                   5386:     } else {
                   5387:         if (!$cdom) { $cdom=''; }
                   5388:         my %libserv = &all_library();
                   5389:         foreach my $tryserver (keys(%libserv)) {
                   5390:             if (ref($hostidref) eq 'ARRAY') {
                   5391:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5392:             } 
                   5393:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5394:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5395:                 &extract_lastaccess(\%returnhash,$rep);
                   5396:             }
                   5397:         }
                   5398:     }
                   5399:     return %returnhash;
                   5400: }
                   5401: 
                   5402: sub extract_lastaccess {
                   5403:     my ($returnhash,$rep) = @_;
                   5404:     if (ref($returnhash) eq 'HASH') {
                   5405:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5406:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5407:                  $rep eq '') {
                   5408:             my @pairs=split(/\&/,$rep);
                   5409:             foreach my $item (@pairs) {
                   5410:                 my ($key,$value)=split(/\=/,$item,2);
                   5411:                 $key = &unescape($key);
                   5412:                 next if ($key =~ /^error: 2 /);
                   5413:                 $returnhash->{$key} = &thaw_unescape($value);
                   5414:             }
                   5415:         }
                   5416:     }
                   5417:     return;
                   5418: }
                   5419: 
1.658     raeburn  5420: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5421: 
                   5422: sub dcmailput {
1.685     raeburn  5423:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5424:     my $status = &Apache::lonnet::critical(
1.740     www      5425:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5426:        &escape($message),$server);
1.662     raeburn  5427:     return $status;
                   5428: }
                   5429: 
1.658     raeburn  5430: sub dcmaildump {
                   5431:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5432:     my %returnhash=();
1.846     albertel 5433: 
                   5434:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5435:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5436:                                                          &escape($enddate).':';
                   5437: 	my @esc_senders=map { &escape($_)} @$senders;
                   5438: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5439: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5440:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5441:             if (($key) && ($value)) {
                   5442:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5443:             }
                   5444:         }
                   5445:     }
                   5446:     return %returnhash;
                   5447: }
1.662     raeburn  5448: # ---------------------------------------------------------- Domain roles
                   5449: 
                   5450: sub get_domain_roles {
                   5451:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5452:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5453:         $startdate = '.';
                   5454:     }
1.1018    raeburn  5455:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5456:         $enddate = '.';
                   5457:     }
1.922     raeburn  5458:     my $rolelist;
                   5459:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5460:         $rolelist = join('&',@{$roles});
1.922     raeburn  5461:     }
1.662     raeburn  5462:     my %personnel = ();
1.841     albertel 5463: 
                   5464:     my %servers = &get_servers($dom,'library');
                   5465:     foreach my $tryserver (keys(%servers)) {
                   5466: 	%{$personnel{$tryserver}}=();
                   5467: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5468: 					    &escape($startdate).':'.
                   5469: 					    &escape($enddate).':'.
                   5470: 					    &escape($rolelist), $tryserver))) {
                   5471: 	    my ($key,$value) = split(/\=/,$line,2);
                   5472: 	    if (($key) && ($value)) {
                   5473: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5474: 	    }
                   5475: 	}
1.662     raeburn  5476:     }
                   5477:     return %personnel;
                   5478: }
1.658     raeburn  5479: 
1.1172.2.89  raeburn  5480: sub get_active_domroles {
                   5481:     my ($dom,$roles) = @_;
                   5482:     return () unless (ref($roles) eq 'ARRAY');
                   5483:     my $now = time;
                   5484:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5485:     my %domroles;
                   5486:     foreach my $server (keys(%dompersonnel)) {
                   5487:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5488:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5489:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5490:         }
                   5491:     }
                   5492:     return %domroles;
                   5493: }
                   5494: 
1.1057    www      5495: # ----------------------------------------------------------- Interval timing 
1.149     www      5496: 
1.1153    www      5497: {
                   5498: # Caches needed for speedup of navmaps
                   5499: # We don't want to cache this for very long at all (5 seconds at most)
                   5500: # 
                   5501: # The user for whom we cache
                   5502: my $cachedkey='';
                   5503: # The cached times for this user
                   5504: my %cachedtimes=();
                   5505: # When this was last done
1.1172.2.66  raeburn  5506: my $cachedtime='';
1.1153    www      5507: 
                   5508: sub load_all_first_access {
1.1172.2.118.  .1(raebu 5509:20):     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5510:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.118.  .1(raebu 5511:20):         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5512:20):         (!$ignorecache)) {
1.1154    raeburn  5513:         return;
                   5514:     }
                   5515:     $cachedtime=time;
                   5516:     $cachedkey=$uname.':'.$udom;
                   5517:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5518: }
                   5519: 
1.504     albertel 5520: sub get_first_access {
1.1172.2.118.  .1(raebu 5521:20):     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5522:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5523:     if ($argsymb) { $symb=$argsymb; }
                   5524:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5525:     if ($argmap) { $map = $argmap; }
1.926     albertel 5526:     if ($type eq 'course') {
                   5527: 	$res='course';
                   5528:     } elsif ($type eq 'map') {
1.588     albertel 5529: 	$res=&symbread($map);
                   5530:     } else {
                   5531: 	$res=$symb;
                   5532:     }
1.1172.2.118.  .1(raebu 5533:20):     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5534:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5535: }
                   5536: 
                   5537: sub set_first_access {
1.1162    raeburn  5538:     my ($type,$interval)=@_;
1.790     albertel 5539:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5540:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5541:     if ($type eq 'course') {
                   5542: 	$res='course';
                   5543:     } elsif ($type eq 'map') {
1.588     albertel 5544: 	$res=&symbread($map);
                   5545:     } else {
                   5546: 	$res=$symb;
                   5547:     }
1.1153    www      5548:     $cachedkey='';
1.1162    raeburn  5549:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5550:     if ($firstaccess) {
                   5551:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5552:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5553:                  "in $courseid");
                   5554:         return 'already_set';
                   5555:     } else {
1.1162    raeburn  5556:         my $start = time;
                   5557: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5558:                           $udom,$uname);
                   5559:         if ($putres eq 'ok') {
                   5560:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5561:                  $udom,$uname); 
                   5562:             &appenv(
                   5563:                      {
                   5564:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5565:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5566:                      }
                   5567:                   );
1.1172.2.97  raeburn  5568:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5569:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5570:             }
1.1172.2.102  raeburn  5571:         } elsif ($putres ne 'refused') {
                   5572:             &logthis("Result: $putres when attempting to set first access time ".
                   5573:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5574:         }
                   5575:         return $putres;
1.505     albertel 5576:     }
                   5577:     return 'already_set';
1.504     albertel 5578: }
1.1153    www      5579: }
1.1172.2.32  raeburn  5580: 
                   5581: sub checkout {
                   5582:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5583:     my $now=time;
                   5584:     my $lonhost=$perlvar{'lonHostID'};
1.1172.2.118.  .14(raeb 5585:-21):     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5586:     my $infostr=&escape(
                   5587:                  'CHECKOUTTOKEN&'.
                   5588:                  $tuname.'&'.
                   5589:                  $tudom.'&'.
                   5590:                  $tcrsid.'&'.
                   5591:                  $symb.'&'.
1.1172.2.118.  .14(raeb 5592:-21):                  $now.'&'.$ip);
1.1172.2.32  raeburn  5593:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5594:     if ($token=~/^error\:/) {
                   5595:         &logthis("<font color=\"blue\">WARNING: ".
                   5596:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5597:                  "</font>");
                   5598:         return '';
                   5599:     }
                   5600: 
                   5601:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5602:     $token=~tr/a-z/A-Z/;
                   5603: 
                   5604:     my %infohash=('resource.0.outtoken' => $token,
                   5605:                   'resource.0.checkouttime' => $now,
1.1172.2.118.  .14(raeb 5606:-21):                   'resource.0.outremote' => $ip);
1.1172.2.32  raeburn  5607: 
                   5608:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5609:        return '';
                   5610:     } else {
                   5611:         &logthis("<font color=\"blue\">WARNING: ".
                   5612:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5613:                  "</font>");
                   5614:     }
                   5615: 
                   5616:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5617:                          &escape('Checkout '.$infostr.' - '.
                   5618:                                                  $token)) ne 'ok') {
                   5619:         return '';
                   5620:     } else {
                   5621:         &logthis("<font color=\"blue\">WARNING: ".
                   5622:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5623:                  "</font>");
                   5624:     }
                   5625:     return $token;
                   5626: }
                   5627: 
                   5628: # ------------------------------------------------------------ Check in an item
                   5629: 
                   5630: sub checkin {
                   5631:     my $token=shift;
                   5632:     my $now=time;
                   5633:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5634:     $lonhost=~tr/A-Z/a-z/;
                   5635:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5636:     $dtoken=~s/\W/\_/g;
1.1172.2.118.  .14(raeb 5637:-21):     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5638:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5639:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5640: 
                   5641:     unless (($tuname) && ($tudom)) {
                   5642:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5643:         return '';
                   5644:     }
                   5645: 
                   5646:     unless (&allowed('mgr',$tcrsid)) {
                   5647:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5648:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5649:         return '';
                   5650:     }
                   5651: 
                   5652:     my %infohash=('resource.0.intoken' => $token,
                   5653:                   'resource.0.checkintime' => $now,
1.1172.2.118.  .14(raeb 5654:-21):                   'resource.0.inremote' => $ip);
1.1172.2.32  raeburn  5655: 
                   5656:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5657:        return '';
                   5658:     }
                   5659: 
                   5660:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5661:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5662:         return '';
                   5663:     }
                   5664: 
                   5665:     return ($symb,$tuname,$tudom,$tcrsid);
                   5666: }
                   5667: 
1.110     www      5668: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5669: 
                   5670: sub expirespread {
                   5671:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5672:     my $cid=$env{'request.course.id'}; 
1.110     www      5673:     if ($cid) {
                   5674:        my $now=time;
                   5675:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5676:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5677:                             $env{'course.'.$cid.'.num'}.
1.110     www      5678: 	        	    ':nohist_expirationdates:'.
                   5679:                             &escape($key).'='.$now,
1.620     albertel 5680:                             $env{'course.'.$cid.'.home'})
1.110     www      5681:     }
                   5682:     return 'ok';
1.14      www      5683: }
                   5684: 
1.109     www      5685: # ----------------------------------------------------- Devalidate Spreadsheets
                   5686: 
                   5687: sub devalidate {
1.325     www      5688:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5689:     my $cid=$env{'request.course.id'}; 
1.109     www      5690:     if ($cid) {
1.391     matthew  5691:         # delete the stored spreadsheets for
                   5692:         # - the student level sheet of this user in course's homespace
                   5693:         # - the assessment level sheet for this resource 
                   5694:         #   for this user in user's homespace
1.553     albertel 5695: 	# - current conditional state info
1.325     www      5696: 	my $key=$uname.':'.$udom.':';
1.109     www      5697:         my $status=
1.299     matthew  5698: 	    &del('nohist_calculatedsheets',
1.391     matthew  5699: 		 [$key.'studentcalc:'],
1.620     albertel 5700: 		 $env{'course.'.$cid.'.domain'},
                   5701: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5702: 		.' '.
                   5703: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5704: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5705:         unless ($status eq 'ok ok') {
                   5706:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5707:                     $uname.' at '.$udom.' for '.
1.109     www      5708: 		    $symb.': '.$status);
1.133     albertel 5709:         }
1.553     albertel 5710: 	&delenv('user.state.'.$cid);
1.109     www      5711:     }
                   5712: }
                   5713: 
1.265     albertel 5714: sub get_scalar {
                   5715:     my ($string,$end) = @_;
                   5716:     my $value;
                   5717:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5718: 	$value = $1;
                   5719:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5720: 	$value = $1;
                   5721:     }
                   5722:     return &unescape($value);
                   5723: }
                   5724: 
                   5725: sub array2str {
                   5726:   my (@array) = @_;
                   5727:   my $result=&arrayref2str(\@array);
                   5728:   $result=~s/^__ARRAY_REF__//;
                   5729:   $result=~s/__END_ARRAY_REF__$//;
                   5730:   return $result;
                   5731: }
                   5732: 
1.204     albertel 5733: sub arrayref2str {
                   5734:   my ($arrayref) = @_;
1.265     albertel 5735:   my $result='__ARRAY_REF__';
1.204     albertel 5736:   foreach my $elem (@$arrayref) {
1.265     albertel 5737:     if(ref($elem) eq 'ARRAY') {
                   5738:       $result.=&arrayref2str($elem).'&';
                   5739:     } elsif(ref($elem) eq 'HASH') {
                   5740:       $result.=&hashref2str($elem).'&';
                   5741:     } elsif(ref($elem)) {
                   5742:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5743:     } else {
                   5744:       $result.=&escape($elem).'&';
                   5745:     }
                   5746:   }
                   5747:   $result=~s/\&$//;
1.265     albertel 5748:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5749:   return $result;
                   5750: }
                   5751: 
1.168     albertel 5752: sub hash2str {
1.204     albertel 5753:   my (%hash) = @_;
                   5754:   my $result=&hashref2str(\%hash);
1.265     albertel 5755:   $result=~s/^__HASH_REF__//;
                   5756:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5757:   return $result;
                   5758: }
                   5759: 
                   5760: sub hashref2str {
                   5761:   my ($hashref)=@_;
1.265     albertel 5762:   my $result='__HASH_REF__';
1.800     albertel 5763:   foreach my $key (sort(keys(%$hashref))) {
                   5764:     if (ref($key) eq 'ARRAY') {
                   5765:       $result.=&arrayref2str($key).'=';
                   5766:     } elsif (ref($key) eq 'HASH') {
                   5767:       $result.=&hashref2str($key).'=';
                   5768:     } elsif (ref($key)) {
1.265     albertel 5769:       $result.='=';
1.800     albertel 5770:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5771:     } else {
1.1132    raeburn  5772: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5773:     }
                   5774: 
1.800     albertel 5775:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5776:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5777:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5778:       $result.=&hashref2str($hashref->{$key}).'&';
                   5779:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5780:        $result.='&';
1.800     albertel 5781:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5782:     } else {
1.800     albertel 5783:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5784:     }
                   5785:   }
1.168     albertel 5786:   $result=~s/\&$//;
1.265     albertel 5787:   $result .= '__END_HASH_REF__';
1.168     albertel 5788:   return $result;
                   5789: }
                   5790: 
                   5791: sub str2hash {
1.265     albertel 5792:     my ($string)=@_;
                   5793:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5794:     return %$hash;
                   5795: }
                   5796: 
                   5797: sub str2hashref {
1.168     albertel 5798:   my ($string) = @_;
1.265     albertel 5799: 
                   5800:   my %hash;
                   5801: 
                   5802:   if($string !~ /^__HASH_REF__/) {
                   5803:       if (! ($string eq '' || !defined($string))) {
                   5804: 	  $hash{'error'}='Not hash reference';
                   5805:       }
                   5806:       return (\%hash, $string);
                   5807:   }
                   5808: 
                   5809:   $string =~ s/^__HASH_REF__//;
                   5810: 
                   5811:   while($string !~ /^__END_HASH_REF__/) {
                   5812:       #key
                   5813:       my $key='';
                   5814:       if($string =~ /^__HASH_REF__/) {
                   5815:           ($key, $string)=&str2hashref($string);
                   5816:           if(defined($key->{'error'})) {
                   5817:               $hash{'error'}='Bad data';
                   5818:               return (\%hash, $string);
                   5819:           }
                   5820:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5821:           ($key, $string)=&str2arrayref($string);
                   5822:           if($key->[0] eq 'Array reference error') {
                   5823:               $hash{'error'}='Bad data';
                   5824:               return (\%hash, $string);
                   5825:           }
                   5826:       } else {
                   5827:           $string =~ s/^(.*?)=//;
1.267     albertel 5828: 	  $key=&unescape($1);
1.265     albertel 5829:       }
                   5830:       $string =~ s/^=//;
                   5831: 
                   5832:       #value
                   5833:       my $value='';
                   5834:       if($string =~ /^__HASH_REF__/) {
                   5835:           ($value, $string)=&str2hashref($string);
                   5836:           if(defined($value->{'error'})) {
                   5837:               $hash{'error'}='Bad data';
                   5838:               return (\%hash, $string);
                   5839:           }
                   5840:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5841:           ($value, $string)=&str2arrayref($string);
                   5842:           if($value->[0] eq 'Array reference error') {
                   5843:               $hash{'error'}='Bad data';
                   5844:               return (\%hash, $string);
                   5845:           }
                   5846:       } else {
                   5847: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5848:       }
                   5849:       $string =~ s/^&//;
                   5850: 
                   5851:       $hash{$key}=$value;
1.204     albertel 5852:   }
1.265     albertel 5853: 
                   5854:   $string =~ s/^__END_HASH_REF__//;
                   5855: 
                   5856:   return (\%hash, $string);
1.204     albertel 5857: }
                   5858: 
                   5859: sub str2array {
1.265     albertel 5860:     my ($string)=@_;
                   5861:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5862:     return @$array;
                   5863: }
                   5864: 
                   5865: sub str2arrayref {
1.204     albertel 5866:   my ($string) = @_;
1.265     albertel 5867:   my @array;
                   5868: 
                   5869:   if($string !~ /^__ARRAY_REF__/) {
                   5870:       if (! ($string eq '' || !defined($string))) {
                   5871: 	  $array[0]='Array reference error';
                   5872:       }
                   5873:       return (\@array, $string);
                   5874:   }
                   5875: 
                   5876:   $string =~ s/^__ARRAY_REF__//;
                   5877: 
                   5878:   while($string !~ /^__END_ARRAY_REF__/) {
                   5879:       my $value='';
                   5880:       if($string =~ /^__HASH_REF__/) {
                   5881:           ($value, $string)=&str2hashref($string);
                   5882:           if(defined($value->{'error'})) {
                   5883:               $array[0] ='Array reference error';
                   5884:               return (\@array, $string);
                   5885:           }
                   5886:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5887:           ($value, $string)=&str2arrayref($string);
                   5888:           if($value->[0] eq 'Array reference error') {
                   5889:               $array[0] ='Array reference error';
                   5890:               return (\@array, $string);
                   5891:           }
                   5892:       } else {
                   5893: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5894:       }
                   5895:       $string =~ s/^&//;
                   5896: 
                   5897:       push(@array, $value);
1.191     harris41 5898:   }
1.265     albertel 5899: 
                   5900:   $string =~ s/^__END_ARRAY_REF__//;
                   5901: 
                   5902:   return (\@array, $string);
1.168     albertel 5903: }
                   5904: 
1.167     albertel 5905: # -------------------------------------------------------------------Temp Store
                   5906: 
1.168     albertel 5907: sub tmpreset {
                   5908:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5909:   if (!$symb) {
                   5910:     $symb=&symbread();
1.620     albertel 5911:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5912:   }
                   5913:   $symb=escape($symb);
                   5914: 
1.620     albertel 5915:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5916:   $namespace=~s/\//\_/g;
                   5917:   $namespace=~s/\W//g;
                   5918: 
1.620     albertel 5919:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5920:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5921:   if ($domain eq 'public' && $stuname eq 'public') {
                   5922:       $stuname=$ENV{'REMOTE_ADDR'};
                   5923:   }
1.1117    foxr     5924:   my $path=LONCAPA::tempdir();
1.168     albertel 5925:   my %hash;
                   5926:   if (tie(%hash,'GDBM_File',
                   5927: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5928: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5929:     foreach my $key (keys(%hash)) {
1.180     albertel 5930:       if ($key=~ /:$symb/) {
1.168     albertel 5931: 	delete($hash{$key});
                   5932:       }
                   5933:     }
                   5934:   }
                   5935: }
                   5936: 
1.167     albertel 5937: sub tmpstore {
1.168     albertel 5938:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5939: 
                   5940:   if (!$symb) {
                   5941:     $symb=&symbread();
1.620     albertel 5942:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5943:   }
                   5944:   $symb=escape($symb);
                   5945: 
                   5946:   if (!$namespace) {
                   5947:     # I don't think we would ever want to store this for a course.
                   5948:     # it seems this will only be used if we don't have a course.
1.620     albertel 5949:     #$namespace=$env{'request.course.id'};
1.168     albertel 5950:     #if (!$namespace) {
1.620     albertel 5951:       $namespace=$env{'request.state'};
1.168     albertel 5952:     #}
                   5953:   }
                   5954:   $namespace=~s/\//\_/g;
                   5955:   $namespace=~s/\W//g;
1.620     albertel 5956:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5957:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5958:   if ($domain eq 'public' && $stuname eq 'public') {
                   5959:       $stuname=$ENV{'REMOTE_ADDR'};
                   5960:   }
1.168     albertel 5961:   my $now=time;
                   5962:   my %hash;
1.1117    foxr     5963:   my $path=LONCAPA::tempdir();
1.168     albertel 5964:   if (tie(%hash,'GDBM_File',
                   5965: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5966: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5967:     $hash{"version:$symb"}++;
                   5968:     my $version=$hash{"version:$symb"};
                   5969:     my $allkeys=''; 
                   5970:     foreach my $key (keys(%$storehash)) {
                   5971:       $allkeys.=$key.':';
1.591     albertel 5972:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5973:     }
                   5974:     $hash{"$version:$symb:timestamp"}=$now;
                   5975:     $allkeys.='timestamp';
                   5976:     $hash{"$version:keys:$symb"}=$allkeys;
                   5977:     if (untie(%hash)) {
                   5978:       return 'ok';
                   5979:     } else {
                   5980:       return "error:$!";
                   5981:     }
                   5982:   } else {
                   5983:     return "error:$!";
                   5984:   }
                   5985: }
1.167     albertel 5986: 
1.168     albertel 5987: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5988: 
1.168     albertel 5989: sub tmprestore {
                   5990:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5991: 
1.168     albertel 5992:   if (!$symb) {
                   5993:     $symb=&symbread();
1.620     albertel 5994:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5995:   }
                   5996:   $symb=escape($symb);
                   5997: 
1.620     albertel 5998:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5999: 
1.620     albertel 6000:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6001:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6002:   if ($domain eq 'public' && $stuname eq 'public') {
                   6003:       $stuname=$ENV{'REMOTE_ADDR'};
                   6004:   }
1.168     albertel 6005:   my %returnhash;
                   6006:   $namespace=~s/\//\_/g;
                   6007:   $namespace=~s/\W//g;
                   6008:   my %hash;
1.1117    foxr     6009:   my $path=LONCAPA::tempdir();
1.168     albertel 6010:   if (tie(%hash,'GDBM_File',
                   6011: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6012: 	  &GDBM_READER(),0640)) {
1.168     albertel 6013:     my $version=$hash{"version:$symb"};
                   6014:     $returnhash{'version'}=$version;
                   6015:     my $scope;
                   6016:     for ($scope=1;$scope<=$version;$scope++) {
                   6017:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6018:       my @keys=split(/:/,$vkeys);
                   6019:       my $key;
                   6020:       $returnhash{"$scope:keys"}=$vkeys;
                   6021:       foreach $key (@keys) {
1.591     albertel 6022: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6023: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6024:       }
                   6025:     }
1.168     albertel 6026:     if (!(untie(%hash))) {
                   6027:       return "error:$!";
                   6028:     }
                   6029:   } else {
                   6030:     return "error:$!";
                   6031:   }
                   6032:   return %returnhash;
1.167     albertel 6033: }
                   6034: 
1.9       www      6035: # ----------------------------------------------------------------------- Store
                   6036: 
                   6037: sub store {
1.1172.2.64  raeburn  6038:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6039:     my $home='';
                   6040: 
1.168     albertel 6041:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6042: 
1.213     www      6043:     $symb=&symbclean($symb);
1.122     albertel 6044:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6045: 
1.620     albertel 6046:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6047:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6048: 
                   6049:     &devalidate($symb,$stuname,$domain);
1.109     www      6050: 
                   6051:     $symb=escape($symb);
1.187     www      6052:     if (!$namespace) { 
1.620     albertel 6053:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6054:           return ''; 
                   6055:        } 
                   6056:     }
1.620     albertel 6057:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6058: 
                   6059:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   6060:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6061: 
1.12      www      6062:     my $namevalue='';
1.800     albertel 6063:     foreach my $key (keys(%$storehash)) {
                   6064:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6065:     }
1.12      www      6066:     $namevalue=~s/\&$//;
1.187     www      6067:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  6068:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6069: }
                   6070: 
1.47      www      6071: # -------------------------------------------------------------- Critical Store
                   6072: 
                   6073: sub cstore {
1.1172.2.64  raeburn  6074:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6075:     my $home='';
                   6076: 
1.168     albertel 6077:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6078: 
1.213     www      6079:     $symb=&symbclean($symb);
1.122     albertel 6080:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6081: 
1.620     albertel 6082:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6083:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6084: 
                   6085:     &devalidate($symb,$stuname,$domain);
1.109     www      6086: 
                   6087:     $symb=escape($symb);
1.187     www      6088:     if (!$namespace) { 
1.620     albertel 6089:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6090:           return ''; 
                   6091:        } 
                   6092:     }
1.620     albertel 6093:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6094: 
                   6095:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   6096:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6097: 
1.47      www      6098:     my $namevalue='';
1.800     albertel 6099:     foreach my $key (keys(%$storehash)) {
                   6100:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6101:     }
1.47      www      6102:     $namevalue=~s/\&$//;
1.187     www      6103:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6104:     return critical
1.1172.2.64  raeburn  6105:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6106: }
                   6107: 
1.9       www      6108: # --------------------------------------------------------------------- Restore
                   6109: 
                   6110: sub restore {
1.124     www      6111:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6112:     my $home='';
                   6113: 
1.168     albertel 6114:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6115: 
1.122     albertel 6116:     if (!$symb) {
1.1172.2.26  raeburn  6117:         return if ($namespace eq 'courserequests');
                   6118:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6119:     } else {
1.1172.2.26  raeburn  6120:         unless ($namespace eq 'courserequests') {
                   6121:             $symb=&escape(&symbclean($symb));
                   6122:         }
1.122     albertel 6123:     }
1.188     www      6124:     if (!$namespace) { 
1.620     albertel 6125:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6126:           return ''; 
                   6127:        } 
                   6128:     }
1.620     albertel 6129:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6130:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6131:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6132:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6133: 
1.12      www      6134:     my %returnhash=();
1.800     albertel 6135:     foreach my $line (split(/\&/,$answer)) {
                   6136: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6137:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6138:     }
1.75      www      6139:     my $version;
                   6140:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6141:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6142:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6143:        }
1.75      www      6144:     }
1.13      www      6145:     return %returnhash;
1.34      www      6146: }
                   6147: 
                   6148: # ---------------------------------------------------------- Course Description
1.1118    foxr     6149: #
                   6150: #  
1.34      www      6151: 
                   6152: sub coursedescription {
1.731     albertel 6153:     my ($courseid,$args)=@_;
1.34      www      6154:     $courseid=~s/^\///;
1.49      www      6155:     $courseid=~s/\_/\//g;
1.34      www      6156:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6157:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6158:     my $normalid=$cdomain.'_'.$cnum;
                   6159:     # need to always cache even if we get errors otherwise we keep 
                   6160:     # trying and trying and trying to get the course description.
                   6161:     my %envhash=();
                   6162:     my %returnhash=();
1.731     albertel 6163:     
                   6164:     my $expiretime=600;
                   6165:     if ($env{'request.course.id'} eq $normalid) {
                   6166: 	$expiretime=120;
                   6167:     }
                   6168: 
                   6169:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6170:     if (!$args->{'freshen_cache'}
                   6171: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6172: 	foreach my $key (keys(%env)) {
                   6173: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6174: 	    my ($setting) = $1;
                   6175: 	    $returnhash{$setting} = $env{$key};
                   6176: 	}
                   6177: 	return %returnhash;
                   6178:     }
                   6179: 
1.1118    foxr     6180:     # get the data again
                   6181: 
1.731     albertel 6182:     if (!$args->{'one_time'}) {
                   6183: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6184:     }
1.811     albertel 6185: 
1.34      www      6186:     if ($chome ne 'no_host') {
1.302     albertel 6187:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6188:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6189: 	   my $username = $env{'user.name'}; # Defult username
                   6190: 	   if(defined $args->{'user'}) {
                   6191: 	       $username = $args->{'user'};
                   6192: 	   }
1.129     albertel 6193:            $returnhash{'home'}= $chome;
                   6194: 	   $returnhash{'domain'} = $cdomain;
                   6195: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6196:            if (!defined($returnhash{'type'})) {
                   6197:                $returnhash{'type'} = 'Course';
                   6198:            }
1.130     albertel 6199:            while (my ($name,$value) = each %returnhash) {
1.53      www      6200:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6201:            }
1.270     www      6202:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6203:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6204: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6205:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6206:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6207:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6208:        }
                   6209:     }
1.731     albertel 6210:     if (!$args->{'one_time'}) {
1.949     raeburn  6211: 	&appenv(\%envhash);
1.731     albertel 6212:     }
1.302     albertel 6213:     return %returnhash;
1.461     www      6214: }
                   6215: 
1.1080    raeburn  6216: sub update_released_required {
                   6217:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6218:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6219:         $cid = $env{'request.course.id'};
                   6220:         $cdom = $env{'course.'.$cid.'.domain'};
                   6221:         $cnum = $env{'course.'.$cid.'.num'};
                   6222:         $chome = $env{'course.'.$cid.'.home'};
                   6223:     }
                   6224:     if ($needsrelease) {
                   6225:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6226:         my $needsupdate;
                   6227:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6228:             $needsupdate = 1;
                   6229:         } else {
                   6230:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6231:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6232:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6233:                 $needsupdate = 1;
                   6234:             }
                   6235:         }
                   6236:         if ($needsupdate) {
                   6237:             my %needshash = (
                   6238:                              'internal.releaserequired' => $needsrelease,
                   6239:                             );
                   6240:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6241:             if ($putresult eq 'ok') {
                   6242:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6243:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6244:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6245:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6246:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6247:                 }
                   6248:             }
                   6249:         }
                   6250:     }
                   6251:     return;
                   6252: }
                   6253: 
1.461     www      6254: # -------------------------------------------------See if a user is privileged
                   6255: 
                   6256: sub privileged {
1.1172.2.23  raeburn  6257:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6258:     my $now = time;
1.1172.2.23  raeburn  6259:     my $roles;
                   6260:     if (ref($possroles) eq 'ARRAY') {
                   6261:         $roles = $possroles;
                   6262:     } else {
                   6263:         $roles = ['dc','su'];
                   6264:     }
                   6265:     if (ref($possdomains) eq 'ARRAY') {
                   6266:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6267:         foreach my $dom (@{$possdomains}) {
                   6268:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6269:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6270:                 foreach my $role (@{$roles}) {
                   6271:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6272:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6273:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6274:                             return 1 unless (($end && $end < $now) ||
                   6275:                                              ($start && $start > $now));
                   6276:                         }
                   6277:                     }
                   6278:                 }
                   6279:             }
                   6280:         }
                   6281:     } else {
                   6282:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6283:         my $now = time;
1.1170    droeschl 6284: 
1.1172.2.58  raeburn  6285:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6286:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6287:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6288:                 return 1 unless ($tend && $tend < $now)
                   6289:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6290:             }
1.1172.2.23  raeburn  6291:         }
                   6292:     }
1.461     www      6293:     return 0;
1.9       www      6294: }
1.1       albertel 6295: 
1.1172.2.23  raeburn  6296: sub privileged_by_domain {
                   6297:     my ($domains,$roles) = @_;
                   6298:     my %privileged = ();
                   6299:     my $cachetime = 60*60*24;
                   6300:     my $now = time;
                   6301:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6302:         return %privileged;
                   6303:     }
                   6304:     foreach my $dom (@{$domains}) {
                   6305:         next if (ref($privileged{$dom}) eq 'HASH');
                   6306:         my $needroles;
                   6307:         foreach my $role (@{$roles}) {
                   6308:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6309:             if (defined($cached)) {
                   6310:                 if (ref($result) eq 'HASH') {
                   6311:                     $privileged{$dom}{$role} = $result;
                   6312:                 }
                   6313:             } else {
                   6314:                 $needroles = 1;
                   6315:             }
                   6316:         }
                   6317:         if ($needroles) {
                   6318:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6319:             $privileged{$dom} = {};
                   6320:             foreach my $server (keys(%dompersonnel)) {
                   6321:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6322:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6323:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6324:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6325:                         next if ($end && $end < $now);
                   6326:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6327:                             $dompersonnel{$server}{$item};
                   6328:                     }
                   6329:                 }
                   6330:             }
                   6331:             if (ref($privileged{$dom}) eq 'HASH') {
                   6332:                 foreach my $role (@{$roles}) {
                   6333:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6334:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6335:                     } else {
                   6336:                         my %hash = ();
                   6337:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6338:                     }
                   6339:                 }
                   6340:             }
                   6341:         }
                   6342:     }
                   6343:     return %privileged;
                   6344: }
                   6345: 
1.103     harris41 6346: # -------------------------------------------------------- Get user privileges
1.11      www      6347: 
                   6348: sub rolesinit {
1.1169    droeschl 6349:     my ($domain, $username) = @_;
                   6350:     my %userroles = ('user.login.time' => time);
                   6351:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6352: 
                   6353:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6354:     # also, blocking can be triggered by an activating timer
                   6355:     # it's saved in the user's %env.
                   6356:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6357:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6358:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6359:         %timerintchk, %timerintenv);
                   6360: 
1.1162    raeburn  6361:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6362:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6363:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6364:     }
1.1169    droeschl 6365: 
1.1162    raeburn  6366:     foreach my $key (keys(%timerinterval)) {
                   6367:         my ($cid,$rest) = split(/\0/,$key);
                   6368:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6369:     }
1.1169    droeschl 6370: 
1.11      www      6371:     my %allroles=();
1.1162    raeburn  6372:     my %allgroups=();
1.11      www      6373: 
1.1172.2.58  raeburn  6374:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6375:         my $role = $rolesdump{$area};
                   6376:         $area =~ s/\_\w\w$//;
                   6377: 
                   6378:         my ($trole, $tend, $tstart, $group_privs);
                   6379: 
                   6380:         if ($role =~ /^cr/) {
                   6381:         # Custom role, defined by a user 
                   6382:         # e.g., user.role.cr/msu/smith/mynewrole
                   6383:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6384:                 $trole = $1;
                   6385:                 ($tend, $tstart) = split('_', $2);
                   6386:             } else {
                   6387:                 $trole = $role;
                   6388:             }
                   6389:         } elsif ($role =~ m|^gr/|) {
                   6390:         # Role of member in a group, defined within a course/community
                   6391:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6392:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6393:             next if $tstart eq '-1';
                   6394:             ($trole, $group_privs) = split(/\//, $trole);
                   6395:             $group_privs = &unescape($group_privs);
                   6396:         } else {
                   6397:         # Just a normal role, defined in roles.tab
                   6398:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6399:         }
                   6400: 
                   6401:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6402:                  $username);
                   6403:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6404: 
                   6405:         # role expired or not available yet?
                   6406:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6407:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6408: 
                   6409:         next if $area eq '' or $trole eq '';
                   6410: 
                   6411:         my $spec = "$trole.$area";
                   6412:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6413: 
                   6414:         if ($trole =~ /^cr\//) {
                   6415:         # Custom role, defined by a user
                   6416:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6417:         } elsif ($trole eq 'gr') {
                   6418:         # Role of a member in a group, defined within a course/community
                   6419:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6420:             next;
                   6421:         } else {
                   6422:         # Normal role, defined in roles.tab
                   6423:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6424:         }
                   6425: 
                   6426:         my $cid = $tdomain.'_'.$trest;
                   6427:         unless ($firstaccchk{$cid}) {
                   6428:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6429:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6430:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6431:                         $coursetimerstarts{$cid}{$item}; 
                   6432:                 }
                   6433:             }
                   6434:             $firstaccchk{$cid} = 1;
                   6435:         }
                   6436:         unless ($timerintchk{$cid}) {
                   6437:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6438:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6439:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6440:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6441:                 }
1.12      www      6442:             }
1.1169    droeschl 6443:             $timerintchk{$cid} = 1;
1.191     harris41 6444:         }
1.11      www      6445:     }
1.1169    droeschl 6446: 
1.1172.2.91  raeburn  6447:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6448:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6449:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6450:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6451: 
1.1162    raeburn  6452:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6453: }
                   6454: 
1.567     raeburn  6455: sub set_arearole {
1.1172.2.19  raeburn  6456:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6457:     unless ($nolog) {
1.567     raeburn  6458: # log the associated role with the area
1.1172.2.19  raeburn  6459:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6460:     }
1.743     albertel 6461:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6462: }
                   6463: 
                   6464: sub custom_roleprivs {
                   6465:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6466:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6467:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6468:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6469:         my ($rdummy,$roledef)=
                   6470:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6471:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6472:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6473:             if (defined($syspriv)) {
1.1043    raeburn  6474:                 if ($trest =~ /^$match_community$/) {
                   6475:                     $syspriv =~ s/bre\&S//; 
                   6476:                 }
1.567     raeburn  6477:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6478:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6479:             }
                   6480:             if ($tdomain ne '') {
                   6481:                 if (defined($dompriv)) {
                   6482:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6483:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6484:                 }
                   6485:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6486:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6487:                         my $rolename = $1;
                   6488:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6489:                     }
1.567     raeburn  6490:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6491:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6492:                 }
                   6493:             }
                   6494:         }
                   6495:     }
                   6496: }
                   6497: 
1.1172.2.89  raeburn  6498: sub course_adhocrole_privs {
                   6499:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6500:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6501:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6502:         my (%currprivs,%storeprivs);
                   6503:         foreach my $item (split(/:/,$coursepriv)) {
                   6504:             my ($priv,$restrict) = split(/\&/,$item);
                   6505:             $currprivs{$priv} = $restrict;
                   6506:         }
                   6507:         my (%possadd,%possremove,%full);
                   6508:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6509:             my ($priv,$restrict)=split(/\&/,$item);
                   6510:             $full{$priv} = $restrict;
                   6511:         }
                   6512:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6513:              next if ($item eq '');
                   6514:              my ($rule,$rest) = split(/=/,$item);
                   6515:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6516:              foreach my $priv (split(/:/,$rest)) {
                   6517:                  if ($priv ne '') {
                   6518:                      if ($rule eq 'off') {
                   6519:                          $possremove{$priv} = 1;
                   6520:                      } else {
                   6521:                          $possadd{$priv} = 1;
                   6522:                      }
                   6523:                  }
                   6524:              }
                   6525:          }
                   6526:          foreach my $priv (sort(keys(%full))) {
                   6527:              if (exists($currprivs{$priv})) {
                   6528:                  unless (exists($possremove{$priv})) {
                   6529:                      $storeprivs{$priv} = $currprivs{$priv};
                   6530:                  }
                   6531:              } elsif (exists($possadd{$priv})) {
                   6532:                  $storeprivs{$priv} = $full{$priv};
                   6533:              }
                   6534:          }
                   6535:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6536:      }
                   6537:      return $coursepriv;
                   6538: }
                   6539: 
1.678     raeburn  6540: sub group_roleprivs {
                   6541:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6542:     my $access = 1;
                   6543:     my $now = time;
                   6544:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6545:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6546:     if ($access) {
1.811     albertel 6547:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6548:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6549:     }
                   6550: }
1.567     raeburn  6551: 
                   6552: sub standard_roleprivs {
                   6553:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6554:     if (defined($pr{$trole.':s'})) {
                   6555:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6556:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6557:     }
                   6558:     if ($tdomain ne '') {
                   6559:         if (defined($pr{$trole.':d'})) {
                   6560:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6561:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6562:         }
                   6563:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6564:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6565:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6566:         }
                   6567:     }
                   6568: }
                   6569: 
                   6570: sub set_userprivs {
1.1064    raeburn  6571:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6572:     my $author=0;
                   6573:     my $adv=0;
1.1172.2.91  raeburn  6574:     my $rar=0;
1.678     raeburn  6575:     my %grouproles = ();
                   6576:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6577:         my @groupkeys; 
1.1000    raeburn  6578:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6579:             push(@groupkeys,$role);
                   6580:         }
                   6581:         if (ref($groups_roles) eq 'HASH') {
                   6582:             foreach my $key (keys(%{$groups_roles})) {
                   6583:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6584:                     push(@groupkeys,$key);
                   6585:                 }
                   6586:             }
                   6587:         }
                   6588:         if (@groupkeys > 0) {
                   6589:             foreach my $role (@groupkeys) {
                   6590:                 my ($trole,$area,$sec,$extendedarea);
                   6591:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6592:                     $trole = $1;
                   6593:                     $area = $2;
                   6594:                     $sec = $3;
                   6595:                     $extendedarea = $area.$sec;
                   6596:                     if (exists($$allgroups{$area})) {
                   6597:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6598:                             my $spec = $trole.'.'.$extendedarea;
                   6599:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6600:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6601:                         }
1.678     raeburn  6602:                     }
                   6603:                 }
                   6604:             }
                   6605:         }
                   6606:     }
1.800     albertel 6607:     foreach my $group (keys(%grouproles)) {
                   6608:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6609:     }
1.800     albertel 6610:     foreach my $role (keys(%{$allroles})) {
                   6611:         my %thesepriv;
1.941     raeburn  6612:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6613:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6614:             if ($item ne '') {
                   6615:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6616:                 if ($restrictions eq '') {
                   6617:                     $thesepriv{$privilege}='F';
                   6618:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6619:                     $thesepriv{$privilege}.=$restrictions;
                   6620:                 }
                   6621:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6622:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6623:             }
                   6624:         }
                   6625:         my $thesestr='';
1.1104    raeburn  6626:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6627: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6628: 	}
                   6629:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6630:     }
1.1172.2.91  raeburn  6631:     return ($author,$adv,$rar);
1.567     raeburn  6632: }
                   6633: 
1.994     raeburn  6634: sub role_status {
1.1104    raeburn  6635:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6636:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6637:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6638:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6639:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6640:             $$where = '/'.$two;
1.994     raeburn  6641:             $$trolecode=$$role.'.'.$$where;
                   6642:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6643:             $$tstatus='is';
1.1104    raeburn  6644:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6645:                 $$tstatus='future';
1.1034    raeburn  6646:                 if ($$tstart<$now) {
                   6647:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6648:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6649:                             my (%allroles,%allgroups,$group_privs,
                   6650:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6651:                             my %userroles = (
                   6652:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6653:                             );
1.1064    raeburn  6654:                             @rolecodes = ('cm'); 
1.1002    raeburn  6655:                             my $spec=$$role.'.'.$$where;
                   6656:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6657:                             if ($$role =~ /^cr\//) {
                   6658:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6659:                                 push(@rolecodes,'cr');
1.1002    raeburn  6660:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6661:                                 push(@rolecodes,$$role);
1.1002    raeburn  6662:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6663:                                                     $env{'user.name'});
1.1064    raeburn  6664:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6665:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6666:                                 $group_privs = &unescape($group_privs);
                   6667:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6668:                                 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  6669:                                 &get_groups_roles($tdomain,$trest,
                   6670:                                                   \%course_roles,\@rolecodes,
                   6671:                                                   \%groups_roles);
1.1002    raeburn  6672:                             } else {
1.1064    raeburn  6673:                                 push(@rolecodes,$$role);
1.1002    raeburn  6674:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6675:                             }
1.1172.2.91  raeburn  6676:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6677:                                                                    \%groups_roles);
1.1064    raeburn  6678:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6679:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6680:                         }
                   6681:                     }
1.1034    raeburn  6682:                     $$tstatus = 'is';
1.1002    raeburn  6683:                 }
1.994     raeburn  6684:             }
                   6685:             if ($$tend) {
1.1104    raeburn  6686:                 if ($$tend<$update) {
1.994     raeburn  6687:                     $$tstatus='expired';
                   6688:                 } elsif ($$tend<$now) {
                   6689:                     $$tstatus='will_not';
                   6690:                 }
                   6691:             }
                   6692:         }
                   6693:     }
                   6694: }
                   6695: 
1.1104    raeburn  6696: sub get_groups_roles {
                   6697:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6698:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6699:                   (ref($rolecodes) eq 'ARRAY') && 
                   6700:                   (ref($groups_roles) eq 'HASH')); 
                   6701:     if (keys(%{$cdom_courseroles}) > 0) {
                   6702:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6703:         if ($cdom ne '' && $cnum ne '') {
                   6704:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6705:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6706:                     my $crsrole = $1;
                   6707:                     my $crssec = $2;
                   6708:                     if ($crsrole =~ /^cr/) {
                   6709:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6710:                             push(@{$rolecodes},'cr');
                   6711:                         }
                   6712:                     } else {
                   6713:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6714:                             push(@{$rolecodes},$crsrole);
                   6715:                         }
                   6716:                     }
                   6717:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6718:                     if ($crssec ne '') {
                   6719:                         $rolekey .= "/$crssec";
                   6720:                     }
                   6721:                     $rolekey .= './';
                   6722:                     $groups_roles->{$rolekey} = $rolecodes;
                   6723:                 }
                   6724:             }
                   6725:         }
                   6726:     }
                   6727:     return;
                   6728: }
                   6729: 
                   6730: sub delete_env_groupprivs {
                   6731:     my ($where,$courseroles,$possroles) = @_;
                   6732:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6733:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6734:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6735:         %{$courseroles->{$udom}} =
                   6736:             &get_my_roles('','','userroles',['active'],
                   6737:                           $possroles,[$udom],1);
                   6738:     }
                   6739:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6740:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6741:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6742:             my $area = '/'.$cdom.'/'.$cnum;
                   6743:             my $privkey = "user.priv.$crsrole.$area";
                   6744:             if ($crssec ne '') {
                   6745:                 $privkey .= '/'.$crssec;
                   6746:             }
                   6747:             $privkey .= ".$area/$group";
                   6748:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6749:         }
                   6750:     }
                   6751:     return;
                   6752: }
                   6753: 
1.994     raeburn  6754: sub check_adhoc_privs {
1.1172.2.86  raeburn  6755:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6756:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6757:     if ($sec) {
                   6758:         $cckey .= '/'.$sec;
                   6759:     }
1.1172.2.9  raeburn  6760:     my $setprivs;
1.994     raeburn  6761:     if ($env{$cckey}) {
                   6762:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6763:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6764:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6765:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6766:             $setprivs = 1;
1.994     raeburn  6767:         }
                   6768:     } else {
1.1172.2.87  raeburn  6769:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6770:         $setprivs = 1;
1.994     raeburn  6771:     }
1.1172.2.9  raeburn  6772:     return $setprivs;
1.994     raeburn  6773: }
                   6774: 
                   6775: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6776: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6777:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6778:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6779:     if ($sec ne '') {
                   6780:         $area .= '/'.$sec;
                   6781:     }
1.994     raeburn  6782:     my $spec = $role.'.'.$area;
                   6783:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6784:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6785:     my %rolehash = ();
1.1172.2.89  raeburn  6786:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6787:         my $rolename = $1;
1.1172.2.84  raeburn  6788:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6789:         my %domdef = &get_domain_defaults($dcdom);
                   6790:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6791:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6792:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6793:             }
                   6794:         }
1.1172.2.84  raeburn  6795:     } else {
                   6796:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6797:     }
1.1172.2.91  raeburn  6798:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6799:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6800:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6801:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6802:         &appenv( {'request.role'        => $spec,
                   6803:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6804:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6805:                  }
                   6806:                );
                   6807:         my $tadv=0;
                   6808:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6809:         &appenv({'request.role.adv'    => $tadv});
                   6810:     }
1.994     raeburn  6811: }
                   6812: 
1.12      www      6813: # --------------------------------------------------------------- get interface
                   6814: 
                   6815: sub get {
1.131     albertel 6816:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6817:    my $items='';
1.800     albertel 6818:    foreach my $item (@$storearr) {
                   6819:        $items.=&escape($item).'&';
1.191     harris41 6820:    }
1.12      www      6821:    $items=~s/\&$//;
1.620     albertel 6822:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6823:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6824:    my $uhome=&homeserver($uname,$udomain);
                   6825: 
1.133     albertel 6826:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6827:    my @pairs=split(/\&/,$rep);
1.273     albertel 6828:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6829:      return @pairs;
                   6830:    }
1.15      www      6831:    my %returnhash=();
1.42      www      6832:    my $i=0;
1.800     albertel 6833:    foreach my $item (@$storearr) {
                   6834:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6835:       $i++;
1.191     harris41 6836:    }
1.15      www      6837:    return %returnhash;
1.27      www      6838: }
                   6839: 
                   6840: # --------------------------------------------------------------- del interface
                   6841: 
                   6842: sub del {
1.133     albertel 6843:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6844:    my $items='';
1.800     albertel 6845:    foreach my $item (@$storearr) {
                   6846:        $items.=&escape($item).'&';
1.191     harris41 6847:    }
1.984     neumanie 6848: 
1.27      www      6849:    $items=~s/\&$//;
1.620     albertel 6850:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6851:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6852:    my $uhome=&homeserver($uname,$udomain);
                   6853:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6854: }
                   6855: 
                   6856: # -------------------------------------------------------------- dump interface
                   6857: 
1.1172.2.22  raeburn  6858: sub unserialize {
                   6859:     my ($rep, $escapedkeys) = @_;
                   6860: 
                   6861:     return {} if $rep =~ /^error/;
                   6862: 
                   6863:     my %returnhash=();
                   6864:     foreach my $item (split(/\&/,$rep)) {
                   6865:         my ($key, $value) = split(/=/, $item, 2);
                   6866:         $key = unescape($key) unless $escapedkeys;
                   6867:         next if $key =~ /^error: 2 /;
                   6868:         $returnhash{$key} = &thaw_unescape($value);
                   6869:     }
                   6870:     return \%returnhash;
                   6871: }
                   6872: 
                   6873: # see Lond::dump_with_regexp
                   6874: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6875: sub dump {
1.1172.2.22  raeburn  6876:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6877:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6878:     if (!$uname) { $uname=$env{'user.name'}; }
                   6879:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6880: 
1.1172.2.55  raeburn  6881:     if ($regexp) {
                   6882:         $regexp=&escape($regexp);
                   6883:     } else {
                   6884:         $regexp='.';
                   6885:     }
1.1172.2.22  raeburn  6886:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6887:         # user is hosted on this machine
1.1172.2.55  raeburn  6888:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6889:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6890:         return %{&unserialize($reply, $escapedkeys)};
                   6891:     }
1.1166    raeburn  6892:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6893:     my @pairs=split(/\&/,$rep);
                   6894:     my %returnhash=();
1.1098    foxr     6895:     if (!($rep =~ /^error/ )) {
                   6896: 	foreach my $item (@pairs) {
                   6897: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6898:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6899: 	    next if ($key =~ /^error: 2 /);
                   6900: 	    $returnhash{$key}=&thaw_unescape($value);
                   6901: 	}
1.755     albertel 6902:     }
                   6903:     return %returnhash;
1.407     www      6904: }
                   6905: 
1.1098    foxr     6906: 
1.717     albertel 6907: # --------------------------------------------------------- dumpstore interface
                   6908: 
                   6909: sub dumpstore {
                   6910:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6911:    # same as dump but keys must be escaped. They may contain colon separated
                   6912:    # lists of values that may themself contain colons (e.g. symbs).
                   6913:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6914: }
                   6915: 
1.407     www      6916: # -------------------------------------------------------------- keys interface
                   6917: 
                   6918: sub getkeys {
                   6919:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6920:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6921:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6922:    my $uhome=&homeserver($uname,$udomain);
                   6923:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6924:    my @keyarray=();
1.800     albertel 6925:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6926:       next if ($key =~ /^error: 2 /);
1.800     albertel 6927:       push(@keyarray,&unescape($key));
1.407     www      6928:    }
                   6929:    return @keyarray;
1.318     matthew  6930: }
                   6931: 
1.319     matthew  6932: # --------------------------------------------------------------- currentdump
                   6933: sub currentdump {
1.328     matthew  6934:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6935:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6936:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6937:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6938:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  6939:    my $rep;
                   6940: 
                   6941:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6942:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   6943:                    $courseid)));
                   6944:    } else {
                   6945:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6946:    }
                   6947: 
1.318     matthew  6948:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6949:    #
1.318     matthew  6950:    my %returnhash=();
1.319     matthew  6951:    #
1.1172.2.118.  .1(raebu 6952:20):    if ($rep eq 'unknown_cmd') {
1.319     matthew  6953:        # an old lond will not know currentdump
                   6954:        # Do a dump and make it look like a currentdump
1.822     albertel 6955:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6956:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6957:        my %hash = @tmp;
                   6958:        @tmp=();
1.424     matthew  6959:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6960:    } else {
                   6961:        my @pairs=split(/\&/,$rep);
1.800     albertel 6962:        foreach my $pair (@pairs) {
                   6963:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6964:            my ($symb,$param) = split(/:/,$key);
                   6965:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6966:                                                         &thaw_unescape($value);
1.319     matthew  6967:        }
1.191     harris41 6968:    }
1.12      www      6969:    return %returnhash;
1.424     matthew  6970: }
                   6971: 
                   6972: sub convert_dump_to_currentdump{
                   6973:     my %hash = %{shift()};
                   6974:     my %returnhash;
                   6975:     # Code ripped from lond, essentially.  The only difference
                   6976:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6977:     # we might run in to problems with parameter names =~ /^v\./
                   6978:     while (my ($key,$value) = each(%hash)) {
                   6979:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6980: 	$symb  = &unescape($symb);
                   6981: 	$param = &unescape($param);
1.424     matthew  6982:         next if ($v eq 'version' || $symb eq 'keys');
                   6983:         next if (exists($returnhash{$symb}) &&
                   6984:                  exists($returnhash{$symb}->{$param}) &&
                   6985:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6986:         $returnhash{$symb}->{$param}=$value;
                   6987:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6988:     }
                   6989:     #
                   6990:     # Remove all of the keys in the hashes which keep track of
                   6991:     # the version of the parameter.
                   6992:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6993:         # use a foreach because we are going to delete from the hash.
                   6994:         foreach my $key (keys(%$param_hash)) {
                   6995:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6996:         }
                   6997:     }
                   6998:     return \%returnhash;
1.12      www      6999: }
                   7000: 
1.627     albertel 7001: # ------------------------------------------------------ critical inc interface
                   7002: 
                   7003: sub cinc {
                   7004:     return &inc(@_,'critical');
                   7005: }
                   7006: 
1.449     matthew  7007: # --------------------------------------------------------------- inc interface
                   7008: 
                   7009: sub inc {
1.627     albertel 7010:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7011:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7012:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7013:     my $uhome=&homeserver($uname,$udomain);
                   7014:     my $items='';
                   7015:     if (! ref($store)) {
                   7016:         # got a single value, so use that instead
                   7017:         $items = &escape($store).'=&';
                   7018:     } elsif (ref($store) eq 'SCALAR') {
                   7019:         $items = &escape($$store).'=&';        
                   7020:     } elsif (ref($store) eq 'ARRAY') {
                   7021:         $items = join('=&',map {&escape($_);} @{$store});
                   7022:     } elsif (ref($store) eq 'HASH') {
                   7023:         while (my($key,$value) = each(%{$store})) {
                   7024:             $items.= &escape($key).'='.&escape($value).'&';
                   7025:         }
                   7026:     }
                   7027:     $items=~s/\&$//;
1.627     albertel 7028:     if ($critical) {
                   7029: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7030:     } else {
                   7031: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7032:     }
1.449     matthew  7033: }
                   7034: 
1.12      www      7035: # --------------------------------------------------------------- put interface
                   7036: 
                   7037: sub put {
1.134     albertel 7038:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7039:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7040:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7041:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7042:    my $items='';
1.800     albertel 7043:    foreach my $item (keys(%$storehash)) {
                   7044:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7045:    }
1.12      www      7046:    $items=~s/\&$//;
1.134     albertel 7047:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      7048: }
                   7049: 
1.631     albertel 7050: # ------------------------------------------------------------ newput interface
                   7051: 
                   7052: sub newput {
                   7053:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7054:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7055:    if (!$uname) { $uname=$env{'user.name'}; }
                   7056:    my $uhome=&homeserver($uname,$udomain);
                   7057:    my $items='';
                   7058:    foreach my $key (keys(%$storehash)) {
                   7059:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7060:    }
                   7061:    $items=~s/\&$//;
                   7062:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7063: }
                   7064: 
                   7065: # ---------------------------------------------------------  putstore interface
                   7066: 
1.524     raeburn  7067: sub putstore {
1.1172.2.59  raeburn  7068:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7069:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7070:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7071:    my $uhome=&homeserver($uname,$udomain);
                   7072:    my $items='';
1.715     albertel 7073:    foreach my $key (keys(%$storehash)) {
                   7074:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7075:    }
1.715     albertel 7076:    $items=~s/\&$//;
1.716     albertel 7077:    my $esc_symb=&escape($symb);
                   7078:    my $esc_v=&escape($version);
1.715     albertel 7079:    my $reply =
1.716     albertel 7080:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7081: 	      $uhome);
1.1172.2.59  raeburn  7082:    if (($tolog) && ($reply eq 'ok')) {
                   7083:        my $namevalue='';
                   7084:        foreach my $key (keys(%{$storehash})) {
                   7085:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7086:        }
1.1172.2.118.  .14(raeb 7087:-21):        my $ip = &get_requestor_ip();
                   7088:-21):        $namevalue .= 'ip='.&escape($ip).
1.1172.2.59  raeburn  7089:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7090:                      '&version='.$esc_v.
                   7091:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7092:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7093:    }
1.715     albertel 7094:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7095:        # gfall back to way things use to be done
1.715     albertel 7096:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7097: 			    $uname);
1.524     raeburn  7098:    }
1.715     albertel 7099:    return $reply;
                   7100: }
                   7101: 
                   7102: sub old_putstore {
1.716     albertel 7103:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7104:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7105:     if (!$uname) { $uname=$env{'user.name'}; }
                   7106:     my $uhome=&homeserver($uname,$udomain);
                   7107:     my %newstorehash;
1.800     albertel 7108:     foreach my $item (keys(%$storehash)) {
                   7109: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7110: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7111:     }
                   7112:     my $items='';
                   7113:     my %allitems = ();
1.800     albertel 7114:     foreach my $item (keys(%newstorehash)) {
                   7115: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7116: 	    my $key = $1.':keys:'.$2;
                   7117: 	    $allitems{$key} .= $3.':';
                   7118: 	}
1.800     albertel 7119: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7120:     }
1.800     albertel 7121:     foreach my $item (keys(%allitems)) {
                   7122: 	$allitems{$item} =~ s/\:$//;
                   7123: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7124:     }
                   7125:     $items=~s/\&$//;
                   7126:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7127: }
                   7128: 
1.47      www      7129: # ------------------------------------------------------ critical put interface
                   7130: 
                   7131: sub cput {
1.134     albertel 7132:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7133:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7134:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7135:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7136:    my $items='';
1.800     albertel 7137:    foreach my $item (keys(%$storehash)) {
                   7138:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7139:    }
1.47      www      7140:    $items=~s/\&$//;
1.134     albertel 7141:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7142: }
                   7143: 
                   7144: # -------------------------------------------------------------- eget interface
                   7145: 
                   7146: sub eget {
1.133     albertel 7147:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7148:    my $items='';
1.800     albertel 7149:    foreach my $item (@$storearr) {
                   7150:        $items.=&escape($item).'&';
1.191     harris41 7151:    }
1.12      www      7152:    $items=~s/\&$//;
1.620     albertel 7153:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7154:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7155:    my $uhome=&homeserver($uname,$udomain);
                   7156:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7157:    my @pairs=split(/\&/,$rep);
                   7158:    my %returnhash=();
1.42      www      7159:    my $i=0;
1.800     albertel 7160:    foreach my $item (@$storearr) {
                   7161:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7162:       $i++;
1.191     harris41 7163:    }
1.12      www      7164:    return %returnhash;
                   7165: }
                   7166: 
1.667     albertel 7167: # ------------------------------------------------------------ tmpput interface
                   7168: sub tmpput {
1.802     raeburn  7169:     my ($storehash,$server,$context)=@_;
1.667     albertel 7170:     my $items='';
1.800     albertel 7171:     foreach my $item (keys(%$storehash)) {
                   7172: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7173:     }
                   7174:     $items=~s/\&$//;
1.802     raeburn  7175:     if (defined($context)) {
                   7176:         $items .= ':'.&escape($context);
                   7177:     }
1.667     albertel 7178:     return &reply("tmpput:$items",$server);
                   7179: }
                   7180: 
                   7181: # ------------------------------------------------------------ tmpget interface
                   7182: sub tmpget {
1.688     albertel 7183:     my ($token,$server)=@_;
                   7184:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7185:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7186:     my %returnhash;
1.1172.2.85  raeburn  7187:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7188:         return %returnhash;
                   7189:     }
1.667     albertel 7190:     foreach my $item (split(/\&/,$rep)) {
                   7191: 	my ($key,$value)=split(/=/,$item);
                   7192: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7193:     }
                   7194:     return %returnhash;
                   7195: }
                   7196: 
1.1113    raeburn  7197: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7198: sub tmpdel {
                   7199:     my ($token,$server)=@_;
                   7200:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7201:     return &reply("tmpdel:$token",$server);
                   7202: }
                   7203: 
1.1172.2.13  raeburn  7204: # ------------------------------------------------------------ get_timebased_id
                   7205: 
                   7206: sub get_timebased_id {
                   7207:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7208:         $maxtries) = @_;
                   7209:     my ($newid,$error,$dellock);
                   7210:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7211:         return ('','ok','invalid call to get suffix');
                   7212:     }
                   7213: 
                   7214: # set defaults for any optional args for which values were not supplied
                   7215:     if ($who eq '') {
                   7216:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7217:     }
                   7218:     if (!$locktries) {
                   7219:         $locktries = 3;
                   7220:     }
                   7221:     if (!$maxtries) {
                   7222:         $maxtries = 10;
                   7223:     }
                   7224: 
                   7225:     if (($cdom eq '') || ($cnum eq '')) {
                   7226:         if ($env{'request.course.id'}) {
                   7227:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7228:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7229:         }
                   7230:         if (($cdom eq '') || ($cnum eq '')) {
                   7231:             return ('','ok','call to get suffix not in course context');
                   7232:         }
                   7233:     }
                   7234: 
                   7235: # construct locking item
                   7236:     my $lockhash = {
                   7237:                       $prefix."\0".'locked_'.$keyid => $who,
                   7238:                    };
                   7239:     my $tries = 0;
                   7240: 
                   7241: # attempt to get lock on nohist_$namespace file
                   7242:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7243:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7244:         $tries ++;
                   7245:         sleep 1;
                   7246:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7247:     }
                   7248: 
                   7249: # attempt to get unique identifier, based on current timestamp
                   7250:     if ($gotlock eq 'ok') {
                   7251:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7252:         my $id = time;
                   7253:         $newid = $id;
1.1172.2.56  raeburn  7254:         if ($idtype eq 'addcode') {
                   7255:             $newid .= &sixnum_code();
                   7256:         }
1.1172.2.13  raeburn  7257:         my $idtries = 0;
                   7258:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7259:             if ($idtype eq 'concat') {
                   7260:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7261:             } elsif ($idtype eq 'addcode') {
                   7262:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7263:             } else {
                   7264:                 $newid ++;
                   7265:             }
                   7266:             $idtries ++;
                   7267:         }
                   7268:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7269:             my %new_item =  (
                   7270:                               $prefix."\0".$newid => $who,
                   7271:                             );
                   7272:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7273:                                                  $cdom,$cnum);
                   7274:             if ($putresult ne 'ok') {
                   7275:                 undef($newid);
                   7276:                 $error = 'error saving new item: '.$putresult;
                   7277:             }
                   7278:         } else {
1.1172.2.56  raeburn  7279:              undef($newid);
1.1172.2.13  raeburn  7280:              $error = ('error: no unique suffix available for the new item ');
                   7281:         }
                   7282: #  remove lock
                   7283:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7284:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7285:     } else {
                   7286:         $error = "error: could not obtain lockfile\n";
                   7287:         $dellock = 'ok';
1.1172.2.58  raeburn  7288:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7289:             $dellock = 'nolock';
                   7290:         }
1.1172.2.13  raeburn  7291:     }
                   7292:     return ($newid,$dellock,$error);
                   7293: }
                   7294: 
1.1172.2.56  raeburn  7295: sub sixnum_code {
                   7296:     my $code;
                   7297:     for (0..6) {
                   7298:         $code .= int( rand(9) );
                   7299:     }
                   7300:     return $code;
                   7301: }
                   7302: 
1.765     albertel 7303: # -------------------------------------------------- portfolio access checking
                   7304: 
                   7305: sub portfolio_access {
1.1172.2.77  raeburn  7306:     my ($requrl,$clientip) = @_;
1.765     albertel 7307:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7308:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7309:     if ($result) {
                   7310:         my %setters;
                   7311:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7312:             my ($startblock,$endblock) =
                   7313:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   7314:             if ($startblock && $endblock) {
                   7315:                 return 'B';
                   7316:             }
                   7317:         } else {
                   7318:             my ($startblock,$endblock) =
                   7319:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   7320:             if ($startblock && $endblock) {
                   7321:                 return 'B';
                   7322:             }
                   7323:         }
                   7324:     }
1.765     albertel 7325:     if ($result eq 'ok') {
1.766     albertel 7326:        return 'F';
1.765     albertel 7327:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7328:        return 'A';
1.765     albertel 7329:     }
1.766     albertel 7330:     return '';
1.765     albertel 7331: }
                   7332: 
                   7333: sub get_portfolio_access {
1.1172.2.77  raeburn  7334:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7335: 
                   7336:     if (!ref($access_hash)) {
                   7337: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7338: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7339: 						   $file_name);
                   7340: 	$access_hash = $access_controls{$file_name};
                   7341:     }
                   7342: 
1.1172.2.77  raeburn  7343:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7344:     my $now = time;
                   7345:     if (ref($access_hash) eq 'HASH') {
                   7346:         foreach my $key (keys(%{$access_hash})) {
                   7347:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7348:             if ($start > $now) {
                   7349:                 next;
                   7350:             }
                   7351:             if ($end && $end<$now) {
                   7352:                 next;
                   7353:             }
                   7354:             if ($scope eq 'public') {
                   7355:                 $public = $key;
                   7356:                 last;
                   7357:             } elsif ($scope eq 'guest') {
                   7358:                 $guest = $key;
                   7359:             } elsif ($scope eq 'domains') {
                   7360:                 push(@domains,$key);
                   7361:             } elsif ($scope eq 'users') {
                   7362:                 push(@users,$key);
                   7363:             } elsif ($scope eq 'course') {
                   7364:                 push(@courses,$key);
                   7365:             } elsif ($scope eq 'group') {
                   7366:                 push(@groups,$key);
1.1172.2.77  raeburn  7367:             } elsif ($scope eq 'ip') {
                   7368:                 push(@ips,$key);
1.765     albertel 7369:             }
                   7370:         }
                   7371:         if ($public) {
                   7372:             return 'ok';
1.1172.2.77  raeburn  7373:         } elsif (@ips > 0) {
                   7374:             my $allowed;
                   7375:             foreach my $ipkey (@ips) {
                   7376:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7377:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7378:                         $allowed = 1;
                   7379:                         last;
                   7380:                     }
                   7381:                 }
                   7382:             }
                   7383:             if ($allowed) {
                   7384:                 return 'ok';
                   7385:             }
1.765     albertel 7386:         }
                   7387:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7388:             if ($guest) {
                   7389:                 return $guest;
                   7390:             }
                   7391:         } else {
                   7392:             if (@domains > 0) {
                   7393:                 foreach my $domkey (@domains) {
                   7394:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7395:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7396:                             return 'ok';
                   7397:                         }
                   7398:                     }
                   7399:                 }
                   7400:             }
                   7401:             if (@users > 0) {
                   7402:                 foreach my $userkey (@users) {
1.865     raeburn  7403:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7404:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7405:                             if (ref($item) eq 'HASH') {
                   7406:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7407:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7408:                                     return 'ok';
                   7409:                                 }
                   7410:                             }
                   7411:                         }
                   7412:                     } 
1.765     albertel 7413:                 }
                   7414:             }
                   7415:             my %roleshash;
                   7416:             my @courses_and_groups = @courses;
                   7417:             push(@courses_and_groups,@groups); 
                   7418:             if (@courses_and_groups > 0) {
                   7419:                 my (%allgroups,%allroles); 
                   7420:                 my ($start,$end,$role,$sec,$group);
                   7421:                 foreach my $envkey (%env) {
1.1060    raeburn  7422:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7423:                         my $cid = $2.'_'.$3; 
                   7424:                         if ($1 eq 'gr') {
                   7425:                             $group = $4;
                   7426:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7427:                         } else {
                   7428:                             if ($4 eq '') {
                   7429:                                 $sec = 'none';
                   7430:                             } else {
                   7431:                                 $sec = $4;
                   7432:                             }
                   7433:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7434:                         }
1.811     albertel 7435:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7436:                         my $cid = $2.'_'.$3;
                   7437:                         if ($4 eq '') {
                   7438:                             $sec = 'none';
                   7439:                         } else {
                   7440:                             $sec = $4;
                   7441:                         }
                   7442:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7443:                     }
                   7444:                 }
                   7445:                 if (keys(%allroles) == 0) {
                   7446:                     return;
                   7447:                 }
                   7448:                 foreach my $key (@courses_and_groups) {
                   7449:                     my %content = %{$$access_hash{$key}};
                   7450:                     my $cnum = $content{'number'};
                   7451:                     my $cdom = $content{'domain'};
                   7452:                     my $cid = $cdom.'_'.$cnum;
                   7453:                     if (!exists($allroles{$cid})) {
                   7454:                         next;
                   7455:                     }    
                   7456:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7457:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7458:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7459:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7460:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7461:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7462:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7463:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7464:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7465:                                         if (grep/^all$/,@sections) {
                   7466:                                             return 'ok';
                   7467:                                         } else {
                   7468:                                             if (grep/^$sec$/,@sections) {
                   7469:                                                 return 'ok';
                   7470:                                             }
                   7471:                                         }
                   7472:                                     }
                   7473:                                 }
                   7474:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7475:                                     if (grep/^none$/,@groups) {
                   7476:                                         return 'ok';
                   7477:                                     }
                   7478:                                 } else {
                   7479:                                     if (grep/^all$/,@groups) {
                   7480:                                         return 'ok';
                   7481:                                     } 
                   7482:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7483:                                         if (grep/^$group$/,@groups) {
                   7484:                                             return 'ok';
                   7485:                                         }
                   7486:                                     }
                   7487:                                 } 
                   7488:                             }
                   7489:                         }
                   7490:                     }
                   7491:                 }
                   7492:             }
                   7493:             if ($guest) {
                   7494:                 return $guest;
                   7495:             }
                   7496:         }
                   7497:     }
                   7498:     return;
                   7499: }
                   7500: 
                   7501: sub course_group_datechecker {
                   7502:     my ($dates,$now,$status) = @_;
                   7503:     my ($start,$end) = split(/\./,$dates);
                   7504:     if (!$start && !$end) {
                   7505:         return 'ok';
                   7506:     }
                   7507:     if (grep/^active$/,@{$status}) {
                   7508:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7509:             return 'ok';
                   7510:         }
                   7511:     }
                   7512:     if (grep/^previous$/,@{$status}) {
                   7513:         if ($end > $now ) {
                   7514:             return 'ok';
                   7515:         }
                   7516:     }
                   7517:     if (grep/^future$/,@{$status}) {
                   7518:         if ($start > $now) {
                   7519:             return 'ok';
                   7520:         }
                   7521:     }
                   7522:     return; 
                   7523: }
                   7524: 
                   7525: sub parse_portfolio_url {
                   7526:     my ($url) = @_;
                   7527: 
                   7528:     my ($type,$udom,$unum,$group,$file_name);
                   7529:     
1.823     albertel 7530:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7531: 	$type = 1;
                   7532:         $udom = $1;
                   7533:         $unum = $2;
                   7534:         $file_name = $3;
1.823     albertel 7535:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7536: 	$type = 2;
                   7537:         $udom = $1;
                   7538:         $unum = $2;
                   7539:         $group = $3;
                   7540:         $file_name = $3.'/'.$4;
                   7541:     }
                   7542:     if (wantarray) {
                   7543: 	return ($type,$udom,$unum,$file_name,$group);
                   7544:     }
                   7545:     return $type;
                   7546: }
                   7547: 
                   7548: sub is_portfolio_url {
                   7549:     my ($url) = @_;
                   7550:     return scalar(&parse_portfolio_url($url));
                   7551: }
                   7552: 
1.798     raeburn  7553: sub is_portfolio_file {
                   7554:     my ($file) = @_;
1.820     raeburn  7555:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7556:         return 1;
                   7557:     }
                   7558:     return;
                   7559: }
                   7560: 
1.976     raeburn  7561: sub usertools_access {
1.1084    raeburn  7562:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7563:     my ($access,%tools);
                   7564:     if ($context eq '') {
                   7565:         $context = 'tools';
                   7566:     }
                   7567:     if ($context eq 'requestcourses') {
                   7568:         %tools = (
                   7569:                       official   => 1,
                   7570:                       unofficial => 1,
1.1006    raeburn  7571:                       community  => 1,
1.1172.2.37  raeburn  7572:                       textbook   => 1,
1.985     raeburn  7573:                  );
1.1172.2.9  raeburn  7574:     } elsif ($context eq 'requestauthor') {
                   7575:         %tools = (
                   7576:                       requestauthor => 1,
                   7577:                  );
1.985     raeburn  7578:     } else {
                   7579:         %tools = (
                   7580:                       aboutme   => 1,
                   7581:                       blog      => 1,
1.1172.2.6  raeburn  7582:                       webdav    => 1,
1.985     raeburn  7583:                       portfolio => 1,
                   7584:                  );
                   7585:     }
1.976     raeburn  7586:     return if (!defined($tools{$tool}));
                   7587: 
1.1172.2.35  raeburn  7588:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7589:         $udom = $env{'user.domain'};
                   7590:         $uname = $env{'user.name'};
                   7591:     }
                   7592: 
1.978     raeburn  7593:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7594:         if ($action ne 'reload') {
1.985     raeburn  7595:             if ($context eq 'requestcourses') {
                   7596:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7597:             } elsif ($context eq 'requestauthor') {
                   7598:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7599:             } else {
                   7600:                 return $env{'environment.availabletools.'.$tool};
                   7601:             }
                   7602:         }
1.976     raeburn  7603:     }
                   7604: 
1.1172.2.9  raeburn  7605:     my ($toolstatus,$inststatus,$envkey);
                   7606:     if ($context eq 'requestauthor') {
                   7607:         $envkey = $context;
                   7608:     } else {
                   7609:         $envkey = $context.'.'.$tool;
                   7610:     }
1.976     raeburn  7611: 
1.985     raeburn  7612:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7613:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7614:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7615:         $inststatus = $env{'environment.inststatus'};
                   7616:     } else {
1.1084    raeburn  7617:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7618:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7619:             $inststatus = $userenvref->{'inststatus'};
                   7620:         } else {
1.1172.2.9  raeburn  7621:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7622:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7623:             $inststatus = $userenv{'inststatus'};
                   7624:         }
1.976     raeburn  7625:     }
                   7626: 
                   7627:     if ($toolstatus ne '') {
                   7628:         if ($toolstatus) {
                   7629:             $access = 1;
                   7630:         } else {
                   7631:             $access = 0;
                   7632:         }
                   7633:         return $access;
                   7634:     }
                   7635: 
1.1084    raeburn  7636:     my ($is_adv,%domdef);
                   7637:     if (ref($is_advref) eq 'HASH') {
                   7638:         $is_adv = $is_advref->{'is_adv'};
                   7639:     } else {
                   7640:         $is_adv = &is_advanced_user($udom,$uname);
                   7641:     }
                   7642:     if (ref($domdefref) eq 'HASH') {
                   7643:         %domdef = %{$domdefref};
                   7644:     } else {
                   7645:         %domdef = &get_domain_defaults($udom);
                   7646:     }
1.976     raeburn  7647:     if (ref($domdef{$tool}) eq 'HASH') {
                   7648:         if ($is_adv) {
                   7649:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7650:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7651:                     $access = 1;
                   7652:                 } else {
                   7653:                     $access = 0;
                   7654:                 }
                   7655:                 return $access;
                   7656:             }
                   7657:         }
                   7658:         if ($inststatus ne '') {
                   7659:             my ($hasaccess,$hasnoaccess);
                   7660:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7661:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7662:                     if ($domdef{$tool}{$affiliation}) {
                   7663:                         $hasaccess = 1;
                   7664:                     } else {
                   7665:                         $hasnoaccess = 1;
                   7666:                     }
                   7667:                 }
                   7668:             }
                   7669:             if ($hasaccess || $hasnoaccess) {
                   7670:                 if ($hasaccess) {
                   7671:                     $access = 1;
                   7672:                 } elsif ($hasnoaccess) {
                   7673:                     $access = 0; 
                   7674:                 }
                   7675:                 return $access;
                   7676:             }
                   7677:         } else {
                   7678:             if ($domdef{$tool}{'default'} ne '') {
                   7679:                 if ($domdef{$tool}{'default'}) {
                   7680:                     $access = 1;
                   7681:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7682:                     $access = 0;
                   7683:                 }
                   7684:                 return $access;
                   7685:             }
                   7686:         }
                   7687:     } else {
1.1172.2.6  raeburn  7688:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7689:             $access = 1;
                   7690:         } else {
                   7691:             $access = 0;
                   7692:         }
1.976     raeburn  7693:         return $access;
                   7694:     }
                   7695: }
                   7696: 
1.1050    raeburn  7697: sub is_course_owner {
                   7698:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7699:     if (($udom eq '') || ($uname eq '')) {
                   7700:         $udom = $env{'user.domain'};
                   7701:         $uname = $env{'user.name'};
                   7702:     }
                   7703:     unless (($udom eq '') || ($uname eq '')) {
                   7704:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7705:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7706:                 return 1;
                   7707:             } else {
                   7708:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7709:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7710:                     return 1;
                   7711:                 }
                   7712:             }
                   7713:         }
                   7714:     }
                   7715:     return;
                   7716: }
                   7717: 
1.976     raeburn  7718: sub is_advanced_user {
                   7719:     my ($udom,$uname) = @_;
1.1085    raeburn  7720:     if ($udom ne '' && $uname ne '') {
                   7721:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7722:             if (wantarray) {
                   7723:                 return ($env{'user.adv'},$env{'user.author'});
                   7724:             } else {
                   7725:                 return $env{'user.adv'};
                   7726:             }
1.1085    raeburn  7727:         }
                   7728:     }
1.976     raeburn  7729:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7730:     my %allroles;
1.1128    raeburn  7731:     my ($is_adv,$is_author);
1.976     raeburn  7732:     foreach my $role (keys(%roleshash)) {
                   7733:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7734:         my $area = '/'.$tdomain.'/'.$trest;
                   7735:         if ($sec ne '') {
                   7736:             $area .= '/'.$sec;
                   7737:         }
                   7738:         if (($area ne '') && ($trole ne '')) {
                   7739:             my $spec=$trole.'.'.$area;
                   7740:             if ($trole =~ /^cr\//) {
                   7741:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7742:             } elsif ($trole ne 'gr') {
                   7743:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7744:             }
1.1128    raeburn  7745:             if ($trole eq 'au') {
                   7746:                 $is_author = 1;
                   7747:             }
1.976     raeburn  7748:         }
                   7749:     }
                   7750:     foreach my $role (keys(%allroles)) {
                   7751:         last if ($is_adv);
                   7752:         foreach my $item (split(/:/,$allroles{$role})) {
                   7753:             if ($item ne '') {
                   7754:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7755:                 if ($privilege eq 'adv') {
                   7756:                     $is_adv = 1;
                   7757:                     last;
                   7758:                 }
                   7759:             }
                   7760:         }
                   7761:     }
1.1128    raeburn  7762:     if (wantarray) {
                   7763:         return ($is_adv,$is_author);
                   7764:     }
1.976     raeburn  7765:     return $is_adv;
                   7766: }
1.798     raeburn  7767: 
1.1035    raeburn  7768: sub check_can_request {
1.1036    raeburn  7769:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7770:     my $canreq = 0;
                   7771:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7772:     my @options = ('approval','validate','autolimit');
                   7773:     my $optregex = join('|',@options);
                   7774:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7775:         foreach my $type (@{$types}) {
                   7776:             if (&usertools_access($env{'user.name'},
                   7777:                                   $env{'user.domain'},
                   7778:                                   $type,undef,'requestcourses')) {
                   7779:                 $canreq ++;
1.1036    raeburn  7780:                 if (ref($request_domains) eq 'HASH') {
                   7781:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7782:                 }
1.1035    raeburn  7783:                 if ($dom eq $env{'user.domain'}) {
                   7784:                     $can_request->{$type} = 1;
                   7785:                 }
                   7786:             }
                   7787:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7788:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7789:                 if (@curr > 0) {
1.1036    raeburn  7790:                     foreach my $item (@curr) {
                   7791:                         if (ref($request_domains) eq 'HASH') {
                   7792:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7793:                             if ($otherdom ne '') {
                   7794:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7795:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7796:                                         push(@{$request_domains->{$type}},$otherdom);
                   7797:                                     }
                   7798:                                 } else {
                   7799:                                     push(@{$request_domains->{$type}},$otherdom);
                   7800:                                 }
                   7801:                             }
                   7802:                         }
                   7803:                     }
                   7804:                     unless($dom eq $env{'user.domain'}) {
                   7805:                         $canreq ++;
1.1035    raeburn  7806:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7807:                             $can_request->{$type} = 1;
                   7808:                         }
                   7809:                     }
                   7810:                 }
                   7811:             }
                   7812:         }
                   7813:     }
                   7814:     return $canreq;
                   7815: }
                   7816: 
1.341     www      7817: # ---------------------------------------------- Custom access rule evaluation
                   7818: 
                   7819: sub customaccess {
                   7820:     my ($priv,$uri)=@_;
1.807     albertel 7821:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7822:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7823:     $udom = &LONCAPA::clean_domain($udom);
                   7824:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7825:     my $access=0;
1.800     albertel 7826:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7827: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7828: 	if ($type eq 'user') {
                   7829: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7830: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7831: 		if ($tdom) {
                   7832: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7833: 		}
1.896     albertel 7834: 		if ($tuname) {
                   7835: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7836: 		}
                   7837: 		$access=($effect eq 'allow');
                   7838: 		last;
                   7839: 	    }
                   7840: 	} else {
                   7841: 	    if ($role) {
                   7842: 		if ($role ne $urole) { next; }
                   7843: 	    }
                   7844: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7845: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7846: 		if ($tdom) {
                   7847: 		    if ($tdom ne $udom) { next; }
                   7848: 		}
                   7849: 		if ($tcrs) {
                   7850: 		    if ($tcrs ne $ucrs) { next; }
                   7851: 		}
                   7852: 		if ($tsec) {
                   7853: 		    if ($tsec ne $usec) { next; }
                   7854: 		}
                   7855: 		$access=($effect eq 'allow');
                   7856: 		last;
                   7857: 	    }
                   7858: 	    if ($realm eq '' && $role eq '') {
                   7859: 		$access=($effect eq 'allow');
                   7860: 	    }
1.402     bowersj2 7861: 	}
1.341     www      7862:     }
                   7863:     return $access;
                   7864: }
                   7865: 
1.103     harris41 7866: # ------------------------------------------------- Check for a user privilege
1.12      www      7867: 
                   7868: sub allowed {
1.1172.2.118.  .8(raebu 7869:20):     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
1.705     albertel 7870:     my $ver_orguri=$uri;
1.439     www      7871:     $uri=&deversion($uri);
1.152     www      7872:     my $orguri=$uri;
1.52      www      7873:     $uri=&declutter($uri);
1.809     raeburn  7874: 
1.810     raeburn  7875:     if ($priv eq 'evb') {
                   7876: # Evade communication block restrictions for specified role in a course
                   7877:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7878:             return $1;
                   7879:         } else {
                   7880:             return;
                   7881:         }
                   7882:     }
                   7883: 
1.620     albertel 7884:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7885: # Free bre access to adm and meta resources
1.1172.2.118.  .13(raeb 7886:-21):     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
1.769     albertel 7887: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7888: 	&& ($priv eq 'bre')) {
1.14      www      7889: 	return 'F';
1.159     www      7890:     }
                   7891: 
1.545     banghart 7892: # Free bre access to user's own portfolio contents
1.714     raeburn  7893:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7894:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7895: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7896:         my %setters;
                   7897:         my ($startblock,$endblock) = 
                   7898:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7899:         if ($startblock && $endblock) {
                   7900:             return 'B';
                   7901:         } else {
                   7902:             return 'F';
                   7903:         }
1.545     banghart 7904:     }
                   7905: 
1.762     raeburn  7906: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7907:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7908:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7909:         if (exists($env{'request.course.id'})) {
                   7910:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7911:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7912:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7913:                 my $courseprivid=$env{'request.course.id'};
                   7914:                 $courseprivid=~s/\_/\//;
                   7915:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7916:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7917:                     return $1; 
1.762     raeburn  7918:                 } else {
                   7919:                     if ($env{'request.course.sec'}) {
                   7920:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7921:                     }
                   7922:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7923:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7924:                         return $2;
                   7925:                     }
1.714     raeburn  7926:                 }
                   7927:             }
                   7928:         }
                   7929:     }
                   7930: 
1.159     www      7931: # Free bre to public access
                   7932: 
                   7933:     if ($priv eq 'bre') {
1.238     www      7934:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7935: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7936:            return 'F'; 
                   7937:         }
1.238     www      7938:         if ($copyright eq 'priv') {
                   7939:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7940: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7941: 		return '';
                   7942:             }
                   7943:         }
                   7944:         if ($copyright eq 'domain') {
                   7945:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7946: 	    unless (($env{'user.domain'} eq $1) ||
                   7947:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7948: 		return '';
                   7949:             }
1.262     matthew  7950:         }
1.620     albertel 7951:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7952:             # Library role, so allow browsing of resources in this domain.
                   7953:             return 'F';
1.238     www      7954:         }
1.341     www      7955:         if ($copyright eq 'custom') {
                   7956: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7957:         }
1.14      www      7958:     }
1.264     matthew  7959:     # Domain coordinator is trying to create a course
1.620     albertel 7960:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7961:         # uri is the requested domain in this case.
                   7962:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7963:         # a role of dc for the domain in question.
1.620     albertel 7964:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7965:     }
1.29      www      7966: 
1.52      www      7967:     my $thisallowed='';
                   7968:     my $statecond=0;
                   7969:     my $courseprivid='';
                   7970: 
1.1039    raeburn  7971:     my $ownaccess;
1.1043    raeburn  7972:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7973:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7974:         if ($uri eq '') {
                   7975:             $ownaccess = 1;
                   7976:         } else {
                   7977:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7978:                 my $udom = $env{'user.domain'};
                   7979:                 my $uname = $env{'user.name'};
                   7980:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7981:                     $ownaccess = 1;
1.1040    raeburn  7982:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7983:                     unless ($uri =~ m{\.\./}) {
                   7984:                         $ownaccess = 1;
                   7985:                     }
                   7986:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7987:                     my $now = time;
                   7988:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7989:                         my $adom = $1;
                   7990:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7991:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7992:                                 my ($start,$end) = split('.',$env{$key});
                   7993:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7994:                                     $ownaccess = 1;
                   7995:                                     last;
                   7996:                                 }
                   7997:                             }
                   7998:                         }
                   7999:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8000:                         my $adom = $1;
                   8001:                         my $aname = $2;
1.1042    raeburn  8002:                         foreach my $role ('ca','aa') { 
                   8003:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8004:                                 my ($start,$end) =
                   8005:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   8006:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   8007:                                     $ownaccess = 1;
                   8008:                                     last;
                   8009:                                 }
1.1039    raeburn  8010:                             }
                   8011:                         }
                   8012:                     }
                   8013:                 }
                   8014:             }
                   8015:         }
                   8016:     }
                   8017: 
1.52      www      8018: # Course
                   8019: 
1.620     albertel 8020:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8021:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8022:             $thisallowed.=$1;
                   8023:         }
1.52      www      8024:     }
1.29      www      8025: 
1.52      www      8026: # Domain
                   8027: 
1.620     albertel 8028:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8029:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8030:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8031:             $thisallowed.=$1;
                   8032:         }
1.12      www      8033:     }
1.52      www      8034: 
1.1141    raeburn  8035: # User who is not author or co-author might still be able to edit
                   8036: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8037:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8038:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8039:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8040:             $thisallowed.=$1;
                   8041:         }
                   8042:     }
                   8043: 
1.52      www      8044: # Course: uri itself is a course
1.66      www      8045:     my $courseuri=$uri;
                   8046:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8047:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8048: 
1.620     albertel 8049:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8050:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  8051:         if ($priv eq 'mip') {
                   8052:             my $rem = $1;
                   8053:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8054:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8055:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8056:                 if ($cdom ne '') {
                   8057:                     my %passwdconf = &get_passwdconf($cdom);
                   8058:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8059:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8060:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8061:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8062:                                 unless (@inststatuses) {
                   8063:                                     @inststatuses = ('default');
                   8064:                                 }
                   8065:                                 foreach my $status (@inststatuses) {
                   8066:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8067:                                         $thisallowed.=$rem;
                   8068:                                     }
                   8069:                                 }
                   8070:                             }
                   8071:                         }
                   8072:                     }
                   8073:                 }
                   8074:             }
                   8075:         } else {
                   8076:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8077:                 $thisallowed.=$1;
                   8078:             }
1.1039    raeburn  8079:         }
1.12      www      8080:     }
1.29      www      8081: 
1.665     albertel 8082: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8083: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8084:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8085: 	$thisallowed='';
1.671     raeburn  8086:         my ($match)=&is_on_map($uri);
                   8087:         if ($match) {
                   8088:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8089:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  8090:                 my $value = $1;
                   8091:                 if ($noblockcheck) {
                   8092:                     $thisallowed.=$value;
1.1162    raeburn  8093:                 } else {
1.1172.2.118.  .8(raebu 8094:20):                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8095:                     if (@blockers > 0) {
                   8096:                         $thisallowed = 'B';
                   8097:                     } else {
                   8098:                         $thisallowed.=$value;
                   8099:                     }
1.1162    raeburn  8100:                 }
1.671     raeburn  8101:             }
                   8102:         } else {
1.705     albertel 8103:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8104:             if ($refuri) {
                   8105:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8106:                     $thisallowed='F';
1.671     raeburn  8107:                 } else {
                   8108:                     $refuri=&declutter($refuri);
                   8109:                     my ($match) = &is_on_map($refuri);
                   8110:                     if ($match) {
1.1172.2.65  raeburn  8111:                         if ($noblockcheck) {
1.1162    raeburn  8112:                             $thisallowed='F';
1.1172.2.65  raeburn  8113:                         } else {
1.1172.2.118.  .8(raebu 8114:20):                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8115:                             if (@blockers > 0) {
                   8116:                                 $thisallowed = 'B';
                   8117:                             } else {
                   8118:                                 $thisallowed='F';
                   8119:                             }
1.1162    raeburn  8120:                         }
1.671     raeburn  8121:                     }
1.669     raeburn  8122:                 }
1.671     raeburn  8123:             }
                   8124:         }
1.314     www      8125:     }
1.492     albertel 8126: 
1.766     albertel 8127:     if ($priv eq 'bre'
                   8128: 	&& $thisallowed ne 'F' 
                   8129: 	&& $thisallowed ne '2'
                   8130: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8131: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8132:     }
1.1172.2.118.  .8(raebu 8133:20): 
1.52      www      8134: # Full access at system, domain or course-wide level? Exit.
1.29      www      8135:     if ($thisallowed=~/F/) {
                   8136: 	return 'F';
                   8137:     }
                   8138: 
1.52      www      8139: # If this is generating or modifying users, exit with special codes
1.29      www      8140: 
1.643     www      8141:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8142: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8143: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8144: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8145: 	    unless ($auname) { return $thisallowed; }
                   8146: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8147: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8148: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8149: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8150: 	}
1.52      www      8151: 	return $thisallowed;
                   8152:     }
                   8153: #
1.103     harris41 8154: # Gathered so far: system, domain and course wide privileges
1.52      www      8155: #
                   8156: # Course: See if uri or referer is an individual resource that is part of 
                   8157: # the course
                   8158: 
1.620     albertel 8159:     if ($env{'request.course.id'}) {
1.232     www      8160: 
1.1172.2.115  raeburn  8161: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8162: 
                   8163:         if ($priv eq 'mip') {
                   8164:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8165:                 return $thisallowed;
                   8166:             } else {
                   8167:                 return '';
                   8168:             }
                   8169:         }
                   8170: 
1.620     albertel 8171:        $courseprivid=$env{'request.course.id'};
                   8172:        if ($env{'request.course.sec'}) {
                   8173:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8174:        }
                   8175:        $courseprivid=~s/\_/\//;
                   8176:        my $checkreferer=1;
1.232     www      8177:        my ($match,$cond)=&is_on_map($uri);
                   8178:        if ($match) {
                   8179:            $statecond=$cond;
1.620     albertel 8180:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8181:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8182:                my $value = $1;
                   8183:                if ($priv eq 'bre') {
1.1172.2.65  raeburn  8184:                    if ($noblockcheck) {
1.1162    raeburn  8185:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8186:                    } else {
1.1172.2.118.  .8(raebu 8187:20):                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8188:                        if (@blockers > 0) {
                   8189:                            $thisallowed = 'B';
                   8190:                        } else {
                   8191:                            $thisallowed.=$value;
                   8192:                        }
1.1162    raeburn  8193:                    }
                   8194:                } else {
                   8195:                    $thisallowed.=$value;
                   8196:                }
1.52      www      8197:                $checkreferer=0;
                   8198:            }
1.29      www      8199:        }
1.1172.2.118.  .8(raebu 8200:20): 
1.148     www      8201:        if ($checkreferer) {
1.620     albertel 8202: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8203:             unless ($refuri) {
1.800     albertel 8204:                 foreach my $key (keys(%env)) {
                   8205: 		    if ($key=~/^httpref\..*\*/) {
                   8206: 			my $pattern=$key;
1.156     www      8207:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8208:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8209:                         $pattern=~s/\//\\\//g;
1.152     www      8210:                         if ($orguri=~/$pattern/) {
1.800     albertel 8211: 			    $refuri=$env{$key};
1.148     www      8212:                         }
                   8213:                     }
1.191     harris41 8214:                 }
1.148     www      8215:             }
1.232     www      8216: 
1.148     www      8217:          if ($refuri) { 
1.152     www      8218: 	  $refuri=&declutter($refuri);
1.232     www      8219:           my ($match,$cond)=&is_on_map($refuri);
                   8220:             if ($match) {
                   8221:               my $refstatecond=$cond;
1.620     albertel 8222:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8223:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8224:                   my $value = $1;
                   8225:                   if ($priv eq 'bre') {
1.1172.2.65  raeburn  8226:                       if ($noblockcheck) {
1.1162    raeburn  8227:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8228:                       } else {
1.1172.2.118.  .8(raebu 8229:20):                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8230:                           if (@blockers > 0) {
                   8231:                               $thisallowed = 'B';
                   8232:                           } else {
                   8233:                               $thisallowed.=$value;
                   8234:                           }
1.1162    raeburn  8235:                       }
                   8236:                   } else {
                   8237:                       $thisallowed.=$value;
                   8238:                   }
1.53      www      8239:                   $uri=$refuri;
                   8240:                   $statecond=$refstatecond;
1.52      www      8241:               }
                   8242:           }
1.148     www      8243:         }
1.29      www      8244:        }
1.52      www      8245:    }
1.29      www      8246: 
1.52      www      8247: #
1.103     harris41 8248: # Gathered now: all privileges that could apply, and condition number
1.52      www      8249: # 
                   8250: #
                   8251: # Full or no access?
                   8252: #
1.29      www      8253: 
1.52      www      8254:     if ($thisallowed=~/F/) {
                   8255: 	return 'F';
                   8256:     }
1.29      www      8257: 
1.52      www      8258:     unless ($thisallowed) {
                   8259:         return '';
                   8260:     }
1.29      www      8261: 
1.52      www      8262: # Restrictions exist, deal with them
                   8263: #
                   8264: #   C:according to course preferences
                   8265: #   R:according to resource settings
                   8266: #   L:unless locked
                   8267: #   X:according to user session state
                   8268: #
                   8269: 
                   8270: # Possibly locked functionality, check all courses
1.54      www      8271: # Locks might take effect only after 10 minutes cache expiration for other
                   8272: # courses, and 2 minutes for current course
1.52      www      8273: 
                   8274:     my $envkey;
                   8275:     if ($thisallowed=~/L/) {
1.1000    raeburn  8276:         foreach $envkey (keys(%env)) {
1.54      www      8277:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8278:                my $courseid=$2;
                   8279:                my $roleid=$1.'.'.$2;
1.92      www      8280:                $courseid=~s/^\///;
1.54      www      8281:                my $expiretime=600;
1.620     albertel 8282:                if ($env{'request.role'} eq $roleid) {
1.54      www      8283: 		  $expiretime=120;
                   8284:                }
                   8285: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8286:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8287:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8288: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8289:                }
1.620     albertel 8290:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8291:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8292: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8293:                        &log($env{'user.domain'},$env{'user.name'},
                   8294:                             $env{'user.home'},
1.57      www      8295:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8296:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8297:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8298: 		       return '';
                   8299:                    }
                   8300:                }
1.620     albertel 8301:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8302:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   8303: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   8304:                        &log($env{'user.domain'},$env{'user.name'},
                   8305:                             $env{'user.home'},
1.57      www      8306:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8307:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8308:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8309: 		       return '';
                   8310:                    }
                   8311:                }
                   8312: 	   }
1.29      www      8313:        }
1.52      www      8314:     }
1.1172.2.118.  .8(raebu 8315:20): 
1.52      www      8316: #
                   8317: # Rest of the restrictions depend on selected course
                   8318: #
                   8319: 
1.620     albertel 8320:     unless ($env{'request.course.id'}) {
1.766     albertel 8321: 	if ($thisallowed eq 'A') {
                   8322: 	    return 'A';
1.814     raeburn  8323:         } elsif ($thisallowed eq 'B') {
                   8324:             return 'B';
1.766     albertel 8325: 	} else {
                   8326: 	    return '1';
                   8327: 	}
1.52      www      8328:     }
1.29      www      8329: 
1.52      www      8330: #
                   8331: # Now user is definitely in a course
                   8332: #
1.53      www      8333: 
                   8334: 
                   8335: # Course preferences
                   8336: 
                   8337:    if ($thisallowed=~/C/) {
1.620     albertel 8338:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8339:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8340:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8341: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8342: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8343: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8344: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8345: 			$env{'request.course.id'});
                   8346: 	   }
1.237     www      8347:            return '';
                   8348:        }
                   8349: 
1.620     albertel 8350:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8351: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8352: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8353: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8354: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8355: 			$env{'request.course.id'});
                   8356: 	   }
1.54      www      8357:            return '';
                   8358:        }
1.53      www      8359:    }
                   8360: 
                   8361: # Resource preferences
                   8362: 
                   8363:    if ($thisallowed=~/R/) {
1.620     albertel 8364:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8365:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8366: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8367: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8368: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8369: 	   }
                   8370: 	   return '';
1.54      www      8371:        }
1.53      www      8372:    }
1.30      www      8373: 
1.246     www      8374: # Restricted by state or randomout?
1.30      www      8375: 
1.52      www      8376:    if ($thisallowed=~/X/) {
1.620     albertel 8377:       if ($env{'acc.randomout'}) {
1.579     albertel 8378: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8379:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8380:             return ''; 
                   8381:          }
1.247     www      8382:       }
                   8383:       if (&condval($statecond)) {
1.52      www      8384: 	 return '2';
                   8385:       } else {
                   8386:          return '';
                   8387:       }
                   8388:    }
1.30      www      8389: 
1.766     albertel 8390:     if ($thisallowed eq 'A') {
                   8391: 	return 'A';
1.814     raeburn  8392:     } elsif ($thisallowed eq 'B') {
                   8393:         return 'B';
1.766     albertel 8394:     }
1.52      www      8395:    return 'F';
1.232     www      8396: }
1.1162    raeburn  8397: 
1.1172.2.13  raeburn  8398: # ------------------------------------------- Check construction space access
                   8399: 
                   8400: sub constructaccess {
                   8401:     my ($url,$setpriv)=@_;
                   8402: 
                   8403: # We do not allow editing of previous versions of files
                   8404:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8405: 
                   8406: # Get username and domain from URL
                   8407:     my ($ownername,$ownerdomain,$ownerhome);
                   8408: 
                   8409:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8410:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8411: 
                   8412: # The URL does not really point to any authorspace, forget it
                   8413:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8414: 
                   8415: # Now we need to see if the user has access to the authorspace of
                   8416: # $ownername at $ownerdomain
                   8417: 
                   8418:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8419: # Real author for this?
                   8420:        $ownerhome = $env{'user.home'};
                   8421:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8422:           return ($ownername,$ownerdomain,$ownerhome);
                   8423:        }
                   8424:     } else {
                   8425: # Co-author for this?
                   8426:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8427:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8428:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8429:             return ($ownername,$ownerdomain,$ownerhome);
                   8430:         }
                   8431:     }
                   8432: 
                   8433: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8434: # we might as well leave
                   8435:    unless ($setpriv) { return ''; }
                   8436: 
                   8437: # Backdoor access?
                   8438:     my $allowed=&allowed('eco',$ownerdomain);
                   8439: # Nope
                   8440:     unless ($allowed) { return ''; }
                   8441: # Looks like we may have access, but could be locked by the owner of the construction space
                   8442:     if ($allowed eq 'U') {
                   8443:         my %blocked=&get('environment',['domcoord.author'],
                   8444:                          $ownerdomain,$ownername);
                   8445: # Is blocked by owner
                   8446:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8447:     }
                   8448:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8449: # Grant temporary access
                   8450:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8451:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8452:         if (!$update) { $update = $then; }
                   8453:         my $refresh=$env{'user.refresh.time'};
                   8454:         if (!$refresh) { $refresh = $update; }
                   8455:         my $now = time;
                   8456:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8457:                            $now,'ca','constructaccess');
                   8458:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8459:         return($ownername,$ownerdomain,$ownerhome);
                   8460:     }
                   8461: # No business here
                   8462:     return '';
                   8463: }
                   8464: 
1.1172.2.66  raeburn  8465: # ----------------------------------------------------------- Content Blocking
                   8466: 
                   8467: {
                   8468: # Caches for faster Course Contents display where content blocking
                   8469: # is in operation (i.e., interval param set) for timed quiz.
                   8470: #
                   8471: # User for whom data are being temporarily cached.
                   8472: my $cacheduser='';
1.1172.2.118.  .8(raebu 8473:20): # Course for which data are being temporarily cached.
                   8474:20): my $cachedcid='';
1.1172.2.66  raeburn  8475: # Cached blockers for this user (a hash of blocking items).
                   8476: my %cachedblockers=();
                   8477: # When the data were last cached.
                   8478: my $cachedlast='';
                   8479: 
                   8480: sub load_all_blockers {
1.1172.2.118.  .9(raebu 8481:20):     my ($uname,$udom)=@_;
1.1172.2.66  raeburn  8482:     if (($uname ne '') && ($udom ne '')) {
                   8483:         if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.118.  .8(raebu 8484:20):             ($cachedcid eq $env{'request.course.id'}) &&
          .9(raebu 8485:20):             (abs($cachedlast-time)<5)) {
1.1172.2.66  raeburn  8486:             return;
                   8487:         }
                   8488:     }
                   8489:     $cachedlast=time;
                   8490:     $cacheduser=$uname.':'.$udom;
1.1172.2.118.  .8(raebu 8491:20):     $cachedcid=$env{'request.course.id'};
          .9(raebu 8492:20):     %cachedblockers = &get_commblock_resources();
          .8(raebu 8493:20):     return;
1.1172.2.66  raeburn  8494: }
                   8495: 
1.1162    raeburn  8496: sub get_comm_blocks {
                   8497:     my ($cdom,$cnum) = @_;
                   8498:     if ($cdom eq '' || $cnum eq '') {
                   8499:         return unless ($env{'request.course.id'});
                   8500:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8501:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8502:     }
                   8503:     my %commblocks;
                   8504:     my $hashid=$cdom.'_'.$cnum;
                   8505:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8506:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8507:         %commblocks = %{$blocksref};
                   8508:     } else {
                   8509:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8510:         my $cachetime = 600;
                   8511:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8512:     }
                   8513:     return %commblocks;
                   8514: }
                   8515: 
1.1172.2.66  raeburn  8516: sub get_commblock_resources {
                   8517:     my ($blocks) = @_;
                   8518:     my %blockers = ();
                   8519:     return %blockers unless ($env{'request.course.id'});
                   8520:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8521:     my %commblocks;
                   8522:     if (ref($blocks) eq 'HASH') {
                   8523:         %commblocks = %{$blocks};
                   8524:     } else {
                   8525:         %commblocks = &get_comm_blocks();
                   8526:     }
1.1172.2.66  raeburn  8527:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8528:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8529:     return %blockers unless (ref($navmap));
                   8530:     my $now = time;
1.1162    raeburn  8531:     foreach my $block (keys(%commblocks)) {
                   8532:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8533:             my ($start,$end) = ($1,$2);
                   8534:             if ($start <= $now && $end >= $now) {
                   8535:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8536:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8537:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8538:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8539:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8540:                             }
                   8541:                         }
                   8542:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8543:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8544:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8545:                             }
                   8546:                         }
                   8547:                     }
                   8548:                 }
                   8549:             }
                   8550:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8551:             my $item = $1;
1.1163    raeburn  8552:             my @to_test;
1.1162    raeburn  8553:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8554:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.66  raeburn  8555:                     my @interval;
                   8556:                     my $type = 'map';
                   8557:                     if ($item eq 'course') {
                   8558:                         $type = 'course';
                   8559:                         @interval=&EXT("resource.0.interval");
                   8560:                     } else {
                   8561:                         if ($item =~ /___\d+___/) {
                   8562:                             $type = 'resource';
                   8563:                             @interval=&EXT("resource.0.interval",$item);
                   8564:                             if (ref($navmap)) {
                   8565:                                 my $res = $navmap->getBySymb($item);
                   8566:                                 push(@to_test,$res);
                   8567:                             }
1.1162    raeburn  8568:                         } else {
1.1172.2.66  raeburn  8569:                             my $mapsymb = &symbread($item,1);
                   8570:                             if ($mapsymb) {
                   8571:                                 if (ref($navmap)) {
                   8572:                                     my $mapres = $navmap->getBySymb($mapsymb);
1.1172.2.118.  .11(raeb 8573:-20):                                     if (ref($mapres)) {
                   8574:-20):                                         my $first = $mapres->map_start();
                   8575:-20):                                         my $finish = $mapres->map_finish();
                   8576:-20):                                         my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   8577:-20):                                         if (ref($it)) {
                   8578:-20):                                             my $res;
                   8579:-20):                                             while ($res = $it->next(undef,1)) {
                   8580:-20):                                                 next unless (ref($res));
                   8581:-20):                                                 my $symb = $res->symb();
                   8582:-20):                                                 next if (($symb eq $mapsymb) || ($symb eq ''));
                   8583:-20):                                                 @interval=&EXT("resource.0.interval",$symb);
                   8584:-20):                                                 if ($interval[1] eq 'map') {
                   8585:-20):                                                     if ($res->answerable()) {
                   8586:-20):                                                         push(@to_test,$res);
                   8587:-20):                                                         last;
                   8588:-20):                                                     }
                   8589:-20):                                                 }
1.1162    raeburn  8590:                                             }
                   8591:                                         }
                   8592:                                     }
                   8593:                                 }
                   8594:                             }
                   8595:                         }
1.1172.2.66  raeburn  8596:                     }
1.1172.2.118.  .1(raebu 8597:20):                     if ($interval[0] =~ /^(\d+)/) {
                   8598:20):                         my $timelimit = $1; 
1.1172.2.66  raeburn  8599:                         my $first_access;
                   8600:                         if ($type eq 'resource') {
                   8601:                             $first_access=&get_first_access($interval[1],$item);
                   8602:                         } elsif ($type eq 'map') {
                   8603:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8604:                         } else {
                   8605:                             $first_access=&get_first_access($interval[1]);
                   8606:                         }
                   8607:                         if ($first_access) {
1.1172.2.118.  .1(raebu 8608:20):                             my $timesup = $first_access+$timelimit;
1.1172.2.66  raeburn  8609:                             if ($timesup > $now) {
                   8610:                                 my $activeblock;
                   8611:                                 foreach my $res (@to_test) {
                   8612:                                     if ($res->answerable()) {
                   8613:                                         $activeblock = 1;
                   8614:                                         last;
                   8615:                                     }
                   8616:                                 }
                   8617:                                 if ($activeblock) {
                   8618:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8619:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8620:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8621:                                          }
                   8622:                                     }
                   8623:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8624:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8625:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8626:                                         }
1.1162    raeburn  8627:                                     }
                   8628:                                 }
                   8629:                             }
                   8630:                         }
                   8631:                     }
                   8632:                 }
                   8633:             }
                   8634:         }
                   8635:     }
1.1172.2.66  raeburn  8636:     return %blockers;
1.1162    raeburn  8637: }
                   8638: 
1.1172.2.66  raeburn  8639: sub has_comm_blocking {
1.1172.2.118.  .9(raebu 8640:20):     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66  raeburn  8641:     my @blockers;
                   8642:     return unless ($env{'request.course.id'});
                   8643:     return unless ($priv eq 'bre');
                   8644:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8645:     return if ($env{'request.state'} eq 'construct');
1.1172.2.118.  .9(raebu 8646:20):     my %blockinfo;
                   8647:20):     if (ref($blocks) eq 'HASH') {
                   8648:20):         %blockinfo = &get_commblock_resources($blocks);
                   8649:20):     } else {
                   8650:20):         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   8651:20):         %blockinfo = %cachedblockers;
                   8652:20):     }
                   8653:20):     return unless (keys(%blockinfo) > 0);
1.1172.2.66  raeburn  8654:     my (%possibles,@symbs);
                   8655:     if (!$symb) {
1.1172.2.118.  .9(raebu 8656:20):         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  8657:     }
1.1172.2.66  raeburn  8658:     if ($symb) {
                   8659:         @symbs = ($symb);
                   8660:     } elsif (keys(%possibles)) {
                   8661:         @symbs = keys(%possibles);
                   8662:     }
                   8663:     my $noblock;
                   8664:     foreach my $symb (@symbs) {
                   8665:         last if ($noblock);
                   8666:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.118.  .9(raebu 8667:20):         foreach my $block (keys(%blockinfo)) {
1.1172.2.66  raeburn  8668:             if ($block =~ /^firstaccess____(.+)$/) {
                   8669:                 my $item = $1;
1.1172.2.118.  .8(raebu 8670:20):                 unless ($blocked) {
                   8671:20):                     if (($item eq $map) || ($item eq $symb)) {
                   8672:20):                         $noblock = 1;
                   8673:20):                         last;
                   8674:20):                     }
1.1172.2.66  raeburn  8675:                 }
1.1162    raeburn  8676:             }
1.1172.2.118.  .9(raebu 8677:20):             if (ref($blockinfo{$block}) eq 'HASH') {
                   8678:20):                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   8679:20):                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66  raeburn  8680:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8681:                             push(@blockers,$block);
                   8682:                         }
                   8683:                     }
                   8684:                 }
1.1172.2.118.  .9(raebu 8685:20):                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   8686:20):                     if ($blockinfo{$block}{'maps'}{$map}) {
          .8(raebu 8687:20):                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8688:20):                             push(@blockers,$block);
                   8689:20):                         }
1.1172.2.66  raeburn  8690:                     }
                   8691:                 }
1.1162    raeburn  8692:             }
                   8693:         }
                   8694:     }
1.1172.2.118.  .8(raebu 8695:20):     unless ($noblock) {
                   8696:20):         return @blockers;
                   8697:20):     }
                   8698:20):     return;
1.1172.2.66  raeburn  8699: }
1.1162    raeburn  8700: }
                   8701: 
1.1172.2.66  raeburn  8702: # -------------------------------- Deversion and split uri into path an filename
                   8703: 
1.1133    foxr     8704: #
1.1172.2.66  raeburn  8705: #   Removes the version from a URI and
1.1133    foxr     8706: #   splits it in to its filename and path to the filename.
                   8707: #   Seems like File::Basename could have done this more clearly.
                   8708: #   Parameters:
                   8709: #      $uri   - input URI
                   8710: #   Returns:
                   8711: #     Two element list consisting of 
                   8712: #     $pathname  - the URI up to and excluding the trailing /
                   8713: #     $filename  - The part of the URI following the last /
                   8714: #  NOTE:
                   8715: #    Another realization of this is simply:
                   8716: #    use File::Basename;
                   8717: #    ...
                   8718: #    $uri = shift;
                   8719: #    $filename = basename($uri);
                   8720: #    $path     = dirname($uri);
                   8721: #    return ($filename, $path);
                   8722: #
                   8723: #     The implementation below is probably faster however.
                   8724: #
1.710     albertel 8725: sub split_uri_for_cond {
                   8726:     my $uri=&deversion(&declutter(shift));
                   8727:     my @uriparts=split(/\//,$uri);
                   8728:     my $filename=pop(@uriparts);
                   8729:     my $pathname=join('/',@uriparts);
                   8730:     return ($pathname,$filename);
                   8731: }
1.232     www      8732: # --------------------------------------------------- Is a resource on the map?
                   8733: 
                   8734: sub is_on_map {
1.710     albertel 8735:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8736:     #Trying to find the conditional for the file
1.620     albertel 8737:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8738: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8739:     if ($match) {
1.289     bowersj2 8740: 	return (1,$1);
                   8741:     } else {
1.434     www      8742: 	return (0,0);
1.289     bowersj2 8743:     }
1.12      www      8744: }
                   8745: 
1.427     www      8746: # --------------------------------------------------------- Get symb from alias
                   8747: 
                   8748: sub get_symb_from_alias {
                   8749:     my $symb=shift;
                   8750:     my ($map,$resid,$url)=&decode_symb($symb);
                   8751: # Already is a symb
                   8752:     if ($url) { return $symb; }
                   8753: # Must be an alias
                   8754:     my $aliassymb='';
                   8755:     my %bighash;
1.620     albertel 8756:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8757:                             &GDBM_READER(),0640)) {
                   8758:         my $rid=$bighash{'mapalias_'.$symb};
                   8759: 	if ($rid) {
                   8760: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8761: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8762: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8763: 	}
                   8764:         untie %bighash;
                   8765:     }
                   8766:     return $aliassymb;
                   8767: }
                   8768: 
1.12      www      8769: # ----------------------------------------------------------------- Define Role
                   8770: 
                   8771: sub definerole {
                   8772:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  8773:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8774:     foreach my $role (split(':',$sysrole)) {
                   8775: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8776:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8777:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8778: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8779:                return "refused:s:$crole&$cqual"; 
                   8780:             }
                   8781:         }
1.191     harris41 8782:     }
1.800     albertel 8783:     foreach my $role (split(':',$domrole)) {
                   8784: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8785:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8786:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8787: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8788:                return "refused:d:$crole&$cqual"; 
                   8789:             }
                   8790:         }
1.191     harris41 8791:     }
1.800     albertel 8792:     foreach my $role (split(':',$courole)) {
                   8793: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8794:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8795:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8796: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8797:                return "refused:c:$crole&$cqual"; 
                   8798:             }
                   8799:         }
1.191     harris41 8800:     }
1.1172.2.84  raeburn  8801:     my $uhome;
                   8802:     if (($uname ne '') && ($udom ne '')) {
                   8803:         $uhome = &homeserver($uname,$udom);
                   8804:         return $uhome if ($uhome eq 'no_host');
                   8805:     } else {
                   8806:         $uname = $env{'user.name'};
                   8807:         $udom = $env{'user.domain'};
                   8808:         $uhome = $env{'user.home'};
                   8809:     }
1.620     albertel 8810:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  8811:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8812:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  8813:     return reply($command,$uhome);
1.12      www      8814:   } else {
                   8815:     return 'refused';
                   8816:   }
1.105     harris41 8817: }
                   8818: 
                   8819: # ---------------- Make a metadata query against the network of library servers
                   8820: 
                   8821: sub metadata_query {
1.1172.2.33  raeburn  8822:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8823:     my %rhash;
1.845     albertel 8824:     my %libserv = &all_library();
1.244     matthew  8825:     my @server_list = (defined($server_array) ? @$server_array
                   8826:                                               : keys(%libserv) );
                   8827:     for my $server (@server_list) {
1.1172.2.33  raeburn  8828:         my $domains = '';
                   8829:         if (ref($domains_hash) eq 'HASH') {
                   8830:             $domains = $domains_hash->{$server};    
                   8831:         }
1.118     harris41 8832: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  8833: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8834: 	    $rhash{$server}=$reply;
                   8835: 	}
                   8836: 	else {
                   8837: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  8838: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8839: 			     $server);
                   8840: 	    $rhash{$server}=$reply;
                   8841: 	}
1.112     harris41 8842:     }
1.118     harris41 8843:     return \%rhash;
1.240     www      8844: }
                   8845: 
                   8846: # ----------------------------------------- Send log queries and wait for reply
                   8847: 
                   8848: sub log_query {
                   8849:     my ($uname,$udom,$query,%filters)=@_;
                   8850:     my $uhome=&homeserver($uname,$udom);
                   8851:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8852:     my $uhost=&hostname($uhome);
1.800     albertel 8853:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8854:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8855:                        $uhome);
1.479     albertel 8856:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8857:     return get_query_reply($queryid);
                   8858: }
                   8859: 
1.818     raeburn  8860: # -------------------------- Update MySQL table for portfolio file
                   8861: 
                   8862: sub update_portfolio_table {
1.821     raeburn  8863:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8864:     if ($group ne '') {
                   8865:         $file_name =~s /^\Q$group\E//;
                   8866:     }
1.818     raeburn  8867:     my $homeserver = &homeserver($uname,$udom);
                   8868:     my $queryid=
1.821     raeburn  8869:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8870:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8871:     my $reply = &get_query_reply($queryid);
                   8872:     return $reply;
                   8873: }
                   8874: 
1.899     raeburn  8875: # -------------------------- Update MySQL allusers table
                   8876: 
                   8877: sub update_allusers_table {
                   8878:     my ($uname,$udom,$names) = @_;
                   8879:     my $homeserver = &homeserver($uname,$udom);
                   8880:     my $queryid=
                   8881:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8882:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8883:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8884:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8885:                'generation='.&escape($names->{'generation'}).'%%'.
                   8886:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8887:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8888:     return;
1.899     raeburn  8889: }
                   8890: 
1.508     raeburn  8891: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8892: 
                   8893: sub fetch_enrollment_query {
1.511     raeburn  8894:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  8895:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8896:     my $maxtries = 1;
1.508     raeburn  8897:     if ($context eq 'automated') {
                   8898:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  8899:         $sleep = 2;
                   8900:         $loopmax = 100;
1.547     raeburn  8901:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8902:     } else {
                   8903:         $homeserver = &homeserver($cnum,$dom);
                   8904:     }
1.838     albertel 8905:     my $host=&hostname($homeserver);
1.506     raeburn  8906:     my $cmd = '';
1.1000    raeburn  8907:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8908:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8909:     }
                   8910:     $cmd =~ s/%%$//;
                   8911:     $cmd = &escape($cmd);
                   8912:     my $query = 'fetchenrollment';
1.620     albertel 8913:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8914:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8915:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8916:         return 'error: '.$queryid;
                   8917:     }
1.1172.2.93  raeburn  8918:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8919:     my $tries = 1;
                   8920:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  8921:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8922:         $tries ++;
                   8923:     }
1.526     raeburn  8924:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8925:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8926:     } else {
1.901     albertel 8927:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  8928:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8929:             foreach my $line (@responses) {
                   8930:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8931:                 $$replyref{$key} = $value;
                   8932:             }
                   8933:         } else {
1.1117    foxr     8934:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8935:             foreach my $line (@responses) {
                   8936:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8937:                 $$replyref{$key} = $value;
                   8938:                 if ($value > 0) {
1.800     albertel 8939:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8940:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8941:                         my $destname = $pathname.'/'.$filename;
                   8942:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8943:                         if ($xml_classlist =~ /^error/) {
                   8944:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8945:                         } else {
1.1172.2.96  raeburn  8946:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8947:                                 print FILE &unescape($xml_classlist);
                   8948:                                 close(FILE);
1.526     raeburn  8949:                             } else {
                   8950:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8951:                             }
                   8952:                         }
                   8953:                     }
                   8954:                 }
                   8955:             }
                   8956:         }
                   8957:         return 'ok';
                   8958:     }
                   8959:     return 'error';
                   8960: }
                   8961: 
1.242     www      8962: sub get_query_reply {
1.1172.2.79  raeburn  8963:     my ($queryid,$sleep,$loopmax) = @_;
                   8964:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8965:         $sleep = 0.2;
                   8966:     }
                   8967:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8968:         $loopmax = 100;
                   8969:     }
1.1117    foxr     8970:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8971:     my $reply='';
1.1172.2.79  raeburn  8972:     for (1..$loopmax) {
                   8973: 	sleep($sleep);
1.240     www      8974:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  8975: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8976: 		$reply = join('',<$fh>);
                   8977: 		close($fh);
1.240     www      8978: 	   } else { return 'error: reply_file_error'; }
1.242     www      8979:            return &unescape($reply);
                   8980: 	}
1.240     www      8981:     }
1.242     www      8982:     return 'timeout:'.$queryid;
1.240     www      8983: }
                   8984: 
                   8985: sub courselog_query {
1.241     www      8986: #
                   8987: # possible filters:
                   8988: # url: url or symb
                   8989: # username
                   8990: # domain
                   8991: # action: view, submit, grade
                   8992: # start: timestamp
                   8993: # end: timestamp
                   8994: #
1.240     www      8995:     my (%filters)=@_;
1.620     albertel 8996:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8997:     if ($filters{'url'}) {
                   8998: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8999:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9000:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9001:     }
1.620     albertel 9002:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9003:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9004:     return &log_query($cname,$cdom,'courselog',%filters);
                   9005: }
                   9006: 
                   9007: sub userlog_query {
1.858     raeburn  9008: #
                   9009: # possible filters:
                   9010: # action: log check role
                   9011: # start: timestamp
                   9012: # end: timestamp
                   9013: #
1.240     www      9014:     my ($uname,$udom,%filters)=@_;
                   9015:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9016: }
                   9017: 
1.506     raeburn  9018: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9019: 
                   9020: sub auto_run {
1.508     raeburn  9021:     my ($cnum,$cdom) = @_;
1.876     raeburn  9022:     my $response = 0;
                   9023:     my $settings;
                   9024:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9025:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9026:         $settings = $domconfig{'autoenroll'};
                   9027:         if ($settings->{'run'} eq '1') {
                   9028:             $response = 1;
                   9029:         }
                   9030:     } else {
1.934     raeburn  9031:         my $homeserver;
                   9032:         if (&is_course($cdom,$cnum)) {
                   9033:             $homeserver = &homeserver($cnum,$cdom);
                   9034:         } else {
                   9035:             $homeserver = &domain($cdom,'primary');
                   9036:         }
                   9037:         if ($homeserver ne 'no_host') {
                   9038:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9039:         }
1.876     raeburn  9040:     }
1.506     raeburn  9041:     return $response;
                   9042: }
1.776     albertel 9043: 
1.506     raeburn  9044: sub auto_get_sections {
1.508     raeburn  9045:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9046:     my $homeserver;
                   9047:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9048:         $homeserver = &homeserver($cnum,$cdom);
                   9049:     }
                   9050:     if (!defined($homeserver)) { 
                   9051:         if ($cdom =~ /^$match_domain$/) {
                   9052:             $homeserver = &domain($cdom,'primary');
                   9053:         }
                   9054:     }
                   9055:     my @secs;
                   9056:     if (defined($homeserver)) {
                   9057:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9058:         unless ($response eq 'refused') {
                   9059:             @secs = split(/:/,$response);
                   9060:         }
1.506     raeburn  9061:     }
                   9062:     return @secs;
                   9063: }
1.776     albertel 9064: 
1.506     raeburn  9065: sub auto_new_course {
1.1099    raeburn  9066:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9067:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9068:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9069:     return $response;
                   9070: }
1.776     albertel 9071: 
1.506     raeburn  9072: sub auto_validate_courseID {
1.508     raeburn  9073:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9074:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9075:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9076:     return $response;
                   9077: }
1.776     albertel 9078: 
1.1007    raeburn  9079: sub auto_validate_instcode {
1.1020    raeburn  9080:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9081:     my ($homeserver,$response);
                   9082:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9083:         $homeserver = &homeserver($cnum,$cdom);
                   9084:     }
                   9085:     if (!defined($homeserver)) {
                   9086:         if ($cdom =~ /^$match_domain$/) {
                   9087:             $homeserver = &domain($cdom,'primary');
                   9088:         }
                   9089:     }
1.1065    raeburn  9090:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9091:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  9092:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9093:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9094: }
                   9095: 
1.506     raeburn  9096: sub auto_create_password {
1.873     raeburn  9097:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9098:     my ($homeserver,$response);
1.506     raeburn  9099:     my $create_passwd = 0;
                   9100:     my $authchk = '';
1.873     raeburn  9101:     if ($udom =~ /^$match_domain$/) {
                   9102:         $homeserver = &domain($udom,'primary');
                   9103:     }
                   9104:     if ($homeserver eq '') {
                   9105:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9106:             $homeserver = &homeserver($cnum,$cdom);
                   9107:         }
                   9108:     }
                   9109:     if ($homeserver eq '') {
                   9110:         $authchk = 'nodomain';
1.506     raeburn  9111:     } else {
1.873     raeburn  9112:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9113:         if ($response eq 'refused') {
                   9114:             $authchk = 'refused';
                   9115:         } else {
1.901     albertel 9116:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9117:         }
1.506     raeburn  9118:     }
                   9119:     return ($authparam,$create_passwd,$authchk);
                   9120: }
                   9121: 
1.706     raeburn  9122: sub auto_photo_permission {
                   9123:     my ($cnum,$cdom,$students) = @_;
                   9124:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9125:     my ($outcome,$perm_reqd,$conditions) = 
                   9126: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9127:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9128: 	return (undef,undef);
                   9129:     }
1.706     raeburn  9130:     return ($outcome,$perm_reqd,$conditions);
                   9131: }
                   9132: 
                   9133: sub auto_checkphotos {
                   9134:     my ($uname,$udom,$pid) = @_;
                   9135:     my $homeserver = &homeserver($uname,$udom);
                   9136:     my ($result,$resulttype);
                   9137:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9138: 				   &escape($uname).':'.&escape($pid),
                   9139: 				   $homeserver));
1.709     albertel 9140:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9141: 	return (undef,undef);
                   9142:     }
1.706     raeburn  9143:     if ($outcome) {
                   9144:         ($result,$resulttype) = split(/:/,$outcome);
                   9145:     } 
                   9146:     return ($result,$resulttype);
                   9147: }
                   9148: 
                   9149: sub auto_photochoice {
                   9150:     my ($cnum,$cdom) = @_;
                   9151:     my $homeserver = &homeserver($cnum,$cdom);
                   9152:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9153: 						       &escape($cdom),
                   9154: 						       $homeserver)));
1.709     albertel 9155:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9156: 	return (undef,undef);
                   9157:     }
1.706     raeburn  9158:     return ($update,$comment);
                   9159: }
                   9160: 
                   9161: sub auto_photoupdate {
                   9162:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9163:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9164:     my $host=&hostname($homeserver);
1.706     raeburn  9165:     my $cmd = '';
                   9166:     my $maxtries = 1;
1.800     albertel 9167:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9168:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9169:     }
                   9170:     $cmd =~ s/%%$//;
                   9171:     $cmd = &escape($cmd);
                   9172:     my $query = 'institutionalphotos';
                   9173:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9174:     unless ($queryid=~/^\Q$host\E\_/) {
                   9175:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9176:         return 'error: '.$queryid;
                   9177:     }
                   9178:     my $reply = &get_query_reply($queryid);
                   9179:     my $tries = 1;
                   9180:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9181:         $reply = &get_query_reply($queryid);
                   9182:         $tries ++;
                   9183:     }
                   9184:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9185:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9186:     } else {
                   9187:         my @responses = split(/:/,$reply);
                   9188:         my $outcome = shift(@responses); 
                   9189:         foreach my $item (@responses) {
                   9190:             my ($key,$value) = split(/=/,$item);
                   9191:             $$photo{$key} = $value;
                   9192:         }
                   9193:         return $outcome;
                   9194:     }
                   9195:     return 'error';
                   9196: }
                   9197: 
1.521     raeburn  9198: sub auto_instcode_format {
1.793     albertel 9199:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9200: 	$cat_order) = @_;
1.521     raeburn  9201:     my $courses = '';
1.772     raeburn  9202:     my @homeservers;
1.521     raeburn  9203:     if ($caller eq 'global') {
1.841     albertel 9204: 	my %servers = &get_servers($codedom,'library');
                   9205: 	foreach my $tryserver (keys(%servers)) {
                   9206: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9207: 		push(@homeservers,$tryserver);
                   9208: 	    }
1.584     raeburn  9209:         }
1.1022    raeburn  9210:     } elsif ($caller eq 'requests') {
                   9211:         if ($codedom =~ /^$match_domain$/) {
                   9212:             my $chome = &domain($codedom,'primary');
                   9213:             unless ($chome eq 'no_host') {
                   9214:                 push(@homeservers,$chome);
                   9215:             }
                   9216:         }
1.521     raeburn  9217:     } else {
1.772     raeburn  9218:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9219:     }
1.793     albertel 9220:     foreach my $code (keys(%{$instcodes})) {
                   9221:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9222:     }
                   9223:     chop($courses);
1.772     raeburn  9224:     my $ok_response = 0;
                   9225:     my $response;
                   9226:     while (@homeservers > 0 && $ok_response == 0) {
                   9227:         my $server = shift(@homeservers); 
                   9228:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9229:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9230:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9231: 		split(/:/,$response);
1.772     raeburn  9232:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9233:             push(@{$codetitles},&str2array($codetitles_str));
                   9234:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9235:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9236:             $ok_response = 1;
                   9237:         }
                   9238:     }
                   9239:     if ($ok_response) {
1.521     raeburn  9240:         return 'ok';
1.772     raeburn  9241:     } else {
                   9242:         return $response;
1.521     raeburn  9243:     }
                   9244: }
                   9245: 
1.792     raeburn  9246: sub auto_instcode_defaults {
                   9247:     my ($domain,$returnhash,$code_order) = @_;
                   9248:     my @homeservers;
1.841     albertel 9249: 
                   9250:     my %servers = &get_servers($domain,'library');
                   9251:     foreach my $tryserver (keys(%servers)) {
                   9252: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9253: 	    push(@homeservers,$tryserver);
                   9254: 	}
1.792     raeburn  9255:     }
1.841     albertel 9256: 
1.792     raeburn  9257:     my $response;
1.841     albertel 9258:     foreach my $server (@homeservers) {
1.792     raeburn  9259:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9260:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9261: 	
                   9262: 	foreach my $pair (split(/\&/,$response)) {
                   9263: 	    my ($name,$value)=split(/\=/,$pair);
                   9264: 	    if ($name eq 'code_order') {
                   9265: 		@{$code_order} = split(/\&/,&unescape($value));
                   9266: 	    } else {
                   9267: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9268: 	    }
                   9269: 	}
                   9270: 	return 'ok';
1.792     raeburn  9271:     }
1.841     albertel 9272: 
                   9273:     return $response;
1.1003    raeburn  9274: }
                   9275: 
                   9276: sub auto_possible_instcodes {
1.1007    raeburn  9277:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9278:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9279:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9280:         return;
                   9281:     }
1.1003    raeburn  9282:     my (@homeservers,$uhome);
                   9283:     if (defined(&domain($domain,'primary'))) {
                   9284:         $uhome=&domain($domain,'primary');
                   9285:         push(@homeservers,&domain($domain,'primary'));
                   9286:     } else {
                   9287:         my %servers = &get_servers($domain,'library');
                   9288:         foreach my $tryserver (keys(%servers)) {
                   9289:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9290:                 push(@homeservers,$tryserver);
                   9291:             }
                   9292:         }
                   9293:     }
                   9294:     my $response;
                   9295:     foreach my $server (@homeservers) {
                   9296:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9297:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9298:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9299:             split(':',$response);
                   9300:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9301:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9302:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9303:             my ($name,$value)=split('=',$item);
                   9304:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9305:         }
                   9306:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9307:             my ($name,$value)=split('=',$item);
                   9308:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9309:         }
                   9310:         return 'ok';
                   9311:     }
                   9312:     return $response;
                   9313: }
1.792     raeburn  9314: 
1.1010    raeburn  9315: sub auto_courserequest_checks {
                   9316:     my ($dom) = @_;
1.1020    raeburn  9317:     my ($homeserver,%validations);
                   9318:     if ($dom =~ /^$match_domain$/) {
                   9319:         $homeserver = &domain($dom,'primary');
                   9320:     }
                   9321:     unless ($homeserver eq 'no_host') {
                   9322:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9323:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9324:             my @items = split(/&/,$response);
                   9325:             foreach my $item (@items) {
                   9326:                 my ($key,$value) = split('=',$item);
                   9327:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9328:             }
                   9329:         }
                   9330:     }
1.1010    raeburn  9331:     return %validations; 
                   9332: }
                   9333: 
1.1020    raeburn  9334: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9335:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9336:     my ($homeserver,$response);
                   9337:     if ($dom =~ /^$match_domain$/) {
                   9338:         $homeserver = &domain($dom,'primary');
                   9339:     }
1.1172.2.43  raeburn  9340:     unless ($homeserver eq 'no_host') {
                   9341:         my $customdata;
                   9342:         if (ref($custominfo) eq 'HASH') {
                   9343:             $customdata = &freeze_escape($custominfo);
                   9344:         }
1.1020    raeburn  9345:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9346:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9347:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9348:                                     $customdata,$homeserver));
1.1020    raeburn  9349:     }
                   9350:     return $response;
                   9351: }
                   9352: 
1.777     albertel 9353: sub auto_validate_class_sec {
1.918     raeburn  9354:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9355:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9356:     my $ownerlist;
                   9357:     if (ref($owners) eq 'ARRAY') {
                   9358:         $ownerlist = join(',',@{$owners});
                   9359:     } else {
                   9360:         $ownerlist = $owners;
                   9361:     }
1.773     raeburn  9362:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9363:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9364:     return $response;
                   9365: }
                   9366: 
1.1172.2.94  raeburn  9367: sub auto_validate_instclasses {
                   9368:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9369:     my ($homeserver,%validations);
                   9370:     $homeserver = &homeserver($cnum,$cdom);
                   9371:     unless ($homeserver eq 'no_host') {
                   9372:         my $ownerlist;
                   9373:         if (ref($owners) eq 'ARRAY') {
                   9374:             $ownerlist = join(',',@{$owners});
                   9375:         } else {
                   9376:             $ownerlist = $owners;
                   9377:         }
                   9378:         if (ref($classesref) eq 'HASH') {
                   9379:             my $classes = &freeze_escape($classesref);
                   9380:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9381:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9382:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9383:                 my @items = split(/&/,$response);
                   9384:                 foreach my $item (@items) {
                   9385:                     my ($key,$value) = split('=',$item);
                   9386:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9387:                 }
                   9388:             }
                   9389:         }
                   9390:     }
                   9391:     return %validations;
                   9392: }
                   9393: 
1.1172.2.38  raeburn  9394: sub auto_crsreq_update {
                   9395:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9396:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9397:     my ($homeserver,%crsreqresponse);
                   9398:     if ($cdom =~ /^$match_domain$/) {
                   9399:         $homeserver = &domain($cdom,'primary');
                   9400:     }
                   9401:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9402:         my $info;
                   9403:         if (ref($inbound) eq 'HASH') {
                   9404:             $info = &freeze_escape($inbound);
                   9405:         }
                   9406:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9407:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9408:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9409:                             &escape($title).':'.&escape($code).':'.
                   9410:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9411:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9412:             my @items = split(/&/,$response);
                   9413:             foreach my $item (@items) {
                   9414:                 my ($key,$value) = split('=',$item);
                   9415:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9416:             }
                   9417:         }
                   9418:     }
                   9419:     return \%crsreqresponse;
                   9420: }
                   9421: 
1.1172.2.78  raeburn  9422: sub auto_export_grades {
                   9423:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9424:     my ($homeserver,%exportresponse);
                   9425:     if ($cdom =~ /^$match_domain$/) {
                   9426:         $homeserver = &domain($cdom,'primary');
                   9427:     }
                   9428:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9429:         my $info;
                   9430:         if (ref($inforef) eq 'HASH') {
                   9431:             $info = &freeze_escape($inforef);
                   9432:         }
                   9433:         if (ref($gradesref) eq 'HASH') {
                   9434:             my $grades = &freeze_escape($gradesref);
                   9435:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9436:                                 $info.':'.$grades,$homeserver);
                   9437:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9438:                 my @items = split(/&/,$response);
                   9439:                 foreach my $item (@items) {
                   9440:                     my ($key,$value) = split('=',$item);
                   9441:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9442:                 }
                   9443:             }
                   9444:         }
                   9445:     }
                   9446:     return \%exportresponse;
                   9447: }
                   9448: 
1.1172.2.68  raeburn  9449: sub check_instcode_cloning {
                   9450:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9451:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9452:         return;
                   9453:     }
                   9454:     my $canclone;
                   9455:     if (@{$code_order} > 0) {
                   9456:         my $instcoderegexp ='^';
                   9457:         my @clonecodes = split(/\&/,$cloner);
                   9458:         foreach my $item (@{$code_order}) {
                   9459:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9460:                 foreach my $pair (@clonecodes) {
                   9461:                     my ($key,$val) = split(/\=/,$pair,2);
                   9462:                     $val = &unescape($val);
                   9463:                     if ($key eq $item) {
                   9464:                         $instcoderegexp .= '('.$val.')';
                   9465:                         last;
                   9466:                     }
                   9467:                 }
                   9468:             } else {
                   9469:                 $instcoderegexp .= $codedefaults->{$item};
                   9470:             }
                   9471:         }
                   9472:         $instcoderegexp .= '$';
                   9473:         my (@from,@to);
                   9474:         eval {
                   9475:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9476:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9477:         };
                   9478:         if ((@from > 0) && (@to > 0)) {
                   9479:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9480:             if (!@diffs) {
                   9481:                 $canclone = 1;
                   9482:             }
                   9483:         }
                   9484:     }
                   9485:     return $canclone;
                   9486: }
                   9487: 
                   9488: sub default_instcode_cloning {
                   9489:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9490:     my (%codedefaults,@code_order,$canclone);
                   9491:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9492:         %codedefaults = %{$codedefaultsref};
                   9493:         @code_order = @{$codeorderref};
                   9494:     } elsif ($clonedom) {
                   9495:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9496:     }
                   9497:     if (($domdefclone) && (@code_order)) {
                   9498:         my @clonecodes = split(/\+/,$domdefclone);
                   9499:         my $instcoderegexp ='^';
                   9500:         foreach my $item (@code_order) {
                   9501:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9502:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9503:             } else {
                   9504:                 $instcoderegexp .= $codedefaults{$item};
                   9505:             }
                   9506:         }
                   9507:         $instcoderegexp .= '$';
                   9508:         my (@from,@to);
                   9509:         eval {
                   9510:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9511:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9512:         };
                   9513:         if ((@from > 0) && (@to > 0)) {
                   9514:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9515:             if (!@diffs) {
                   9516:                 $canclone = 1;
                   9517:             }
                   9518:         }
                   9519:     }
                   9520:     return $canclone;
                   9521: }
                   9522: 
1.679     raeburn  9523: # ------------------------------------------------------- Course Group routines
                   9524: 
                   9525: sub get_coursegroups {
1.809     raeburn  9526:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9527:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9528: }
                   9529: 
1.679     raeburn  9530: sub modify_coursegroup {
                   9531:     my ($cdom,$cnum,$groupsettings) = @_;
                   9532:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9533: }
                   9534: 
1.809     raeburn  9535: sub toggle_coursegroup_status {
                   9536:     my ($cdom,$cnum,$group,$action) = @_;
                   9537:     my ($from_namespace,$to_namespace);
                   9538:     if ($action eq 'delete') {
                   9539:         $from_namespace = 'coursegroups';
                   9540:         $to_namespace = 'deleted_groups';
                   9541:     } else {
                   9542:         $from_namespace = 'deleted_groups';
                   9543:         $to_namespace = 'coursegroups';
                   9544:     }
                   9545:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9546:     if (my $tmp = &error(%curr_group)) {
                   9547:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9548:         return ('read error',$tmp);
                   9549:     } else {
                   9550:         my %savedsettings = %curr_group; 
1.809     raeburn  9551:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9552:         my $deloutcome;
                   9553:         if ($result eq 'ok') {
1.809     raeburn  9554:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9555:         } else {
                   9556:             return ('write error',$result);
                   9557:         }
                   9558:         if ($deloutcome eq 'ok') {
                   9559:             return 'ok';
                   9560:         } else {
                   9561:             return ('delete error',$deloutcome);
                   9562:         }
                   9563:     }
                   9564: }
                   9565: 
1.679     raeburn  9566: sub modify_group_roles {
1.957     raeburn  9567:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9568:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9569:     my $role = 'gr/'.&escape($userprivs);
                   9570:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9571:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9572:     if ($result eq 'ok') {
                   9573:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9574:     }
1.679     raeburn  9575:     return $result;
                   9576: }
                   9577: 
                   9578: sub modify_coursegroup_membership {
                   9579:     my ($cdom,$cnum,$membership) = @_;
                   9580:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9581:     return $result;
                   9582: }
                   9583: 
1.682     raeburn  9584: sub get_active_groups {
                   9585:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9586:     my $now = time;
                   9587:     my %groups = ();
                   9588:     foreach my $key (keys(%env)) {
1.811     albertel 9589:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9590:             my ($start,$end) = split(/\./,$env{$key});
                   9591:             if (($end!=0) && ($end<$now)) { next; }
                   9592:             if (($start!=0) && ($start>$now)) { next; }
                   9593:             if ($1 eq $cdom && $2 eq $cnum) {
                   9594:                 $groups{$3} = $env{$key} ;
                   9595:             }
                   9596:         }
                   9597:     }
                   9598:     return %groups;
                   9599: }
                   9600: 
1.683     raeburn  9601: sub get_group_membership {
                   9602:     my ($cdom,$cnum,$group) = @_;
                   9603:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9604: }
                   9605: 
                   9606: sub get_users_groups {
                   9607:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9608:     my @usersgroups;
1.683     raeburn  9609:     my $cachetime=1800;
                   9610: 
                   9611:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9612:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9613:     if (defined($cached)) {
1.734     albertel 9614:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9615:     } else {  
                   9616:         $grouplist = '';
1.816     raeburn  9617:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9618:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9619:         my $access_end = $env{'course.'.$courseid.
                   9620:                               '.default_enrollment_end_date'};
                   9621:         my $now = time;
                   9622:         foreach my $key (keys(%roleshash)) {
                   9623:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9624:                 my $group = $1;
                   9625:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9626:                     my $start = $2;
                   9627:                     my $end = $1;
                   9628:                     if ($start == -1) { next; } # deleted from group
                   9629:                     if (($start!=0) && ($start>$now)) { next; }
                   9630:                     if (($end!=0) && ($end<$now)) {
                   9631:                         if ($access_end && $access_end < $now) {
                   9632:                             if ($access_end - $end < 86400) {
                   9633:                                 push(@usersgroups,$group);
1.733     raeburn  9634:                             }
                   9635:                         }
1.817     raeburn  9636:                         next;
1.733     raeburn  9637:                     }
1.817     raeburn  9638:                     push(@usersgroups,$group);
1.683     raeburn  9639:                 }
                   9640:             }
                   9641:         }
1.817     raeburn  9642:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9643:         $grouplist = join(':',@usersgroups);
                   9644:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9645:     }
1.733     raeburn  9646:     return @usersgroups;
1.683     raeburn  9647: }
                   9648: 
                   9649: sub devalidate_getgroups_cache {
                   9650:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9651:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9652: 
1.683     raeburn  9653:     my $hashid="$udom:$uname:$courseid";
                   9654:     &devalidate_cache_new('getgroups',$hashid);
                   9655: }
                   9656: 
1.12      www      9657: # ------------------------------------------------------------------ Plain Text
                   9658: 
                   9659: sub plaintext {
1.988     raeburn  9660:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9661:     if ($short =~ m{^cr/}) {
1.758     albertel 9662: 	return (split('/',$short))[-1];
                   9663:     }
1.742     raeburn  9664:     if (!defined($cid)) {
                   9665:         $cid = $env{'request.course.id'};
                   9666:     }
                   9667:     my %rolenames = (
1.1008    raeburn  9668:                       Course    => 'std',
                   9669:                       Community => 'alt1',
1.742     raeburn  9670:                     );
1.1037    raeburn  9671:     if ($cid ne '') {
                   9672:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9673:             unless ($forcedefault) {
                   9674:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9675:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9676:                 return &Apache::lonlocal::mt($roletext);
                   9677:             }
                   9678:         }
                   9679:     }
                   9680:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9681:         (defined($rolenames{$type})) && 
                   9682:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9683:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9684:     } elsif ($cid ne '') {
                   9685:         my $crstype = $env{'course.'.$cid.'.type'};
                   9686:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9687:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9688:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9689:         }
1.742     raeburn  9690:     }
1.1037    raeburn  9691:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9692: }
                   9693: 
                   9694: # ----------------------------------------------------------------- Assign Role
                   9695: 
                   9696: sub assignrole {
1.957     raeburn  9697:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9698:         $context)=@_;
1.21      www      9699:     my $mrole;
                   9700:     if ($role =~ /^cr\//) {
1.393     www      9701:         my $cwosec=$url;
1.811     albertel 9702:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9703: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9704:            my $refused = 1;
                   9705:            if ($context eq 'requestcourses') {
                   9706:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9707:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9708:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9709:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9710:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9711:                            if ($crsenv{'internal.courseowner'} eq
                   9712:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9713:                                $refused = '';
                   9714:                            }
                   9715:                        }
                   9716:                    }
                   9717:                }
                   9718:            }
                   9719:            if ($refused) {
                   9720:                &logthis('Refused custom assignrole: '.
                   9721:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9722:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9723:                return 'refused';
                   9724:            }
1.104     www      9725:         }
1.21      www      9726:         $mrole='cr';
1.678     raeburn  9727:     } elsif ($role =~ /^gr\//) {
                   9728:         my $cwogrp=$url;
1.811     albertel 9729:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9730:         unless (&allowed('mdg',$cwogrp)) {
                   9731:             &logthis('Refused group assignrole: '.
                   9732:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9733:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9734:             return 'refused';
                   9735:         }
                   9736:         $mrole='gr';
1.21      www      9737:     } else {
1.82      www      9738:         my $cwosec=$url;
1.811     albertel 9739:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9740:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9741:             my $refused;
                   9742:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9743:                 if (!(&allowed('c'.$role,$url))) {
                   9744:                     $refused = 1;
                   9745:                 }
                   9746:             } else {
                   9747:                 $refused = 1;
                   9748:             }
1.947     raeburn  9749:             if ($refused) {
1.1045    raeburn  9750:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9751:                 if (!$selfenroll && $context eq 'course') {
                   9752:                     my %crsenv;
                   9753:                     if ($role eq 'cc' || $role eq 'co') {
                   9754:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9755:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9756:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9757:                                 if ($crsenv{'internal.courseowner'} eq 
                   9758:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9759:                                     $refused = '';
                   9760:                                 }
                   9761:                             }
                   9762:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9763:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9764:                                 if ($crsenv{'internal.courseowner'} eq 
                   9765:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9766:                                     $refused = '';
                   9767:                                 }
                   9768:                             }
                   9769:                         }
                   9770:                     }
                   9771:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9772:                     $refused = '';
1.1017    raeburn  9773:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9774:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9775:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9776:                         my $wrongcc;
                   9777:                         if ($cnum =~ /^$match_community$/) {
                   9778:                             $wrongcc = 1 if ($role eq 'cc');
                   9779:                         } else {
                   9780:                             $wrongcc = 1 if ($role eq 'co');
                   9781:                         }
                   9782:                         unless ($wrongcc) {
                   9783:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9784:                             if ($crsenv{'internal.courseowner'} eq 
                   9785:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9786:                                 $refused = '';
                   9787:                             }
1.1017    raeburn  9788:                         }
                   9789:                     }
1.1172.2.9  raeburn  9790:                 } elsif ($context eq 'requestauthor') {
                   9791:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   9792:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9793:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9794:                             $refused = '';
                   9795:                         } else {
                   9796:                             my %domdefaults = &get_domain_defaults($udom);
                   9797:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9798:                                 my $checkbystatus;
                   9799:                                 if ($env{'user.adv'}) {
                   9800:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9801:                                     if ($disposition eq 'automatic') {
                   9802:                                         $refused = '';
                   9803:                                     } elsif ($disposition eq '') {
                   9804:                                         $checkbystatus = 1;
                   9805:                                     }
                   9806:                                 } else {
                   9807:                                     $checkbystatus = 1;
                   9808:                                 }
                   9809:                                 if ($checkbystatus) {
                   9810:                                     if ($env{'environment.inststatus'}) {
                   9811:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9812:                                         foreach my $type (@inststatuses) {
                   9813:                                             if (($type ne '') &&
                   9814:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9815:                                                 $refused = '';
                   9816:                                             }
                   9817:                                         }
                   9818:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9819:                                         $refused = '';
                   9820:                                     }
                   9821:                                 }
                   9822:                             }
                   9823:                         }
                   9824:                     }
1.1017    raeburn  9825:                 }
                   9826:                 if ($refused) {
1.947     raeburn  9827:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9828:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9829: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9830:                     return 'refused';
                   9831:                 }
1.932     raeburn  9832:             }
1.1131    raeburn  9833:         } elsif ($role eq 'au') {
                   9834:             if ($url ne '/'.$udom.'/') {
                   9835:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9836:                          ' to assign author role for '.$uname.':'.$udom.
                   9837:                          ' in domain: '.$url.' refused (wrong domain).');
                   9838:                 return 'refused';
                   9839:             }
1.104     www      9840:         }
1.21      www      9841:         $mrole=$role;
                   9842:     }
1.620     albertel 9843:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9844:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9845:     if ($end) { $command.='_'.$end; }
1.21      www      9846:     if ($start) {
                   9847: 	if ($end) { 
1.81      www      9848:            $command.='_'.$start; 
1.21      www      9849:         } else {
1.81      www      9850:            $command.='_0_'.$start;
1.21      www      9851:         }
                   9852:     }
1.739     raeburn  9853:     my $origstart = $start;
                   9854:     my $origend = $end;
1.957     raeburn  9855:     my $delflag;
1.357     www      9856: # actually delete
                   9857:     if ($deleteflag) {
1.373     www      9858: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9859: # modify command to delete the role
1.620     albertel 9860:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9861:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9862: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9863: # set start and finish to negative values for userrolelog
                   9864:            $start=-1;
                   9865:            $end=-1;
1.957     raeburn  9866:            $delflag = 1;
1.357     www      9867:         }
                   9868:     }
                   9869: # send command
1.349     www      9870:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9871: # log new user role if status is ok
1.349     www      9872:     if ($answer eq 'ok') {
1.663     raeburn  9873: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  9874:         if (($role eq 'cc') || ($role eq 'in') ||
                   9875:             ($role eq 'ep') || ($role eq 'ad') ||
                   9876:             ($role eq 'ta') || ($role eq 'st') ||
                   9877:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9878:             ($role eq 'co')) {
1.1172.2.13  raeburn  9879: # for course roles, perform group memberships changes triggered by role change.
                   9880:             unless ($role =~ /^gr/) {
                   9881:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9882:                                                  $origstart,$selfenroll,$context);
                   9883:             }
1.1172.2.9  raeburn  9884:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9885:                            $selfenroll,$context);
                   9886:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  9887:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9888:                  ($role eq 'da')) {
1.1172.2.9  raeburn  9889:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9890:                            $context);
                   9891:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9892:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9893:                              $context);
                   9894:         }
1.1053    raeburn  9895:         if ($role eq 'cc') {
                   9896:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9897:         }
1.349     www      9898:     }
                   9899:     return $answer;
1.169     harris41 9900: }
                   9901: 
1.1053    raeburn  9902: sub autoupdate_coowners {
                   9903:     my ($url,$end,$start,$uname,$udom) = @_;
                   9904:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9905:     if (($cdom ne '') && ($cnum ne '')) {
                   9906:         my $now = time;
                   9907:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9908:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9909:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9910:             my $instcode = $coursehash{'internal.coursecode'};
                   9911:             if ($instcode ne '') {
1.1056    raeburn  9912:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9913:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9914:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9915:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9916:                         if ($result eq 'valid') {
                   9917:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9918:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9919:                                     push(@newcoowners,$coowner);
                   9920:                                 }
                   9921:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9922:                                     push(@newcoowners,$uname.':'.$udom);
                   9923:                                 }
                   9924:                                 @newcoowners = sort(@newcoowners);
                   9925:                             } else {
                   9926:                                 push(@newcoowners,$uname.':'.$udom);
                   9927:                             }
                   9928:                         } else {
                   9929:                             if ($coursehash{'internal.co-owners'}) {
                   9930:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9931:                                     unless ($coowner eq $uname.':'.$udom) {
                   9932:                                         push(@newcoowners,$coowner);
                   9933:                                     }
                   9934:                                 }
                   9935:                                 unless (@newcoowners > 0) {
                   9936:                                     $delcoowners = 1;
                   9937:                                     $coowners = '';
                   9938:                                 }
                   9939:                             }
                   9940:                         }
                   9941:                         if (@newcoowners || $delcoowners) {
                   9942:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9943:                                             $delcoowners,@newcoowners);
                   9944:                         }
                   9945:                     }
                   9946:                 }
                   9947:             }
                   9948:         }
                   9949:     }
                   9950: }
                   9951: 
                   9952: sub store_coowners {
                   9953:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9954:     my $cid = $cdom.'_'.$cnum;
                   9955:     my ($coowners,$delresult,$putresult);
                   9956:     if (@newcoowners) {
                   9957:         $coowners = join(',',@newcoowners);
                   9958:         my %coownershash = (
                   9959:                             'internal.co-owners' => $coowners,
                   9960:                            );
                   9961:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9962:         if ($putresult eq 'ok') {
                   9963:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9964:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9965:             }
                   9966:         }
                   9967:     }
                   9968:     if ($delcoowners) {
                   9969:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9970:         if ($delresult eq 'ok') {
                   9971:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9972:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9973:             }
                   9974:         }
                   9975:     }
                   9976:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9977:         my %crsinfo =
                   9978:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9979:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9980:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9981:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9982:         }
                   9983:     }
                   9984: }
                   9985: 
1.169     harris41 9986: # -------------------------------------------------- Modify user authentication
1.197     www      9987: # Overrides without validation
                   9988: 
1.169     harris41 9989: sub modifyuserauth {
                   9990:     my ($udom,$uname,$umode,$upass)=@_;
                   9991:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  9992:     my $allowed;
                   9993:     if (&allowed('mau',$udom)) {
                   9994:         $allowed = 1;
                   9995:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   9996:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   9997:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   9998:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9999:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10000:         if (($cdom ne '') && ($cnum ne '')) {
                   10001:             my $is_owner = &is_course_owner($cdom,$cnum);
                   10002:             if ($is_owner) {
                   10003:                 $allowed = 1;
                   10004:             }
                   10005:         }
                   10006:     }
                   10007:     unless ($allowed) { return 'refused'; }
1.197     www      10008:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 10009:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10010:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 10011:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10012: 		     &escape($upass),$uhome);
1.1172.2.118.  .14(raeb 10013:-21):     my $ip = &get_requestor_ip();
1.620     albertel 10014:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10015:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.118.  .14(raeb 10016:-21):          '(Remote '.$ip.'): '.$reply);
1.197     www      10017:     &log($udom,,$uname,$uhome,
1.620     albertel 10018:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10019:                                      $env{'user.name'}.', '.$umode.
1.1172.2.118.  .14(raeb 10020:-21):          '(Remote '.$ip.'): '.$reply);
1.169     harris41 10021:     unless ($reply eq 'ok') {
1.197     www      10022:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10023: 	return 'error: '.$reply;
                   10024:     }   
1.170     harris41 10025:     return 'ok';
1.80      www      10026: }
                   10027: 
1.81      www      10028: # --------------------------------------------------------------- Modify a user
1.80      www      10029: 
1.81      www      10030: sub modifyuser {
1.206     matthew  10031:     my ($udom,    $uname, $uid,
                   10032:         $umode,   $upass, $first,
                   10033:         $middle,  $last,  $gene,
1.1058    raeburn  10034:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10035:     $udom= &LONCAPA::clean_domain($udom);
                   10036:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10037:     my $showcandelete = 'none';
                   10038:     if (ref($candelete) eq 'ARRAY') {
                   10039:         if (@{$candelete} > 0) {
                   10040:             $showcandelete = join(', ',@{$candelete});
                   10041:         }
                   10042:     }
1.81      www      10043:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10044:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10045: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10046:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10047:                                      ' desiredhome not specified'). 
1.620     albertel 10048:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10049:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10050:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10051:     my $newuser;
                   10052:     if ($uhome eq 'no_host') {
                   10053:         $newuser = 1;
                   10054:     }
1.80      www      10055: # ----------------------------------------------------------------- Create User
1.406     albertel 10056:     if (($uhome eq 'no_host') && 
                   10057: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      10058:         my $unhome='';
1.844     albertel 10059:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10060:             $unhome = $desiredhome;
1.620     albertel 10061: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10062: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10063:         } else { # load balancing routine for determining $unhome
1.81      www      10064:             my $loadm=10000000;
1.841     albertel 10065: 	    my %servers = &get_servers($udom,'library');
                   10066: 	    foreach my $tryserver (keys(%servers)) {
                   10067: 		my $answer=reply('load',$tryserver);
                   10068: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10069: 		    $loadm=$answer;
                   10070: 		    $unhome=$tryserver;
                   10071: 		}
1.80      www      10072: 	    }
                   10073:         }
                   10074:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10075: 	    return 'error: unable to find a home server for '.$uname.
                   10076:                    ' in domain '.$udom;
1.80      www      10077:         }
                   10078:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10079:                          &escape($upass),$unhome);
                   10080: 	unless ($reply eq 'ok') {
                   10081:             return 'error: '.$reply;
                   10082:         }   
1.230     stredwic 10083:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10084:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10085: 	    return 'error: unable verify users home machine.';
1.80      www      10086:         }
1.209     matthew  10087:     }   # End of creation of new user
1.80      www      10088: # ---------------------------------------------------------------------- Add ID
                   10089:     if ($uid) {
                   10090:        $uid=~tr/A-Z/a-z/;
                   10091:        my %uidhash=&idrget($udom,$uname);
1.196     www      10092:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10093:          && (!$forceid)) {
1.80      www      10094: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10095: 	      return 'error: user id "'.$uid.'" does not match '.
                   10096:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10097:           }
                   10098:        } else {
                   10099: 	  &idput($udom,($uname => $uid));
                   10100:        }
                   10101:     }
                   10102: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10103:     my @tmp=&get('environment',
1.899     raeburn  10104: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10105:                     'permanentemail','inststatus'],
1.134     albertel 10106: 		   $udom,$uname);
1.1075    raeburn  10107:     my (%names,%oldnames);
1.313     matthew  10108:     if ($tmp[0] =~ m/^error:.*/) { 
                   10109:         %names=(); 
                   10110:     } else {
                   10111:         %names = @tmp;
1.1075    raeburn  10112:         %oldnames = %names;
1.313     matthew  10113:     }
1.388     www      10114: #
1.1058    raeburn  10115: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10116: # of users did not contain them), do not overwrite existing values
                   10117: # unless field is in $candelete array ref.  
                   10118: #
                   10119: 
                   10120:     my @fields = ('firstname','middlename','lastname','generation',
                   10121:                   'permanentemail','id');
                   10122:     my %newvalues;
                   10123:     if (ref($candelete) eq 'ARRAY') {
                   10124:         foreach my $field (@fields) {
                   10125:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10126:                 if ($field eq 'firstname') {
                   10127:                     $names{$field} = $first;
                   10128:                 } elsif ($field eq 'middlename') {
                   10129:                     $names{$field} = $middle;
                   10130:                 } elsif ($field eq 'lastname') {
                   10131:                     $names{$field} = $last;
                   10132:                 } elsif ($field eq 'generation') { 
                   10133:                     $names{$field} = $gene;
                   10134:                 } elsif ($field eq 'permanentemail') {
                   10135:                     $names{$field} = $email;
                   10136:                 } elsif ($field eq 'id') {
                   10137:                     $names{$field}  = $uid;
                   10138:                 }
                   10139:             }
                   10140:         }
                   10141:     }
1.388     www      10142:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10143:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10144:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10145:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10146:     if ($email) {
                   10147:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10148:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10149:     }
1.899     raeburn  10150:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10151:     if (defined($inststatus)) {
                   10152:         $names{'inststatus'} = '';
                   10153:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10154:         if (ref($usertypes) eq 'HASH') {
                   10155:             my @okstatuses; 
                   10156:             foreach my $item (split(/:/,$inststatus)) {
                   10157:                 if (defined($usertypes->{$item})) {
                   10158:                     push(@okstatuses,$item);  
                   10159:                 }
                   10160:             }
                   10161:             if (@okstatuses) {
                   10162:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10163:             }
                   10164:         }
                   10165:     }
1.1075    raeburn  10166:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10167:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10168:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10169:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10170:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10171:     } else {
                   10172:         $logmsg .= ' during self creation';
                   10173:     }
1.1075    raeburn  10174:     my $changed;
                   10175:     if ($newuser) {
                   10176:         $changed = 1;
                   10177:     } else {
                   10178:         foreach my $field (@fields) {
                   10179:             if ($names{$field} ne $oldnames{$field}) {
                   10180:                 $changed = 1;
                   10181:                 last;
                   10182:             }
                   10183:         }
                   10184:     }
                   10185:     unless ($changed) {
                   10186:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10187:         &logthis($logmsg);
                   10188:         return 'ok';
                   10189:     }
                   10190:     my $reply = &put('environment', \%names, $udom,$uname);
                   10191:     if ($reply ne 'ok') { 
                   10192:         return 'error: '.$reply;
                   10193:     }
1.1087    raeburn  10194:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10195:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10196:     }
1.1075    raeburn  10197:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10198:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10199:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10200:     &logthis($logmsg);
1.134     albertel 10201:     return 'ok';
1.80      www      10202: }
                   10203: 
1.81      www      10204: # -------------------------------------------------------------- Modify student
1.80      www      10205: 
1.81      www      10206: sub modifystudent {
                   10207:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10208:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10209:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10210:     if (!$cid) {
1.620     albertel 10211: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10212: 	    return 'not_in_class';
                   10213: 	}
1.80      www      10214:     }
                   10215: # --------------------------------------------------------------- Make the user
1.81      www      10216:     my $reply=&modifyuser
1.209     matthew  10217: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10218:          $desiredhome,$email,$inststatus);
1.80      www      10219:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10220:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10221:     # student's environment
1.297     matthew  10222:     $uid = undef if (!$forceid);
1.455     albertel 10223:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10224: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10225:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10226:     return $reply;
                   10227: }
                   10228: 
                   10229: sub modify_student_enrollment {
1.1172.2.23  raeburn  10230:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10231:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10232:     my ($cdom,$cnum,$chome);
                   10233:     if (!$cid) {
1.620     albertel 10234: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10235: 	    return 'not_in_class';
                   10236: 	}
1.620     albertel 10237: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10238: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10239:     } else {
                   10240: 	($cdom,$cnum)=split(/_/,$cid);
                   10241:     }
1.620     albertel 10242:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10243:     if (!$chome) {
1.457     raeburn  10244: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10245:     }
1.455     albertel 10246:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10247:     # Make sure the user exists
1.81      www      10248:     my $uhome=&homeserver($uname,$udom);
                   10249:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10250: 	return 'error: no such user';
                   10251:     }
1.297     matthew  10252:     # Get student data if we were not given enough information
                   10253:     if (!defined($first)  || $first  eq '' || 
                   10254:         !defined($last)   || $last   eq '' || 
                   10255:         !defined($uid)    || $uid    eq '' || 
                   10256:         !defined($middle) || $middle eq '' || 
                   10257:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10258:         # They did not supply us with enough data to enroll the student, so
                   10259:         # we need to pick up more information.
1.297     matthew  10260:         my %tmp = &get('environment',
1.294     matthew  10261:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10262:                        ,$udom,$uname);
                   10263: 
1.800     albertel 10264:         #foreach my $key (keys(%tmp)) {
                   10265:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10266:         #}
1.294     matthew  10267:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10268:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10269:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10270:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10271:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10272:     }
1.556     albertel 10273:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10274:     my $user = "$uname:$udom";
                   10275:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10276:     my $reply=cput('classlist',
1.1148    raeburn  10277: 		   {$user => 
1.1172.2.76  raeburn  10278: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10279: 		   $cdom,$cnum);
1.1148    raeburn  10280:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10281:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10282:     } else { 
1.81      www      10283: 	return 'error: '.$reply;
                   10284:     }
1.297     matthew  10285:     # Add student role to user
1.83      www      10286:     my $uurl='/'.$cid;
1.81      www      10287:     $uurl=~s/\_/\//g;
                   10288:     if ($usec) {
                   10289: 	$uurl.='/'.$usec;
                   10290:     }
1.1148    raeburn  10291:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10292:                              $selfenroll,$context);
                   10293:     if ($result ne 'ok') {
                   10294:         if ($old_entry{$user} ne '') {
                   10295:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10296:         } else {
                   10297:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10298:         }
                   10299:     }
                   10300:     return $result; 
1.21      www      10301: }
                   10302: 
1.556     albertel 10303: sub format_name {
                   10304:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10305:     my $name;
                   10306:     if ($first ne 'lastname') {
                   10307: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10308:     } else {
                   10309: 	if ($lastname=~/\S/) {
                   10310: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10311: 	    $name=~s/\s+,/,/;
                   10312: 	} else {
                   10313: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10314: 	}
                   10315:     }
                   10316:     $name=~s/^\s+//;
                   10317:     $name=~s/\s+$//;
                   10318:     $name=~s/\s+/ /g;
                   10319:     return $name;
                   10320: }
                   10321: 
1.84      www      10322: # ------------------------------------------------- Write to course preferences
                   10323: 
                   10324: sub writecoursepref {
                   10325:     my ($courseid,%prefs)=@_;
                   10326:     $courseid=~s/^\///;
                   10327:     $courseid=~s/\_/\//g;
                   10328:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10329:     my $chome=homeserver($cnum,$cdomain);
                   10330:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10331: 	return 'error: no such course';
                   10332:     }
                   10333:     my $cstring='';
1.800     albertel 10334:     foreach my $pref (keys(%prefs)) {
                   10335: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10336:     }
1.84      www      10337:     $cstring=~s/\&$//;
                   10338:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10339: }
                   10340: 
                   10341: # ---------------------------------------------------------- Make/modify course
                   10342: 
                   10343: sub createcourse {
1.741     raeburn  10344:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1172.2.118.  .6(raebu 10345:20):         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      10346:     $url=&declutter($url);
                   10347:     my $cid='';
1.1028    raeburn  10348:     if ($context eq 'requestcourses') {
                   10349:         my $can_create = 0;
                   10350:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10351:         if ($udom eq $ownerdom) {
1.1172.2.118.  .6(raebu 10352:20):             my $reload;
                   10353:20):             if (($callercontext eq 'auto') &&
                   10354:20):                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   10355:20):                 $reload = 'reload';
                   10356:20):             }
                   10357:20):             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  10358:                                   $context)) {
                   10359:                 $can_create = 1;
                   10360:             }
                   10361:         } else {
                   10362:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10363:                                            $category);
                   10364:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10365:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10366:                 if (@curr > 0) {
                   10367:                     my @options = qw(approval validate autolimit);
                   10368:                     my $optregex = join('|',@options);
                   10369:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10370:                         $can_create = 1;
                   10371:                     }
                   10372:                 }
                   10373:             }
                   10374:         }
                   10375:         if ($can_create) {
                   10376:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10377:                 unless (&allowed('ccc',$udom)) {
                   10378:                     return 'refused'; 
                   10379:                 }
1.1017    raeburn  10380:             }
                   10381:         } else {
                   10382:             return 'refused';
                   10383:         }
1.1028    raeburn  10384:     } elsif (!&allowed('ccc',$udom)) {
                   10385:         return 'refused';
1.84      www      10386:     }
1.1011    raeburn  10387: # --------------------------------------------------------------- Get Unique ID
                   10388:     my $uname;
                   10389:     if ($cnum =~ /^$match_courseid$/) {
                   10390:         my $chome=&homeserver($cnum,$udom,'true');
                   10391:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10392:             $uname = $cnum;
                   10393:         } else {
1.1038    raeburn  10394:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10395:         }
                   10396:     } else {
1.1038    raeburn  10397:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10398:     }
                   10399:     return $uname if ($uname =~ /^error/);
                   10400: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10401:     if (!defined($course_server)) {
                   10402:         if (defined(&domain($udom,'primary'))) {
                   10403:             $course_server = &domain($udom,'primary');
                   10404:         } else {
                   10405:             $course_server = $env{'user.home'}; 
                   10406:         }
                   10407:     }
                   10408:     my %host_servers =
                   10409:         &Apache::lonnet::get_servers($udom,'library');
                   10410:     unless ($host_servers{$course_server}) {
                   10411:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10412:     }
1.84      www      10413: # ------------------------------------------------------------- Make the course
                   10414:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10415:                       $course_server);
1.84      www      10416:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10417:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10418:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10419: 	return 'error: no such course';
                   10420:     }
1.271     www      10421: # ----------------------------------------------------------------- Course made
1.516     raeburn  10422: # log existence
1.1029    raeburn  10423:     my $now = time;
1.918     raeburn  10424:     my $newcourse = {
                   10425:                     $udom.'_'.$uname => {
1.921     raeburn  10426:                                      description => $description,
                   10427:                                      inst_code   => $inst_code,
                   10428:                                      owner       => $course_owner,
                   10429:                                      type        => $crstype,
1.1029    raeburn  10430:                                      creator     => $env{'user.name'}.':'.
                   10431:                                                     $env{'user.domain'},
                   10432:                                      created     => $now,
                   10433:                                      context     => $context,
1.918     raeburn  10434:                                                 },
                   10435:                     };
1.921     raeburn  10436:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10437: # set toplevel url
1.271     www      10438:     my $topurl=$url;
                   10439:     unless ($nonstandard) {
                   10440: # ------------------------------------------ For standard courses, make top url
                   10441:         my $mapurl=&clutter($url);
1.278     www      10442:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10443:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10444: <map>
                   10445: <resource id="1" type="start"></resource>
                   10446: <resource id="2" src="$mapurl"></resource>
                   10447: <resource id="3" type="finish"></resource>
                   10448: <link index="1" from="1" to="2"></link>
                   10449: <link index="2" from="2" to="3"></link>
                   10450: </map>
                   10451: ENDINITMAP
                   10452:         $topurl=&declutter(
1.638     albertel 10453:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10454:                           );
                   10455:     }
                   10456: # ----------------------------------------------------------- Write preferences
1.84      www      10457:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10458:                      ('description'              => $description,
                   10459:                       'url'                      => $topurl,
                   10460:                       'internal.creator'         => $env{'user.name'}.':'.
                   10461:                                                     $env{'user.domain'},
                   10462:                       'internal.created'         => $now,
                   10463:                       'internal.creationcontext' => $context)
                   10464:                     );
1.84      www      10465:     return '/'.$udom.'/'.$uname;
                   10466: }
                   10467: 
1.1011    raeburn  10468: # ------------------------------------------------------------------- Create ID
                   10469: sub generate_coursenum {
1.1038    raeburn  10470:     my ($udom,$crstype) = @_;
1.1011    raeburn  10471:     my $domdesc = &domain($udom);
                   10472:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10473:     my $first;
                   10474:     if ($crstype eq 'Community') {
                   10475:         $first = '0';
                   10476:     } else {
                   10477:         $first = int(1+rand(9)); 
                   10478:     } 
                   10479:     my $uname=$first.
1.1011    raeburn  10480:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10481:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10482:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10483: # ----------------------------------------------- Make sure that does not exist
                   10484:     my $uhome=&homeserver($uname,$udom,'true');
                   10485:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10486:         if ($crstype eq 'Community') {
                   10487:             $first = '0';
                   10488:         } else {
                   10489:             $first = int(1+rand(9));
                   10490:         }
                   10491:         $uname=$first.
1.1011    raeburn  10492:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10493:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10494:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10495:         $uhome=&homeserver($uname,$udom,'true');
                   10496:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10497:             return 'error: unable to generate unique course-ID';
                   10498:         }
                   10499:     }
                   10500:     return $uname;
                   10501: }
                   10502: 
1.813     albertel 10503: sub is_course {
1.1167    droeschl 10504:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10505:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10506:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10507:     my $uhome=&homeserver($cnum,$cdom);
                   10508:     my $iscourse;
                   10509:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10510:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10511:     } else {
                   10512:         my $hashid = $cdom.':'.$cnum;
                   10513:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10514:         unless (defined($cached)) {
                   10515:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10516:                                         $cnum,undef,undef,'.');
                   10517:             $iscourse = 0;
                   10518:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10519:                 $iscourse = 1;
                   10520:             }
                   10521:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10522:         }
                   10523:     }
                   10524:     return unless($iscourse);
1.1167    droeschl 10525:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10526: }
                   10527: 
1.1015    raeburn  10528: sub store_userdata {
                   10529:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10530:     my $result;
1.1016    raeburn  10531:     if ($datakey ne '') {
1.1013    raeburn  10532:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10533:             if ($udom eq '' || $uname eq '') {
                   10534:                 $udom = $env{'user.domain'};
                   10535:                 $uname = $env{'user.name'};
                   10536:             }
                   10537:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10538:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10539:                 $result = 'error: no_host';
                   10540:             } else {
1.1172.2.118.  .14(raeb 10541:-21):                 $storehash->{'ip'} = &get_requestor_ip();
1.1013    raeburn  10542:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10543: 
                   10544:                 my $namevalue='';
                   10545:                 foreach my $key (keys(%{$storehash})) {
                   10546:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10547:                 }
                   10548:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10549:                 unless ($namespace eq 'courserequests') {
                   10550:                     $datakey = &escape($datakey);
                   10551:                 }
1.1105    raeburn  10552:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10553:                                   $namevalue,$uhome);
1.1013    raeburn  10554:             }
                   10555:         } else {
                   10556:             $result = 'error: data to store was not a hash reference'; 
                   10557:         }
                   10558:     } else {
                   10559:         $result= 'error: invalid requestkey'; 
                   10560:     }
                   10561:     return $result;
                   10562: }
                   10563: 
1.21      www      10564: # ---------------------------------------------------------- Assign Custom Role
                   10565: 
                   10566: sub assigncustomrole {
1.957     raeburn  10567:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10568:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10569:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10570: }
                   10571: 
                   10572: # ----------------------------------------------------------------- Revoke Role
                   10573: 
                   10574: sub revokerole {
1.957     raeburn  10575:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10576:     my $now=time;
1.965     raeburn  10577:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10578: }
                   10579: 
                   10580: # ---------------------------------------------------------- Revoke Custom Role
                   10581: 
                   10582: sub revokecustomrole {
1.957     raeburn  10583:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10584:     my $now=time;
1.357     www      10585:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10586:            $deleteflag,$selfenroll,$context);
1.17      www      10587: }
                   10588: 
1.533     banghart 10589: # ------------------------------------------------------------ Disk usage
1.535     albertel 10590: sub diskusage {
1.955     raeburn  10591:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10592:     $directorypath =~ s/\/$//;
                   10593:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10594:                        .&escape($getpropath).':'.&escape($uname).':'
                   10595:                        .&escape($udom),homeserver($uname,$udom));
                   10596:     if ($listing eq 'unknown_cmd') {
                   10597:         if ($getpropath) {
                   10598:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10599:         }
                   10600:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10601:     }
1.514     albertel 10602:     return $listing;
1.512     banghart 10603: }
                   10604: 
1.566     banghart 10605: sub is_locked {
1.1096    raeburn  10606:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10607:     my @check;
                   10608:     my $is_locked;
1.1093    raeburn  10609:     push (@check,$file_name);
1.613     albertel 10610:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10611: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10612:     my ($tmp)=keys(%locked);
                   10613:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10614:     
1.566     banghart 10615:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10616:         $is_locked = 'false';
                   10617:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10618:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10619:                $is_locked = 'true';
1.1096    raeburn  10620:                if (ref($which) eq 'ARRAY') {
                   10621:                    push(@{$which},$entry);
                   10622:                } else {
                   10623:                    last;
                   10624:                }
1.745     raeburn  10625:            }
                   10626:        }
1.566     banghart 10627:     } else {
                   10628:         $is_locked = 'false';
                   10629:     }
1.1093    raeburn  10630:     return $is_locked;
1.566     banghart 10631: }
                   10632: 
1.759     albertel 10633: sub declutter_portfile {
                   10634:     my ($file) = @_;
1.833     albertel 10635:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10636:     return $file;
                   10637: }
                   10638: 
1.559     banghart 10639: # ------------------------------------------------------------- Mark as Read Only
                   10640: 
                   10641: sub mark_as_readonly {
                   10642:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10643:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10644:     my ($tmp)=keys(%current_permissions);
                   10645:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10646:     foreach my $file (@{$files}) {
1.759     albertel 10647: 	$file = &declutter_portfile($file);
1.561     banghart 10648:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10649:     }
1.613     albertel 10650:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10651:     return;
                   10652: }
                   10653: 
1.572     banghart 10654: # ------------------------------------------------------------Save Selected Files
                   10655: 
                   10656: sub save_selected_files {
                   10657:     my ($user, $path, @files) = @_;
                   10658:     my $filename = $user."savedfiles";
1.573     banghart 10659:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  10660:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10661:     foreach my $file (@files) {
1.620     albertel 10662:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10663:     }
                   10664:     foreach my $file (@other_files) {
1.574     banghart 10665:         print (OUT $file."\n");
1.572     banghart 10666:     }
1.574     banghart 10667:     close (OUT);
1.572     banghart 10668:     return 'ok';
                   10669: }
                   10670: 
1.574     banghart 10671: sub clear_selected_files {
                   10672:     my ($user) = @_;
                   10673:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  10674:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10675:     print (OUT undef);
                   10676:     close (OUT);
                   10677:     return ("ok");    
                   10678: }
                   10679: 
1.572     banghart 10680: sub files_in_path {
                   10681:     my ($user, $path) = @_;
                   10682:     my $filename = $user."savedfiles";
                   10683:     my %return_files;
1.1172.2.96  raeburn  10684:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10685:     while (my $line_in = <IN>) {
1.574     banghart 10686:         chomp ($line_in);
                   10687:         my @paths_and_file = split (m!/!, $line_in);
                   10688:         my $file_part = pop (@paths_and_file);
                   10689:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10690:         $path_part.='/';
                   10691:         my $path_and_file = $path_part.$file_part;
                   10692:         if ($path_part eq $path) {
                   10693:             $return_files{$file_part}= 'selected';
                   10694:         }
                   10695:     }
1.574     banghart 10696:     close (IN);
                   10697:     return (\%return_files);
1.572     banghart 10698: }
                   10699: 
                   10700: # called in portfolio select mode, to show files selected NOT in current directory
                   10701: sub files_not_in_path {
                   10702:     my ($user, $path) = @_;
                   10703:     my $filename = $user."savedfiles";
                   10704:     my @return_files;
                   10705:     my $path_part;
1.1172.2.96  raeburn  10706:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10707:     while (my $line = <IN>) {
1.572     banghart 10708:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10709:         my @paths_and_file = split(m|/|, $line);
                   10710:         my $file_part = pop(@paths_and_file);
                   10711:         chomp($file_part);
                   10712:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10713:         $path_part .= '/';
                   10714:         my $path_and_file = $path_part.$file_part;
                   10715:         if ($path_part ne $path) {
1.800     albertel 10716:             push(@return_files, ($path_and_file));
1.572     banghart 10717:         }
                   10718:     }
1.800     albertel 10719:     close(OUT);
1.574     banghart 10720:     return (@return_files);
1.572     banghart 10721: }
                   10722: 
1.745     raeburn  10723: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10724: 
1.745     raeburn  10725: sub get_portfile_permissions {
                   10726:     my ($domain,$user) = @_;
1.613     albertel 10727:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10728:     my ($tmp)=keys(%current_permissions);
                   10729:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10730:     return \%current_permissions;
                   10731: }
                   10732: 
                   10733: #---------------------------------------------Get portfolio file access controls
                   10734: 
1.749     raeburn  10735: sub get_access_controls {
1.745     raeburn  10736:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10737:     my %access;
                   10738:     my $real_file = $file;
                   10739:     $file =~ s/\.meta$//;
1.745     raeburn  10740:     if (defined($file)) {
1.749     raeburn  10741:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10742:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10743:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10744:             }
                   10745:         }
1.745     raeburn  10746:     } else {
1.749     raeburn  10747:         foreach my $key (keys(%{$current_permissions})) {
                   10748:             if ($key =~ /\0accesscontrol$/) {
                   10749:                 if (defined($group)) {
                   10750:                     if ($key !~ m-^\Q$group\E/-) {
                   10751:                         next;
                   10752:                     }
                   10753:                 }
                   10754:                 my ($fullpath) = split(/\0/,$key);
                   10755:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10756:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10757:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10758:                     }
                   10759:                 }
                   10760:             }
                   10761:         }
                   10762:     }
                   10763:     return %access;
                   10764: }
                   10765: 
                   10766: sub modify_access_controls {
                   10767:     my ($file_name,$changes,$domain,$user)=@_;
                   10768:     my ($outcome,$deloutcome);
                   10769:     my %store_permissions;
                   10770:     my %new_values;
                   10771:     my %new_control;
                   10772:     my %translation;
                   10773:     my @deletions = ();
                   10774:     my $now = time;
                   10775:     if (exists($$changes{'activate'})) {
                   10776:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10777:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10778:             my $numnew = scalar(@newitems);
                   10779:             for (my $i=0; $i<$numnew; $i++) {
                   10780:                 my $newkey = $newitems[$i];
                   10781:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10782:                 if ($newkey =~ /^\d+:/) { 
                   10783:                     $newkey =~ s/^(\d+)/$newid/;
                   10784:                     $translation{$1} = $newid;
                   10785:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10786:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10787:                     $translation{$1} = $newid;
                   10788:                 }
1.749     raeburn  10789:                 $new_values{$file_name."\0".$newkey} = 
                   10790:                                           $$changes{'activate'}{$newitems[$i]};
                   10791:                 $new_control{$newkey} = $now;
                   10792:             }
                   10793:         }
                   10794:     }
                   10795:     my %todelete;
                   10796:     my %changed_items;
                   10797:     foreach my $action ('delete','update') {
                   10798:         if (exists($$changes{$action})) {
                   10799:             if (ref($$changes{$action}) eq 'HASH') {
                   10800:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10801:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10802:                     if ($action eq 'delete') { 
                   10803:                         $todelete{$itemnum} = 1;
                   10804:                     } else {
                   10805:                         $changed_items{$itemnum} = $key;
                   10806:                     }
                   10807:                 }
1.745     raeburn  10808:             }
                   10809:         }
1.749     raeburn  10810:     }
                   10811:     # get lock on access controls for file.
                   10812:     my $lockhash = {
                   10813:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10814:                                                        ':'.$env{'user.domain'},
                   10815:                    }; 
                   10816:     my $tries = 0;
                   10817:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10818:    
1.1172.2.79  raeburn  10819:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10820:         $tries ++;
1.1172.2.79  raeburn  10821:         sleep(0.1);
1.749     raeburn  10822:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10823:     }
                   10824:     if ($gotlock eq 'ok') {
                   10825:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10826:         my ($tmp)=keys(%curr_permissions);
                   10827:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10828:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10829:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10830:             if (ref($curr_controls) eq 'HASH') {
                   10831:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10832:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10833:                     if (defined($todelete{$itemnum})) {
                   10834:                         push(@deletions,$file_name."\0".$control_item);
                   10835:                     } else {
                   10836:                         if (defined($changed_items{$itemnum})) {
                   10837:                             $new_control{$changed_items{$itemnum}} = $now;
                   10838:                             push(@deletions,$file_name."\0".$control_item);
                   10839:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10840:                         } else {
                   10841:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10842:                         }
                   10843:                     }
1.745     raeburn  10844:                 }
                   10845:             }
                   10846:         }
1.970     raeburn  10847:         my ($group);
                   10848:         if (&is_course($domain,$user)) {
                   10849:             ($group,my $file) = split(/\//,$file_name,2);
                   10850:         }
1.749     raeburn  10851:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10852:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10853:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10854:         #  remove lock
                   10855:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10856:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10857:         my $sqlresult =
1.970     raeburn  10858:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10859:                                     $group);
1.749     raeburn  10860:     } else {
                   10861:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10862:     }
1.749     raeburn  10863:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10864: }
                   10865: 
1.827     raeburn  10866: sub make_public_indefinitely {
                   10867:     my ($requrl) = @_;
                   10868:     my $now = time;
                   10869:     my $action = 'activate';
                   10870:     my $aclnum = 0;
                   10871:     if (&is_portfolio_url($requrl)) {
                   10872:         my (undef,$udom,$unum,$file_name,$group) =
                   10873:             &parse_portfolio_url($requrl);
                   10874:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   10875:         my %access_controls = &get_access_controls($current_perms,
                   10876:                                                    $group,$file_name);
                   10877:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10878:             my ($num,$scope,$end,$start) = 
                   10879:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   10880:             if ($scope eq 'public') {
                   10881:                 if ($start <= $now && $end == 0) {
                   10882:                     $action = 'none';
                   10883:                 } else {
                   10884:                     $action = 'update';
                   10885:                     $aclnum = $num;
                   10886:                 }
                   10887:                 last;
                   10888:             }
                   10889:         }
                   10890:         if ($action eq 'none') {
                   10891:              return 'ok';
                   10892:         } else {
                   10893:             my %changes;
                   10894:             my $newend = 0;
                   10895:             my $newstart = $now;
                   10896:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   10897:             $changes{$action}{$newkey} = {
                   10898:                 type => 'public',
                   10899:                 time => {
                   10900:                     start => $newstart,
                   10901:                     end   => $newend,
                   10902:                 },
                   10903:             };
                   10904:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10905:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   10906:             return $outcome;
                   10907:         }
                   10908:     } else {
                   10909:         return 'invalid';
                   10910:     }
                   10911: }
                   10912: 
1.745     raeburn  10913: #------------------------------------------------------Get Marked as Read Only
                   10914: 
                   10915: sub get_marked_as_readonly {
                   10916:     my ($domain,$user,$what,$group) = @_;
                   10917:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10918:     my @readonly_files;
1.629     banghart 10919:     my $cmp1=$what;
                   10920:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10921:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10922:         if (defined($group)) {
                   10923:             if ($file_name !~ m-^\Q$group\E/-) {
                   10924:                 next;
                   10925:             }
                   10926:         }
1.561     banghart 10927:         if (ref($value) eq "ARRAY"){
                   10928:             foreach my $stored_what (@{$value}) {
1.629     banghart 10929:                 my $cmp2=$stored_what;
1.759     albertel 10930:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10931:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10932:                 }
1.629     banghart 10933:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10934:                     push(@readonly_files, $file_name);
1.745     raeburn  10935:                     last;
1.563     banghart 10936:                 } elsif (!defined($what)) {
                   10937:                     push(@readonly_files, $file_name);
1.745     raeburn  10938:                     last;
1.561     banghart 10939:                 }
                   10940:             }
1.745     raeburn  10941:         }
1.561     banghart 10942:     }
                   10943:     return @readonly_files;
                   10944: }
1.577     banghart 10945: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10946: 
1.577     banghart 10947: sub get_marked_as_readonly_hash {
1.745     raeburn  10948:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10949:     my %readonly_files;
1.745     raeburn  10950:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10951:         if (defined($group)) {
                   10952:             if ($file_name !~ m-^\Q$group\E/-) {
                   10953:                 next;
                   10954:             }
                   10955:         }
1.577     banghart 10956:         if (ref($value) eq "ARRAY"){
                   10957:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10958:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10959:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10960:                         if ($lock_descriptor eq 'graded') {
                   10961:                             $readonly_files{$file_name} = 'graded';
                   10962:                         } elsif ($lock_descriptor eq 'handback') {
                   10963:                             $readonly_files{$file_name} = 'handback';
                   10964:                         } else {
                   10965:                             if (!exists($readonly_files{$file_name})) {
                   10966:                                 $readonly_files{$file_name} = 'locked';
                   10967:                             }
                   10968:                         }
1.745     raeburn  10969:                     }
1.750     banghart 10970:                 } 
1.577     banghart 10971:             }
                   10972:         } 
                   10973:     }
                   10974:     return %readonly_files;
                   10975: }
1.559     banghart 10976: # ------------------------------------------------------------ Unmark as Read Only
                   10977: 
                   10978: sub unmark_as_readonly {
1.629     banghart 10979:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10980:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10981:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10982:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10983:     my $symb_crs = $what;
                   10984:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10985:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10986:     my ($tmp)=keys(%current_permissions);
                   10987:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10988:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10989:     foreach my $file (@readonly_files) {
1.759     albertel 10990: 	my $clean_file = &declutter_portfile($file);
                   10991: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10992: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10993:         my @new_locks;
                   10994:         my @del_keys;
                   10995:         if (ref($current_locks) eq "ARRAY"){
                   10996:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10997:                 my $compare=$locker;
1.749     raeburn  10998:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10999:                     $compare=join('',@{$locker});
1.746     raeburn  11000:                     if ($compare ne $symb_crs) {
                   11001:                         push(@new_locks, $locker);
                   11002:                     }
1.563     banghart 11003:                 }
                   11004:             }
1.650     albertel 11005:             if (scalar(@new_locks) > 0) {
1.563     banghart 11006:                 $current_permissions{$file} = \@new_locks;
                   11007:             } else {
                   11008:                 push(@del_keys, $file);
1.613     albertel 11009:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11010:                 delete($current_permissions{$file});
1.563     banghart 11011:             }
                   11012:         }
1.561     banghart 11013:     }
1.613     albertel 11014:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11015:     return;
                   11016: }
1.512     banghart 11017: 
1.17      www      11018: # ------------------------------------------------------------ Directory lister
                   11019: 
                   11020: sub dirlist {
1.955     raeburn  11021:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11022:     $uri=~s/^\///;
                   11023:     $uri=~s/\/$//;
1.253     stredwic 11024:     my ($udom, $uname);
1.955     raeburn  11025:     if ($getuserdir) {
1.253     stredwic 11026:         $udom = $userdomain;
                   11027:         $uname = $username;
1.955     raeburn  11028:     } else {
                   11029:         (undef,$udom,$uname)=split(/\//,$uri);
                   11030:         if(defined($userdomain)) {
                   11031:             $udom = $userdomain;
                   11032:         }
                   11033:         if(defined($username)) {
                   11034:             $uname = $username;
                   11035:         }
1.253     stredwic 11036:     }
1.955     raeburn  11037:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11038: 
1.955     raeburn  11039:     $dirRoot = $perlvar{'lonDocRoot'};
                   11040:     if (defined($getpropath)) {
                   11041:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11042:         $dirRoot =~ s/\/$//;
1.955     raeburn  11043:     } elsif (defined($getuserdir)) {
                   11044:         my $subdir=$uname.'__';
                   11045:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11046:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11047:                    ."/$udom/$subdir/$uname";
                   11048:     } elsif (defined($alternateRoot)) {
                   11049:         $dirRoot = $alternateRoot;
1.751     banghart 11050:     }
1.253     stredwic 11051: 
                   11052:     if($udom) {
                   11053:         if($uname) {
1.1135    raeburn  11054:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11055:             if ($uhome eq 'no_host') {
                   11056:                 return ([],'no_host');
                   11057:             }
1.955     raeburn  11058:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11059:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11060:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11061:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11062:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11063:             } else {
                   11064:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11065:             }
1.605     matthew  11066:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11067:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11068:                 @listing_results = split(/:/,$listing);
                   11069:             } else {
                   11070:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11071:             }
1.1135    raeburn  11072:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11073:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11074:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11075:                 return ([],$listing);
                   11076:             } else {
                   11077:                 return (\@listing_results);
1.1135    raeburn  11078:             }
1.955     raeburn  11079:         } elsif(!$alternateRoot) {
1.1136    raeburn  11080:             my (%allusers,%listerror);
1.841     albertel 11081: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11082:  	    foreach my $tryserver (keys(%servers)) {
                   11083:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11084:                                   &escape($udom),$tryserver);
                   11085:                 if ($listing eq 'unknown_cmd') {
                   11086: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11087: 				      $udom, $tryserver);
                   11088:                 } else {
                   11089:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11090:                 }
1.841     albertel 11091: 		if ($listing eq 'unknown_cmd') {
                   11092: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11093: 				      $udom, $tryserver);
                   11094: 		    @listing_results = split(/:/,$listing);
                   11095: 		} else {
                   11096: 		    @listing_results =
                   11097: 			map { &unescape($_); } split(/:/,$listing);
                   11098: 		}
1.1136    raeburn  11099:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11100:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11101:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11102:                     $listerror{$tryserver} = $listing;
                   11103:                 } else {
1.841     albertel 11104: 		    foreach my $line (@listing_results) {
                   11105: 			my ($entry) = split(/&/,$line,2);
                   11106: 			$allusers{$entry} = 1;
                   11107: 		    }
                   11108: 		}
1.253     stredwic 11109:             }
1.1136    raeburn  11110:             my @alluserslist=();
1.800     albertel 11111:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11112:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11113:             }
1.1172.2.80  raeburn  11114:             if (!%listerror) {
                   11115:                 # no errors
                   11116:                 return (\@alluserslist);
                   11117:             } elsif (scalar(keys(%servers)) == 1) {
                   11118:                 # one library server, one error
                   11119:                 my ($key) = keys(%listerror);
                   11120:                 return (\@alluserslist, $listerror{$key});
                   11121:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11122:                 # con_lost indicates that we might miss data from at least one
                   11123:                 # library server
                   11124:                 return (\@alluserslist, 'con_lost');
                   11125:             } else {
                   11126:                 # multiple library servers and no con_lost -> data should be
                   11127:                 # complete.
                   11128:                 return (\@alluserslist);
                   11129:             }
                   11130: 
1.253     stredwic 11131:         } else {
1.1136    raeburn  11132:             return ([],'missing username');
1.253     stredwic 11133:         }
1.955     raeburn  11134:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11135:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11136:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11137:         return (\@all_domains);
1.955     raeburn  11138:     } else {
1.1136    raeburn  11139:         return ([],'missing domain');
1.275     stredwic 11140:     }
                   11141: }
                   11142: 
                   11143: # --------------------------------------------- GetFileTimestamp
                   11144: # This function utilizes dirlist and returns the date stamp for
                   11145: # when it was last modified.  It will also return an error of -1
                   11146: # if an error occurs
                   11147: 
                   11148: sub GetFileTimestamp {
1.955     raeburn  11149:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11150:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11151:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11152:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11153:                                     undef,$getuserdir);
                   11154:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11155:         return -1;
                   11156:     }
                   11157:     if (ref($fileref) eq 'ARRAY') {
                   11158:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11159:         # @stats contains first the filename, then the stat output
                   11160:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11161:     } else {
                   11162:         return -1;
1.253     stredwic 11163:     }
1.26      www      11164: }
                   11165: 
1.712     albertel 11166: sub stat_file {
                   11167:     my ($uri) = @_;
1.787     albertel 11168:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11169: 
1.955     raeburn  11170:     my ($udom,$uname,$file);
1.712     albertel 11171:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11172: 	($udom,$uname,$file) =
1.811     albertel 11173: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11174: 	$file = 'userfiles/'.$file;
                   11175:     }
                   11176:     if ($uri =~ m-^/res/-) {
                   11177: 	($udom,$uname) = 
1.807     albertel 11178: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11179: 	$file = $uri;
                   11180:     }
                   11181: 
                   11182:     if (!$udom || !$uname || !$file) {
                   11183: 	# unable to handle the uri
                   11184: 	return ();
                   11185:     }
1.956     raeburn  11186:     my $getpropath;
                   11187:     if ($file =~ /^userfiles\//) {
                   11188:         $getpropath = 1;
                   11189:     }
1.1136    raeburn  11190:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11191:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11192:         return ();
                   11193:     } else {
                   11194:         if (ref($listref) eq 'ARRAY') {
                   11195:             my @stats = split('&',$listref->[0]);
                   11196: 	    shift(@stats); #filename is first
                   11197: 	    return @stats;
                   11198:         }
1.712     albertel 11199:     }
                   11200:     return ();
                   11201: }
                   11202: 
1.26      www      11203: # -------------------------------------------------------- Value of a Condition
                   11204: 
1.713     albertel 11205: # gets the value of a specific preevaluated condition
                   11206: #    stored in the string  $env{user.state.<cid>}
                   11207: # or looks up a condition reference in the bighash and if if hasn't
                   11208: # already been evaluated recurses into docondval to get the value of
                   11209: # the condition, then memoizing it to 
                   11210: #   $env{user.state.<cid>.<condition>}
1.40      www      11211: sub directcondval {
                   11212:     my $number=shift;
1.620     albertel 11213:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11214: 	&Apache::lonuserstate::evalstate();
                   11215:     }
1.713     albertel 11216:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11217: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11218:     } elsif ($number =~ /^_/) {
                   11219: 	my $sub_condition;
                   11220: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11221: 		&GDBM_READER(),0640)) {
                   11222: 	    $sub_condition=$bighash{'conditions'.$number};
                   11223: 	    untie(%bighash);
                   11224: 	}
                   11225: 	my $value = &docondval($sub_condition);
1.949     raeburn  11226: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11227: 	return $value;
                   11228:     }
1.620     albertel 11229:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11230:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11231:     } else {
                   11232:        return 2;
                   11233:     }
                   11234: }
                   11235: 
1.713     albertel 11236: # get the collection of conditions for this resource
1.26      www      11237: sub condval {
                   11238:     my $condidx=shift;
1.54      www      11239:     my $allpathcond='';
1.713     albertel 11240:     foreach my $cond (split(/\|/,$condidx)) {
                   11241: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11242: 	    $allpathcond.=
                   11243: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11244: 	}
1.191     harris41 11245:     }
1.54      www      11246:     $allpathcond=~s/\|$//;
1.713     albertel 11247:     return &docondval($allpathcond);
                   11248: }
                   11249: 
                   11250: #evaluates an expression of conditions
                   11251: sub docondval {
                   11252:     my ($allpathcond) = @_;
                   11253:     my $result=0;
                   11254:     if ($env{'request.course.id'}
                   11255: 	&& defined($allpathcond)) {
                   11256: 	my $operand='|';
                   11257: 	my @stack;
                   11258: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11259: 	    if ($chunk eq '(') {
                   11260: 		push @stack,($operand,$result);
                   11261: 	    } elsif ($chunk eq ')') {
                   11262: 		my $before=pop @stack;
                   11263: 		if (pop @stack eq '&') {
                   11264: 		    $result=$result>$before?$before:$result;
                   11265: 		} else {
                   11266: 		    $result=$result>$before?$result:$before;
                   11267: 		}
                   11268: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11269: 		$operand=$chunk;
                   11270: 	    } else {
                   11271: 		my $new=directcondval($chunk);
                   11272: 		if ($operand eq '&') {
                   11273: 		    $result=$result>$new?$new:$result;
                   11274: 		} else {
                   11275: 		    $result=$result>$new?$result:$new;
                   11276: 		}
                   11277: 	    }
                   11278: 	}
1.26      www      11279:     }
                   11280:     return $result;
1.421     albertel 11281: }
                   11282: 
                   11283: # ---------------------------------------------------- Devalidate courseresdata
                   11284: 
                   11285: sub devalidatecourseresdata {
                   11286:     my ($coursenum,$coursedomain)=@_;
                   11287:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11288:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11289: }
                   11290: 
1.763     www      11291: 
1.200     www      11292: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11293: #
                   11294: #  Parameters:
                   11295: #      $coursenum    - Number of the course.
                   11296: #      $coursedomain - Domain at which the course was created.
                   11297: #  Returns:
                   11298: #     A hash of the course parameters along (I think) with timestamps
                   11299: #     and version info.
1.877     foxr     11300: 
1.624     albertel 11301: sub get_courseresdata {
                   11302:     my ($coursenum,$coursedomain)=@_;
1.200     www      11303:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11304:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11305:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11306:     my %dumpreply;
1.417     albertel 11307:     unless (defined($cached)) {
1.624     albertel 11308: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11309: 	$result=\%dumpreply;
1.251     albertel 11310: 	my ($tmp) = keys(%dumpreply);
                   11311: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11312: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11313: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11314: 	    return $tmp;
1.416     albertel 11315: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11316: 	    $result=undef;
1.599     albertel 11317: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11318: 	}
                   11319:     }
1.624     albertel 11320:     return $result;
                   11321: }
                   11322: 
1.633     albertel 11323: sub devalidateuserresdata {
                   11324:     my ($uname,$udom)=@_;
                   11325:     my $hashid="$udom:$uname";
                   11326:     &devalidate_cache_new('userres',$hashid);
                   11327: }
                   11328: 
1.624     albertel 11329: sub get_userresdata {
                   11330:     my ($uname,$udom)=@_;
                   11331:     #most student don\'t have any data set, check if there is some data
                   11332:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11333: 
                   11334:     my $hashid="$udom:$uname";
                   11335:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11336:     if (!defined($cached)) {
                   11337: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11338: 	$result=\%resourcedata;
                   11339: 	&do_cache_new('userres',$hashid,$result,600);
                   11340:     }
                   11341:     my ($tmp)=keys(%$result);
                   11342:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11343: 	return $result;
                   11344:     }
                   11345:     #error 2 occurs when the .db doesn't exist
                   11346:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11347:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11348: 	    &logthis("<font color=\"blue\">WARNING:".
                   11349: 		     " Trying to get resource data for ".
                   11350: 		     $uname." at ".$udom.": ".
                   11351: 		     $tmp."</font>");
                   11352:         }
1.624     albertel 11353:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11354: 	#&EXT_cache_set($udom,$uname);
                   11355: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11356: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11357:     }
                   11358:     return $tmp;
                   11359: }
1.879     foxr     11360: #----------------------------------------------- resdata - return resource data
                   11361: #  Purpose:
                   11362: #    Return resource data for either users or for a course.
                   11363: #  Parameters:
                   11364: #     $name      - Course/user name.
                   11365: #     $domain    - Name of the domain the user/course is registered on.
1.1172.2.118.  .1(raebu 11366:20): #     $type      - Type of thing $name is (must be 'course' or 'user')
1.879     foxr     11367: #     @which     - Array of names of resources desired.
                   11368: #  Returns:
                   11369: #     The value of the first reasource in @which that is found in the
                   11370: #     resource hash.
                   11371: #  Exceptional Conditions:
                   11372: #     If the $type passed in is not valid (not the string 'course' or 
                   11373: #     'user', an undefined  reference is returned.
                   11374: #     If none of the resources are found, an undef is returned
1.624     albertel 11375: sub resdata {
                   11376:     my ($name,$domain,$type,@which)=@_;
                   11377:     my $result;
                   11378:     if ($type eq 'course') {
                   11379: 	$result=&get_courseresdata($name,$domain);
                   11380:     } elsif ($type eq 'user') {
                   11381: 	$result=&get_userresdata($name,$domain);
                   11382:     }
                   11383:     if (!ref($result)) { return $result; }    
1.251     albertel 11384:     foreach my $item (@which) {
1.1172.2.118.  .8(raebu 11385:20): 	if (defined($result->{$item->[0]})) {
                   11386:20): 	    return [$result->{$item->[0]},$item->[1]];
          .1(raebu 11387:20):         }
1.250     albertel 11388:     }
1.291     albertel 11389:     return undef;
1.200     www      11390: }
                   11391: 
1.1172.2.118.  .10(raeb 11392:-20): sub get_domain_lti {
                   11393:-20):     my ($cdom,$context) = @_;
                   11394:-20):     my ($name,%lti);
                   11395:-20):     if ($context eq 'consumer') {
                   11396:-20):         $name = 'ltitools';
                   11397:-20):     } elsif ($context eq 'provider') {
                   11398:-20):         $name = 'lti';
                   11399:-20):     } else {
                   11400:-20):         return %lti;
                   11401:-20):     }
                   11402:-20):     my ($result,$cached)=&is_cached_new($name,$cdom);
          .1(raebu 11403:20):     if (defined($cached)) {
                   11404:20):         if (ref($result) eq 'HASH') {
          .10(raeb 11405:-20):             %lti = %{$result};
          .1(raebu 11406:20):         }
                   11407:20):     } else {
          .10(raeb 11408:-20):         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   11409:-20):         if (ref($domconfig{$name}) eq 'HASH') {
                   11410:-20):             %lti = %{$domconfig{$name}};
                   11411:-20):             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
                   11412:-20):             if (ref($encdomconfig{$name}) eq 'HASH') {
                   11413:-20):                 foreach my $id (keys(%lti)) {
                   11414:-20):                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
          .1(raebu 11415:20):                         foreach my $item ('key','secret') {
          .10(raeb 11416:-20):                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
          .1(raebu 11417:20):                         }
                   11418:20):                     }
                   11419:20):                 }
                   11420:20):             }
                   11421:20):         }
                   11422:20):         my $cachetime = 24*60*60;
          .10(raeb 11423:-20):         &do_cache_new($name,$cdom,\%lti,$cachetime);
          .1(raebu 11424:20):     }
          .10(raeb 11425:-20):     return %lti;
          .1(raebu 11426:20): }
                   11427:20): 
1.1172.2.31  raeburn  11428: sub get_numsuppfiles {
                   11429:     my ($cnum,$cdom,$ignorecache)=@_;
                   11430:     my $hashid=$cnum.':'.$cdom;
                   11431:     my ($suppcount,$cached);
                   11432:     unless ($ignorecache) {
                   11433:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11434:     }
                   11435:     unless (defined($cached)) {
                   11436:         my $chome=&homeserver($cnum,$cdom);
                   11437:         unless ($chome eq 'no_host') {
                   11438:             ($suppcount,my $errors) = (0,0);
                   11439:             my $suppmap = 'supplemental.sequence';
                   11440:             ($suppcount,$errors) =
                   11441:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11442:         }
                   11443:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11444:     }
                   11445:     return $suppcount;
                   11446: }
                   11447: 
1.379     matthew  11448: #
                   11449: # EXT resource caching routines
                   11450: #
                   11451: 
                   11452: sub clear_EXT_cache_status {
1.383     albertel 11453:     &delenv('cache.EXT.');
1.379     matthew  11454: }
                   11455: 
                   11456: sub EXT_cache_status {
                   11457:     my ($target_domain,$target_user) = @_;
1.383     albertel 11458:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11459:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11460:         # We know already the user has no data
                   11461:         return 1;
                   11462:     } else {
                   11463:         return 0;
                   11464:     }
                   11465: }
                   11466: 
                   11467: sub EXT_cache_set {
                   11468:     my ($target_domain,$target_user) = @_;
1.383     albertel 11469:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11470:     #&appenv({$cachename => time});
1.379     matthew  11471: }
                   11472: 
1.28      www      11473: # --------------------------------------------------------- Value of a Variable
1.58      www      11474: sub EXT {
1.715     albertel 11475: 
1.1172.2.28  raeburn  11476:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11477:     unless ($varname) { return ''; }
1.218     albertel 11478:     #get real user name/domain, courseid and symb
                   11479:     my $courseid;
1.359     albertel 11480:     my $publicuser;
1.427     www      11481:     if ($symbparm) {
                   11482: 	$symbparm=&get_symb_from_alias($symbparm);
                   11483:     }
1.218     albertel 11484:     if (!($uname && $udom)) {
1.790     albertel 11485:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11486:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11487:     } else {
1.620     albertel 11488: 	$courseid=$env{'request.course.id'};
1.218     albertel 11489:     }
1.48      www      11490:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11491:     my $rest;
1.320     albertel 11492:     if (defined($therest[0])) {
1.48      www      11493:        $rest=join('.',@therest);
                   11494:     } else {
                   11495:        $rest='';
                   11496:     }
1.320     albertel 11497: 
1.57      www      11498:     my $qualifierrest=$qualifier;
                   11499:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11500:     my $spacequalifierrest=$space;
                   11501:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11502:     if ($realm eq 'user') {
1.48      www      11503: # --------------------------------------------------------------- user.resource
                   11504: 	if ($space eq 'resource') {
1.651     albertel 11505: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11506: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11507: 		 &&
1.744     albertel 11508: 		 ($symbparm eq &symbread()) ) {	
                   11509: 		# if we are in the middle of processing the resource the
                   11510: 		# get the value we are planning on committing
                   11511:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11512:                     return $Apache::lonhomework::results{$qualifierrest};
                   11513:                 } else {
                   11514:                     return $Apache::lonhomework::history{$qualifierrest};
                   11515:                 }
1.335     albertel 11516: 	    } else {
1.359     albertel 11517: 		my %restored;
1.620     albertel 11518: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11519: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11520: 		} else {
                   11521: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11522: 		}
1.335     albertel 11523: 		return $restored{$qualifierrest};
                   11524: 	    }
1.48      www      11525: # ----------------------------------------------------------------- user.access
                   11526:         } elsif ($space eq 'access') {
1.218     albertel 11527: 	    # FIXME - not supporting calls for a specific user
1.48      www      11528:             return &allowed($qualifier,$rest);
                   11529: # ------------------------------------------ user.preferences, user.environment
                   11530:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11531: 	    if (($uname eq $env{'user.name'}) &&
                   11532: 		($udom eq $env{'user.domain'})) {
                   11533: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11534: 	    } else {
1.359     albertel 11535: 		my %returnhash;
                   11536: 		if (!$publicuser) {
                   11537: 		    %returnhash=&userenvironment($udom,$uname,
                   11538: 						 $qualifierrest);
                   11539: 		}
1.218     albertel 11540: 		return $returnhash{$qualifierrest};
                   11541: 	    }
1.48      www      11542: # ----------------------------------------------------------------- user.course
                   11543:         } elsif ($space eq 'course') {
1.218     albertel 11544: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11545:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11546: # ------------------------------------------------------------------- user.role
                   11547:         } elsif ($space eq 'role') {
1.218     albertel 11548: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11549:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11550:             if ($qualifier eq 'value') {
                   11551: 		return $role;
                   11552:             } elsif ($qualifier eq 'extent') {
                   11553:                 return $where;
                   11554:             }
                   11555: # ----------------------------------------------------------------- user.domain
                   11556:         } elsif ($space eq 'domain') {
1.218     albertel 11557:             return $udom;
1.48      www      11558: # ------------------------------------------------------------------- user.name
                   11559:         } elsif ($space eq 'name') {
1.218     albertel 11560:             return $uname;
1.48      www      11561: # ---------------------------------------------------- Any other user namespace
1.29      www      11562:         } else {
1.359     albertel 11563: 	    my %reply;
                   11564: 	    if (!$publicuser) {
                   11565: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11566: 	    }
                   11567: 	    return $reply{$qualifierrest};
1.48      www      11568:         }
1.236     www      11569:     } elsif ($realm eq 'query') {
                   11570: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11571:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11572: 						[$spacequalifierrest]);
1.620     albertel 11573: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11574:    } elsif ($realm eq 'request') {
1.48      www      11575: # ------------------------------------------------------------- request.browser
                   11576:         if ($space eq 'browser') {
1.1145    bisitz   11577:             return $env{'browser.'.$qualifier};
1.57      www      11578: # ------------------------------------------------------------ request.filename
                   11579:         } else {
1.620     albertel 11580:             return $env{'request.'.$spacequalifierrest};
1.29      www      11581:         }
1.28      www      11582:     } elsif ($realm eq 'course') {
1.48      www      11583: # ---------------------------------------------------------- course.description
1.620     albertel 11584:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11585:     } elsif ($realm eq 'resource') {
1.165     www      11586: 
1.620     albertel 11587: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11588: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11589: 	}
1.693     albertel 11590: 
1.1172.2.30  raeburn  11591:         if ($qualifier eq '') {
                   11592: 	    if ($space eq 'title') {
                   11593: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11594: 	        return &gettitle($symbparm);
                   11595: 	    }
1.693     albertel 11596: 	
1.1172.2.30  raeburn  11597: 	    if ($space eq 'map') {
                   11598: 	        my ($map) = &decode_symb($symbparm);
                   11599: 	        return &symbread($map);
                   11600: 	    }
                   11601:             if ($space eq 'maptitle') {
                   11602:                 my ($map) = &decode_symb($symbparm);
                   11603:                 return &gettitle($map);
                   11604:             }
                   11605: 	    if ($space eq 'filename') {
                   11606: 	        if ($symbparm) {
                   11607: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11608: 	        }
                   11609: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11610: 	    }
1.1172.2.30  raeburn  11611: 
                   11612:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11613:                 if ($space eq 'visibleparts') {
                   11614:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11615:                     my $item;
                   11616:                     if (ref($navmap)) {
                   11617:                         my $res = $navmap->getBySymb($symbparm);
                   11618:                         my $parts = $res->parts();
                   11619:                         if (ref($parts) eq 'ARRAY') {
                   11620:                             $item = join(',',@{$parts});
                   11621:                         }
                   11622:                         undef($navmap);
                   11623:                     }
                   11624:                     return $item;
                   11625:                 }
                   11626:             }
                   11627:         }
1.693     albertel 11628: 
                   11629: 	my ($section, $group, @groups);
1.593     albertel 11630: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  11631:         if (($courseid eq '') && ($cid)) {
                   11632:             $courseid = $cid;
                   11633:         }
                   11634: 	if (($symbparm && $courseid) && 
                   11635: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      11636: 
1.218     albertel 11637: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11638: 
1.60      www      11639: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11640: 	    my $symbp=$symbparm;
1.735     albertel 11641: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11642: 
                   11643: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   11644: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   11645: 
1.620     albertel 11646: 	    if (($env{'user.name'} eq $uname) &&
                   11647: 		($env{'user.domain'} eq $udom)) {
                   11648: 		$section=$env{'request.course.sec'};
1.733     raeburn  11649:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11650:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11651: 	    } else {
1.539     albertel 11652: 		if (! defined($usection)) {
1.551     albertel 11653: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11654: 		} else {
                   11655: 		    $section = $usection;
                   11656: 		}
1.733     raeburn  11657:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11658: 	    }
                   11659: 
                   11660: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11661: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   11662: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11663: 
1.593     albertel 11664: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11665: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 11666: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11667: 
1.60      www      11668: # ----------------------------------------------------------- first, check user
1.624     albertel 11669: 
                   11670: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 11671: 				       ([$courselevelr,'resource'],
                   11672: 					[$courselevelm,'map'     ],
                   11673: 					[$courselevel, 'course'  ]));
1.931     albertel 11674: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11675: 
1.594     albertel 11676: # ------------------------------------------------ second, check some of course
1.684     raeburn  11677:             my $coursereply;
1.691     raeburn  11678:             if (@groups > 0) {
                   11679:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   11680:                                        $mapparm,$spacequalifierrest);
1.927     albertel 11681:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  11682:             }
1.96      www      11683: 
1.684     raeburn  11684: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11685: 				  $env{'course.'.$courseid.'.domain'},
                   11686: 				  'course',
                   11687: 				  ([$seclevelr,   'resource'],
                   11688: 				   [$seclevelm,   'map'     ],
                   11689: 				   [$seclevel,    'course'  ],
                   11690: 				   [$courselevelr,'resource']));
                   11691: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11692: 
1.60      www      11693: # ------------------------------------------------------ third, check map parms
1.218     albertel 11694: 	    my %parmhash=();
                   11695: 	    my $thisparm='';
                   11696: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11697: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11698: 		    &GDBM_READER(),0640)) {
1.218     albertel 11699: 		$thisparm=$parmhash{$symbparm};
                   11700: 		untie(%parmhash);
                   11701: 	    }
1.927     albertel 11702: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11703: 	}
1.594     albertel 11704: # ------------------------------------------ fourth, look in resource metadata
1.71      www      11705: 
1.218     albertel 11706: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 11707: 	my $filename;
                   11708: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11709: 	if ($symbparm) {
1.409     www      11710: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11711: 	} else {
1.620     albertel 11712: 	    $filename=$env{'request.filename'};
1.282     albertel 11713: 	}
                   11714: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 11715: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 11716: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 11717: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11718: 
1.927     albertel 11719: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 11720: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11721: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11722: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11723: 				     $env{'course.'.$courseid.'.domain'},
                   11724: 				     'course',
1.927     albertel 11725: 				     ([$courselevelm,'map'   ],
                   11726: 				      [$courselevel, 'course']));
                   11727: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11728: 	}
1.145     www      11729: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11730: 	unless ($space eq '0') {
1.336     albertel 11731: 	    my @parts=split(/_/,$space);
                   11732: 	    my $id=pop(@parts);
                   11733: 	    my $part=join('_',@parts);
                   11734: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11735: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11736: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11737: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11738: 	}
1.395     albertel 11739: 	if ($recurse) { return undef; }
                   11740: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11741: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11742: # ---------------------------------------------------- Any other user namespace
                   11743:     } elsif ($realm eq 'environment') {
                   11744: # ----------------------------------------------------------------- environment
1.620     albertel 11745: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11746: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11747: 	} else {
1.770     albertel 11748: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11749: 		return '';
                   11750: 	    }
1.219     albertel 11751: 	    my %returnhash=&userenvironment($udom,$uname,
                   11752: 					    $spacequalifierrest);
                   11753: 	    return $returnhash{$spacequalifierrest};
                   11754: 	}
1.28      www      11755:     } elsif ($realm eq 'system') {
1.48      www      11756: # ----------------------------------------------------------------- system.time
                   11757: 	if ($space eq 'time') {
                   11758: 	    return time;
                   11759:         }
1.696     albertel 11760:     } elsif ($realm eq 'server') {
                   11761: # ----------------------------------------------------------------- system.time
                   11762: 	if ($space eq 'name') {
                   11763: 	    return $ENV{'SERVER_NAME'};
                   11764:         }
1.28      www      11765:     }
1.48      www      11766:     return '';
1.61      www      11767: }
                   11768: 
1.927     albertel 11769: sub get_reply {
                   11770:     my ($reply_value) = @_;
1.940     raeburn  11771:     if (ref($reply_value) eq 'ARRAY') {
                   11772:         if (wantarray) {
                   11773: 	    return @$reply_value;
                   11774:         }
                   11775:         return $reply_value->[0];
                   11776:     } else {
                   11777:         return $reply_value;
1.927     albertel 11778:     }
                   11779: }
                   11780: 
1.691     raeburn  11781: sub check_group_parms {
                   11782:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   11783:     my @groupitems = ();
                   11784:     my $resultitem;
1.927     albertel 11785:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  11786:     foreach my $group (@{$groups}) {
                   11787:         foreach my $level (@levels) {
1.927     albertel 11788:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11789:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11790:         }
                   11791:     }
                   11792:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11793:                             $env{'course.'.$courseid.'.domain'},
                   11794:                                      'course',@groupitems);
                   11795:     return $coursereply;
                   11796: }
                   11797: 
                   11798: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11799:     my ($courseid,@groups) = @_;
                   11800:     @groups = sort(@groups);
1.691     raeburn  11801:     return @groups;
                   11802: }
                   11803: 
1.395     albertel 11804: sub packages_tab_default {
                   11805:     my ($uri,$varname)=@_;
                   11806:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11807: 
                   11808:     my (@extension,@specifics,$do_default);
                   11809:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11810: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11811: 	if ($pack_type eq 'default') {
                   11812: 	    $do_default=1;
                   11813: 	} elsif ($pack_type eq 'extension') {
                   11814: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11815: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11816: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11817: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11818: 	}
                   11819:     }
                   11820:     # first look for a package that matches the requested part id
                   11821:     foreach my $package (@specifics) {
                   11822: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11823: 	next if ($pack_part ne $part);
                   11824: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11825: 	    return $packagetab{"$pack_type&$name&default"};
                   11826: 	}
                   11827:     }
                   11828:     # look for any possible matching non extension_ package
                   11829:     foreach my $package (@specifics) {
                   11830: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11831: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11832: 	    return $packagetab{"$pack_type&$name&default"};
                   11833: 	}
1.585     albertel 11834: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11835: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11836: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11837: 	}
                   11838:     }
1.738     albertel 11839:     # look for any posible extension_ match
                   11840:     foreach my $package (@extension) {
                   11841: 	my ($package,$pack_type)=@{$package};
                   11842: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11843: 	    return $packagetab{"$pack_type&$name&default"};
                   11844: 	}
                   11845: 	if (defined($packagetab{$package."&$name&default"})) {
                   11846: 	    return $packagetab{$package."&$name&default"};
                   11847: 	}
                   11848:     }
                   11849:     # look for a global default setting
                   11850:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11851: 	return $packagetab{"default&$name&default"};
                   11852:     }
1.395     albertel 11853:     return undef;
                   11854: }
                   11855: 
1.334     albertel 11856: sub add_prefix_and_part {
                   11857:     my ($prefix,$part)=@_;
                   11858:     my $keyroot;
                   11859:     if (defined($prefix) && $prefix !~ /^__/) {
                   11860: 	# prefix that has a part already
                   11861: 	$keyroot=$prefix;
                   11862:     } elsif (defined($prefix)) {
                   11863: 	# prefix that is missing a part
                   11864: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11865:     } else {
                   11866: 	# no prefix at all
                   11867: 	if (defined($part)) { $keyroot='_'.$part; }
                   11868:     }
                   11869:     return $keyroot;
                   11870: }
                   11871: 
1.71      www      11872: # ---------------------------------------------------------------- Get metadata
                   11873: 
1.599     albertel 11874: my %metaentry;
1.1070    www      11875: my %importedpartids;
1.1172.2.99  raeburn  11876: my %importedrespids;
1.71      www      11877: sub metadata {
1.176     www      11878:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11879:     $uri=&declutter($uri);
1.288     albertel 11880:     # if it is a non metadata possible uri return quickly
1.529     albertel 11881:     if (($uri eq '') || 
                   11882: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.118.  .1(raebu 11883:20): 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  11884:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11885: 	return undef;
                   11886:     }
1.1172.2.49  raeburn  11887:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11888: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11889: 	return undef;
1.288     albertel 11890:     }
1.73      www      11891:     my $filename=$uri;
                   11892:     $uri=~s/\.meta$//;
1.172     www      11893: #
                   11894: # Is the metadata already cached?
1.177     www      11895: # Look at timestamp of caching
1.172     www      11896: # Everything is cached by the main uri, libraries are never directly cached
                   11897: #
1.428     albertel 11898:     if (!defined($liburi)) {
1.599     albertel 11899: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11900: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11901:     }
                   11902:     {
1.1069    www      11903: # Imported parts would go here
1.1172.2.99  raeburn  11904:         my @origfiletagids=();
1.1069    www      11905:         my $importedparts=0;
1.1172.2.99  raeburn  11906: 
                   11907: # Imported responseids would go here
                   11908:         my $importedresponses=0;
1.172     www      11909: #
                   11910: # Is this a recursive call for a library?
                   11911: #
1.599     albertel 11912: #	if (! exists($metacache{$uri})) {
                   11913: #	    $metacache{$uri}={};
                   11914: #	}
1.924     albertel 11915: 	my $cachetime = 60*60;
1.171     www      11916:         if ($liburi) {
                   11917: 	    $liburi=&declutter($liburi);
                   11918:             $filename=$liburi;
1.401     bowersj2 11919:         } else {
1.599     albertel 11920: 	    &devalidate_cache_new('meta',$uri);
                   11921: 	    undef(%metaentry);
1.401     bowersj2 11922: 	}
1.140     www      11923:         my %metathesekeys=();
1.73      www      11924:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11925: 	my $metastring;
1.1140    www      11926: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11927: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11928: 	    $metastring = 
1.929     albertel 11929: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11930: 					  ('grade_target' => 'meta'));
                   11931: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11932: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11933:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11934: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11935: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11936: 	    $metastring=&getfile($file);
1.489     albertel 11937: 	}
1.208     albertel 11938:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11939:         my $token;
1.140     www      11940:         undef %metathesekeys;
1.71      www      11941:         while ($token=$parser->get_token) {
1.339     albertel 11942: 	    if ($token->[0] eq 'S') {
                   11943: 		if (defined($token->[2]->{'package'})) {
1.172     www      11944: #
                   11945: # This is a package - get package info
                   11946: #
1.339     albertel 11947: 		    my $package=$token->[2]->{'package'};
                   11948: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11949: 		    if (defined($token->[2]->{'id'})) { 
                   11950: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11951: 		    }
1.599     albertel 11952: 		    if ($metaentry{':packages'}) {
                   11953: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11954: 		    } else {
1.599     albertel 11955: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11956: 		    }
1.736     albertel 11957: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11958: 			my $part=$keyroot;
                   11959: 			$part=~s/^\_//;
1.736     albertel 11960: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11961: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11962: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11963: 			    # ignore package.tab specified default values
                   11964:                             # here &package_tab_default() will fetch those
                   11965: 			    if ($subp eq 'default') { next; }
1.736     albertel 11966: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11967: 			    my $unikey;
                   11968: 			    if ($pack =~ /_0$/) {
                   11969: 				$unikey='parameter_0_'.$name;
                   11970: 				$part=0;
                   11971: 			    } else {
                   11972: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11973: 			    }
1.339     albertel 11974: 			    if ($subp eq 'display') {
                   11975: 				$value.=' [Part: '.$part.']';
                   11976: 			    }
1.599     albertel 11977: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11978: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11979: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11980: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11981: 			    }
1.599     albertel 11982: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11983: 				$metaentry{':'.$unikey}=
                   11984: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11985: 			    }
1.339     albertel 11986: 			}
                   11987: 		    }
                   11988: 		} else {
1.172     www      11989: #
                   11990: # This is not a package - some other kind of start tag
1.339     albertel 11991: #
                   11992: 		    my $entry=$token->[1];
1.1068    www      11993: 		    my $unikey='';
1.175     www      11994: 
1.339     albertel 11995: 		    if ($entry eq 'import') {
1.175     www      11996: #
                   11997: # Importing a library here
1.339     albertel 11998: #
1.1067    www      11999:                         my $location=$parser->get_text('/import');
                   12000:                         my $dir=$filename;
                   12001:                         $dir=~s|[^/]*$||;
                   12002:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  12003: 
                   12004:                         my $importid=$token->[2]->{'id'};
1.1068    www      12005:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  12006: #
                   12007: # Check metadata for imported file to
                   12008: # see if it contained response items
                   12009: #
                   12010:                         my %currmetaentry = %metaentry;
                   12011:                         my $libresponseorder = &metadata($location,'responseorder');
                   12012:                         my $origfile;
                   12013:                         if ($libresponseorder ne '') {
                   12014:                             if ($#origfiletagids<0) {
                   12015:                                 undef(%importedrespids);
                   12016:                                 undef(%importedpartids);
                   12017:                             }
                   12018:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   12019:                             if (@{$importedrespids{$importid}} > 0) {
                   12020:                                 $importedresponses = 1;
                   12021: # We need to get the original file and the imported file to get the response order correct
                   12022: # Load and inspect original file
                   12023:                                 if ($#origfiletagids<0) {
                   12024:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12025:                                     $origfile=&getfile($origfilelocation);
                   12026:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12027:                                 }
                   12028:                             }
                   12029:                         }
                   12030: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12031: # hash populated for imported library file
                   12032:                         %metaentry = %currmetaentry;
                   12033:                         undef(%currmetaentry);
1.1068    www      12034:                         if ($importmode eq 'problem') {
1.1069    www      12035: # Import as problem/response
1.1068    www      12036:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12037:                         } elsif ($importmode eq 'part') {
                   12038: # Import as part(s)
1.1069    www      12039:                            $importedparts=1;
                   12040: # We need to get the original file and the imported file to get the part order correct
                   12041: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  12042: # Load and inspect original file if we didn't do that already
                   12043:                            if ($#origfiletagids<0) {
                   12044:                                undef(%importedrespids);
                   12045:                                undef(%importedpartids);
                   12046:                                if ($origfile eq '') {
                   12047:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12048:                                    $origfile=&getfile($origfilelocation);
                   12049:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12050:                                }
1.1070    www      12051:                            }
                   12052: 
1.1069    www      12053: # Load and inspect imported file
                   12054:                            my $impfile=&getfile($location);
                   12055:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12056:                            if ($#impfilepartids>=0) {
                   12057: # This problem had parts
1.1070    www      12058:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12059:                            } else {
                   12060: # Importing by turning a single problem into a problem part
                   12061: # It gets the import-tags ID as part-ID
                   12062:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12063:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12064:                            }
1.1068    www      12065:                         } else {
                   12066: # Normal import
                   12067:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12068:                            if (defined($token->[2]->{'id'})) {
                   12069:                               $unikey.='_'.$token->[2]->{'id'};
                   12070:                            }
1.1067    www      12071:                         }
                   12072: 
1.339     albertel 12073: 			if ($depthcount<20) {
1.736     albertel 12074: 			    my $metadata = 
                   12075: 				&metadata($uri,'keys', $location,$unikey,
                   12076: 					  $depthcount+1);
                   12077: 			    foreach my $meta (split(',',$metadata)) {
                   12078: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12079: 				$metathesekeys{$meta}=1;
1.339     albertel 12080: 			    }
1.1068    www      12081: 			
                   12082:                         }
1.1067    www      12083: 		    } else {
                   12084: #
                   12085: # Not importing, some other kind of non-package, non-library start tag
                   12086: # 
                   12087:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12088:                         if (defined($token->[2]->{'id'})) {
                   12089:                             $unikey.='_'.$token->[2]->{'id'};
                   12090:                         }
1.339     albertel 12091: 			if (defined($token->[2]->{'name'})) { 
                   12092: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12093: 			}
                   12094: 			$metathesekeys{$unikey}=1;
1.736     albertel 12095: 			foreach my $param (@{$token->[3]}) {
                   12096: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12097: 				$token->[2]->{$param};
1.339     albertel 12098: 			}
                   12099: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12100: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12101: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12102: 		 # only ws inside the tag, and not in default, so use default
                   12103: 		 # as value
1.599     albertel 12104: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12105: 			} elsif ( $internaltext =~ /\S/ ) {
                   12106: 		  # something interesting inside the tag
                   12107: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12108: 			} else {
1.908     albertel 12109: 		  # no interesting values, don't set a default
1.339     albertel 12110: 			}
1.172     www      12111: # end of not-a-package not-a-library import
1.339     albertel 12112: 		    }
1.172     www      12113: # end of not-a-package start tag
1.339     albertel 12114: 		}
1.172     www      12115: # the next is the end of "start tag"
1.339     albertel 12116: 	    }
                   12117: 	}
1.483     albertel 12118: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12119: 	$extension = lc($extension);
                   12120: 	if ($extension eq 'htm') { $extension='html'; }
                   12121: 
1.737     albertel 12122: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12123: 	    #no specific packages #how's our extension
                   12124: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12125: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12126: 					 \%metathesekeys);
                   12127: 	}
1.883     albertel 12128: 
                   12129: 	if (!exists($metaentry{':packages'})
                   12130: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12131: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12132: 		#no specific packages well let's get default then
                   12133: 		if ($key!~/^default&/) { next; }
1.488     albertel 12134: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12135: 					     \%metathesekeys);
                   12136: 	    }
                   12137: 	}
1.338     www      12138: # are there custom rights to evaluate
1.599     albertel 12139: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12140: 
1.338     www      12141:     #
                   12142:     # Importing a rights file here
1.339     albertel 12143:     #
                   12144: 	    unless ($depthcount) {
1.599     albertel 12145: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12146: 		my $dir=$filename;
                   12147: 		$dir=~s|[^/]*$||;
                   12148: 		$location=&filelocation($dir,$location);
1.736     albertel 12149: 		my $rights_metadata =
                   12150: 		    &metadata($uri,'keys',$location,'_rights',
                   12151: 			      $depthcount+1);
                   12152: 		foreach my $rights (split(',',$rights_metadata)) {
                   12153: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12154: 		    $metathesekeys{$rights}=1;
1.339     albertel 12155: 		}
                   12156: 	    }
                   12157: 	}
1.737     albertel 12158: 	# uniqifiy package listing
                   12159: 	my %seen;
                   12160: 	my @uniq_packages =
                   12161: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12162: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12163: 
1.1172.2.99  raeburn  12164:         if (($importedresponses) || ($importedparts)) {
                   12165:             if ($importedparts) {
1.1070    www      12166: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  12167:                 $metaentry{':partorder'}='';
                   12168:                 $metathesekeys{'partorder'}=1;
                   12169:             }
                   12170:             if ($importedresponses) {
                   12171: # We had imported responses and need to rebuild responseorder
                   12172:                 $metaentry{':responseorder'}='';
                   12173:                 $metathesekeys{'responseorder'}=1;
                   12174:             }
                   12175:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12176:                 my $origid = $origfiletagids[$index+1];
                   12177:                 if ($origfiletagids[$index] eq 'part') {
                   12178: # Original part, part of the problem
                   12179:                     if ($importedparts) {
                   12180:                         $metaentry{':partorder'}.=','.$origid;
                   12181:                     }
                   12182:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12183:                     if ($importedparts) {
                   12184: # We have imported parts at this position
                   12185:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12186:                     }
                   12187:                     if ($importedresponses) {
                   12188: # We have imported responses at this position
                   12189:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   12190:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   12191:                         }
                   12192:                     }
                   12193:                 } else {
                   12194: # Original response item, part of the problem
                   12195:                     if ($importedresponses) {
                   12196:                         $metaentry{':responseorder'}.=','.$origid;
                   12197:                     }
                   12198:                 }
                   12199:             }
                   12200:             if ($importedparts) {
                   12201:                 $metaentry{':partorder'}=~s/^\,//;
                   12202:             }
                   12203:             if ($importedresponses) {
                   12204:                 $metaentry{':responseorder'}=~s/^\,//;
                   12205:             }
1.1070    www      12206:         }
                   12207: 
1.737     albertel 12208: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12209: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  12210: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 12211: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      12212: # this is the end of "was not already recently cached
1.71      www      12213:     }
1.599     albertel 12214:     return $metaentry{':'.$what};
1.261     albertel 12215: }
                   12216: 
1.488     albertel 12217: sub metadata_create_package_def {
1.483     albertel 12218:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12219:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12220:     if ($subp eq 'default') { next; }
                   12221:     
1.599     albertel 12222:     if (defined($metaentry{':packages'})) {
                   12223: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12224:     } else {
1.599     albertel 12225: 	$metaentry{':packages'}=$package;
1.483     albertel 12226:     }
                   12227:     my $value=$packagetab{$key};
                   12228:     my $unikey;
                   12229:     $unikey='parameter_0_'.$name;
1.599     albertel 12230:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12231:     $$metathesekeys{$unikey}=1;
1.599     albertel 12232:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12233: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12234:     }
1.599     albertel 12235:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12236: 	$metaentry{':'.$unikey}=
                   12237: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12238:     }
                   12239: }
                   12240: 
1.261     albertel 12241: sub metadata_generate_part0 {
                   12242:     my ($metadata,$metacache,$uri) = @_;
                   12243:     my %allnames;
1.737     albertel 12244:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12245: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12246: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12247: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12248: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12249: 	    $allnames{$name}=$part;
                   12250: 	  }
                   12251: 	}
                   12252:     }
                   12253:     foreach my $name (keys(%allnames)) {
                   12254:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12255:       my $key=":parameter_0_$name";
1.261     albertel 12256:       $$metacache{"$key.part"}='0';
                   12257:       $$metacache{"$key.name"}=$name;
1.428     albertel 12258:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12259: 					   $allnames{$name}.'_'.$name.
                   12260: 					   '.type'};
1.428     albertel 12261:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12262: 			     '.display'};
1.644     www      12263:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12264:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12265:       $$metacache{"$key.display"}=$olddis;
                   12266:     }
1.71      www      12267: }
                   12268: 
1.764     albertel 12269: # ------------------------------------------------------ Devalidate title cache
                   12270: 
                   12271: sub devalidate_title_cache {
                   12272:     my ($url)=@_;
                   12273:     if (!$env{'request.course.id'}) { return; }
                   12274:     my $symb=&symbread($url);
                   12275:     if (!$symb) { return; }
                   12276:     my $key=$env{'request.course.id'}."\0".$symb;
                   12277:     &devalidate_cache_new('title',$key);
                   12278: }
                   12279: 
1.1014    droeschl 12280: # ------------------------------------------------- Get the title of a course
                   12281: 
                   12282: sub current_course_title {
                   12283:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12284: }
1.301     www      12285: # ------------------------------------------------- Get the title of a resource
                   12286: 
                   12287: sub gettitle {
                   12288:     my $urlsymb=shift;
                   12289:     my $symb=&symbread($urlsymb);
1.534     albertel 12290:     if ($symb) {
1.620     albertel 12291: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12292: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12293: 	if (defined($cached)) { 
                   12294: 	    return $result;
                   12295: 	}
1.534     albertel 12296: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12297: 	my $title='';
1.907     albertel 12298: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12299: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12300: 	} else {
                   12301: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12302: 		    &GDBM_READER(),0640)) {
                   12303: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12304: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12305: 		untie(%bighash);
                   12306: 	    }
1.534     albertel 12307: 	}
                   12308: 	$title=~s/\&colon\;/\:/gs;
                   12309: 	if ($title) {
1.1159    www      12310: # Remember both $symb and $title for dynamic metadata
                   12311:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12312:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12313: # Cache this title and then return it
1.599     albertel 12314: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12315: 	}
                   12316: 	$urlsymb=$url;
                   12317:     }
                   12318:     my $title=&metadata($urlsymb,'title');
                   12319:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12320:     return $title;
1.301     www      12321: }
1.613     albertel 12322: 
1.614     albertel 12323: sub get_slot {
                   12324:     my ($which,$cnum,$cdom)=@_;
                   12325:     if (!$cnum || !$cdom) {
1.790     albertel 12326: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12327: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12328: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12329:     }
1.703     albertel 12330:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12331:     my %slotinfo;
                   12332:     if (exists($remembered{$key})) {
                   12333: 	$slotinfo{$which} = $remembered{$key};
                   12334:     } else {
                   12335: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12336: 	&Apache::lonhomework::showhash(%slotinfo);
                   12337: 	my ($tmp)=keys(%slotinfo);
                   12338: 	if ($tmp=~/^error:/) { return (); }
                   12339: 	$remembered{$key} = $slotinfo{$which};
                   12340:     }
1.616     albertel 12341:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12342: 	return %{$slotinfo{$which}};
                   12343:     }
                   12344:     return $slotinfo{$which};
1.614     albertel 12345: }
1.1150    raeburn  12346: 
                   12347: sub get_reservable_slots {
                   12348:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12349:     my $now = time;
                   12350:     my $reservable_info;
                   12351:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12352:     if (exists($remembered{$key})) {
                   12353:         $reservable_info = $remembered{$key};
                   12354:     } else {
                   12355:         my %resv;
                   12356:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12357:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12358:         $reservable_info = \%resv;
                   12359:         $remembered{$key} = $reservable_info;
                   12360:     }
                   12361:     return $reservable_info;
                   12362: }
                   12363: 
                   12364: sub get_course_slots {
                   12365:     my ($cnum,$cdom) = @_;
                   12366:     my $hashid=$cnum.':'.$cdom;
                   12367:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12368:     if (defined($cached)) {
                   12369:         if (ref($result) eq 'HASH') {
                   12370:             return %{$result};
                   12371:         }
                   12372:     } else {
                   12373:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12374:         my ($tmp) = keys(%slots);
                   12375:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12376:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12377:             return %slots;
                   12378:         }
                   12379:     }
                   12380:     return;
                   12381: }
                   12382: 
                   12383: sub devalidate_slots_cache {
                   12384:     my ($cnum,$cdom)=@_;
                   12385:     my $hashid=$cnum.':'.$cdom;
                   12386:     &devalidate_cache_new('allslots',$hashid);
                   12387: }
                   12388: 
1.1172.2.8  raeburn  12389: sub get_coursechange {
                   12390:     my ($cdom,$cnum) = @_;
                   12391:     if ($cdom eq '' || $cnum eq '') {
                   12392:         return unless ($env{'request.course.id'});
                   12393:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12394:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12395:     }
                   12396:     my $hashid=$cdom.'_'.$cnum;
                   12397:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12398:     if ((defined($cached)) && ($change ne '')) {
                   12399:         return $change;
                   12400:     } else {
                   12401:         my %crshash;
                   12402:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12403:         if ($crshash{'internal.contentchange'} eq '') {
                   12404:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12405:             if ($change eq '') {
                   12406:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12407:                 $change = $crshash{'internal.created'};
                   12408:             }
                   12409:         } else {
                   12410:             $change = $crshash{'internal.contentchange'};
                   12411:         }
                   12412:         my $cachetime = 600;
                   12413:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12414:     }
                   12415:     return $change;
                   12416: }
                   12417: 
                   12418: sub devalidate_coursechange_cache {
                   12419:     my ($cnum,$cdom)=@_;
                   12420:     my $hashid=$cnum.':'.$cdom;
                   12421:     &devalidate_cache_new('crschange',$hashid);
                   12422: }
                   12423: 
1.31      www      12424: # ------------------------------------------------- Update symbolic store links
                   12425: 
                   12426: sub symblist {
                   12427:     my ($mapname,%newhash)=@_;
1.438     www      12428:     $mapname=&deversion(&declutter($mapname));
1.31      www      12429:     my %hash;
1.620     albertel 12430:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12431:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12432:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12433: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12434: 		next if ($url eq 'last_known'
                   12435: 			 && $env{'form.no_update_last_known'});
                   12436: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12437: 						    $newhash{$url}->[1],
                   12438: 						    $newhash{$url}->[0]);
1.191     harris41 12439:             }
1.31      www      12440:             if (untie(%hash)) {
                   12441: 		return 'ok';
                   12442:             }
                   12443:         }
                   12444:     }
                   12445:     return 'error';
1.212     www      12446: }
                   12447: 
                   12448: # --------------------------------------------------------------- Verify a symb
                   12449: 
                   12450: sub symbverify {
1.1172.2.11  raeburn  12451:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12452:     my $thisfn=$thisurl;
1.439     www      12453:     $thisfn=&declutter($thisfn);
1.215     www      12454: # direct jump to resource in page or to a sequence - will construct own symbs
                   12455:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12456: # check URL part
1.409     www      12457:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12458: 
1.431     www      12459:     unless ($url eq $thisfn) { return 0; }
1.213     www      12460: 
1.216     www      12461:     $symb=&symbclean($symb);
1.510     www      12462:     $thisurl=&deversion($thisurl);
1.439     www      12463:     $thisfn=&deversion($thisfn);
1.213     www      12464: 
                   12465:     my %bighash;
                   12466:     my $okay=0;
1.431     www      12467: 
1.620     albertel 12468:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12469:                             &GDBM_READER(),0640)) {
1.1032    raeburn  12470:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12471:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  12472:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12473:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12474:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12475:             }
                   12476:         }
                   12477:         my $ids;
1.1172.2.118.  .5(raebu 12478:20):         if ($map =~ m{^uploaded/.+\.page$}) {
                   12479:20):             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13  raeburn  12480:         } else {
                   12481:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12482:         }
1.1102    raeburn  12483:         unless ($ids) {
1.1172.2.13  raeburn  12484:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  12485:             $ids=$bighash{$idkey};
1.216     www      12486:         }
                   12487:         if ($ids) {
                   12488: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  12489:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   12490:                 $symb =~ s/\?.+$//;
                   12491:             }
1.800     albertel 12492: 	    foreach my $id (split(/\,/,$ids)) {
                   12493: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12494:                if (
                   12495:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  12496:    eq $symb) {
1.1172.2.11  raeburn  12497:                    if (ref($encstate)) {
                   12498:                        $$encstate = $bighash{'encrypted_'.$id};
                   12499:                    }
1.1172.2.13  raeburn  12500:                    if (($env{'request.role.adv'}) ||
                   12501:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  12502:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  12503:                        $okay=1;
                   12504:                        last;
                   12505:                    }
                   12506:                }
                   12507:            }
1.216     www      12508:         }
1.213     www      12509: 	untie(%bighash);
                   12510:     }
                   12511:     return $okay;
1.31      www      12512: }
                   12513: 
1.210     www      12514: # --------------------------------------------------------------- Clean-up symb
                   12515: 
                   12516: sub symbclean {
                   12517:     my $symb=shift;
1.568     albertel 12518:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12519: # remove version from map
                   12520:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12521: 
1.210     www      12522: # remove version from URL
                   12523:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12524: 
1.507     www      12525: # remove wrapper
                   12526: 
1.510     www      12527:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12528:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12529:     return $symb;
1.409     www      12530: }
                   12531: 
                   12532: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12533: 
                   12534: sub encode_symb {
                   12535:     my ($map,$resid,$url)=@_;
                   12536:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12537: }
1.409     www      12538: 
                   12539: sub decode_symb {
1.568     albertel 12540:     my $symb=shift;
                   12541:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12542:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12543:     return (&fixversion($map),$resid,&fixversion($url));
                   12544: }
                   12545: 
                   12546: sub fixversion {
                   12547:     my $fn=shift;
1.609     banghart 12548:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12549:     my %bighash;
                   12550:     my $uri=&clutter($fn);
1.620     albertel 12551:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12552: # is this cached?
1.599     albertel 12553:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12554:     if (defined($cached)) { return $result; }
                   12555: # unfortunately not cached, or expired
1.620     albertel 12556:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12557: 	    &GDBM_READER(),0640)) {
                   12558:  	if ($bighash{'version_'.$uri}) {
                   12559:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12560:  	    unless (($version eq 'mostrecent') || 
                   12561: 		    ($version==&getversion($uri))) {
1.440     www      12562:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12563:  	    }
                   12564:  	}
                   12565:  	untie %bighash;
1.413     www      12566:     }
1.599     albertel 12567:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12568: }
                   12569: 
                   12570: sub deversion {
                   12571:     my $url=shift;
                   12572:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12573:     return $url;
1.210     www      12574: }
                   12575: 
1.31      www      12576: # ------------------------------------------------------ Return symb list entry
                   12577: 
                   12578: sub symbread {
1.1172.2.118.  .8(raebu 12579:20):     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
          .9(raebu 12580:20):         $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54  raeburn  12581:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.118.  .9(raebu 12582:20):     if (defined($env{$cache_str})) {
          .8(raebu 12583:20):         unless (ref($possibles) eq 'HASH') {
                   12584:20):             if ($ignorecachednull) {
                   12585:20):                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12586:20):             } else {
                   12587:20):                 return $env{$cache_str};
                   12588:20):             }
1.1172.2.66  raeburn  12589:         }
                   12590:     }
1.242     www      12591: # no filename provided? try from environment
1.1172.2.54  raeburn  12592:     unless ($thisfn) {
1.620     albertel 12593:         if ($env{'request.symb'}) {
1.1172.2.118.  .9(raebu 12594:20):             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13  raeburn  12595:         }
                   12596:         $thisfn=$env{'request.filename'};
1.44      www      12597:     }
1.569     albertel 12598:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12599: # is that filename actually a symb? Verify, clean, and return
                   12600:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12601: 	if (&symbverify($thisfn,$1)) {
1.1172.2.118.  .9(raebu 12602:20): 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12603: 	}
1.242     www      12604:     }
1.44      www      12605:     $thisfn=declutter($thisfn);
1.31      www      12606:     my %hash;
1.37      www      12607:     my %bighash;
                   12608:     my $syval='';
1.620     albertel 12609:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12610:         my $targetfn = $thisfn;
1.609     banghart 12611:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12612:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12613:         }
1.687     albertel 12614: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12615: 	    $targetfn=$1;
                   12616: 	}
1.1172.2.118.  .9(raebu 12617:20):         unless ($ignoresymbdb) {
          .8(raebu 12618:20):             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   12619:20):                           &GDBM_READER(),0640)) {
                   12620:20): 	        $syval=$hash{$targetfn};
                   12621:20):                 untie(%hash);
                   12622:20):             }
          .9(raebu 12623:20):             if ($syval && $checkforblock) {
                   12624:20):                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
          .8(raebu 12625:20):                 if (@blockers) {
                   12626:20):                     $syval='';
                   12627:20):                 }
                   12628:20):             }
1.37      www      12629:         }
                   12630: # ---------------------------------------------------------- There was an entry
                   12631:         if ($syval) {
1.601     albertel 12632: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12633: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12634: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12635: 		    #return $env{$cache_str}='';
1.601     albertel 12636: 		#}    
                   12637: 		#$syval.=$1;
                   12638: 	    #}
1.37      www      12639:         } else {
                   12640: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12641:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12642:                             &GDBM_READER(),0640)) {
1.37      www      12643: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12644:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12645:               unless ($ids) { 
                   12646:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12647:               }
                   12648:               unless ($ids) {
                   12649: # alias?
                   12650: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12651:               }
1.37      www      12652:               if ($ids) {
                   12653: # ------------------------------------------------------------------- Has ID(s)
                   12654:                  my @possibilities=split(/\,/,$ids);
1.39      www      12655:                  if ($#possibilities==0) {
                   12656: # ----------------------------------------------- There is only one possibility
1.37      www      12657: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12658: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12659: 						    $resid,$thisfn);
1.1172.2.66  raeburn  12660:                      if (ref($possibles) eq 'HASH') {
1.1172.2.118.  .8(raebu 12661:20):                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   12662:20):                              $possibles->{$syval} = 1;
                   12663:20):                          }
1.1172.2.66  raeburn  12664:                      }
                   12665:                      if ($checkforblock) {
1.1172.2.118.  .8(raebu 12666:20):                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   12667:20):                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
                   12668:20):                              if (@blockers) {
                   12669:20):                                  $syval = '';
                   12670:20):                                  untie(%bighash);
                   12671:20):                                  return $env{$cache_str}='';
                   12672:20):                              }
1.1172.2.66  raeburn  12673:                          }
                   12674:                      }
                   12675:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      12676: # ------------------------------------------ There is more than one possibility
                   12677:                      my $realpossible=0;
1.800     albertel 12678:                      foreach my $id (@possibilities) {
                   12679: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  12680:                          my $canaccess;
                   12681:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12682:                              $canaccess = 1;
                   12683:                          } else {
                   12684:                              $canaccess = &allowed('bre',$file);
                   12685:                          }
                   12686:                          if ($canaccess) {
                   12687:          		     my ($mapid,$resid)=split(/\./,$id);
                   12688:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12689:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12690:                                                              $resid,$thisfn);
1.1172.2.118.  .8(raebu 12691:20):                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
                   12692:20):                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66  raeburn  12693:                                  if ($checkforblock) {
1.1172.2.118.  .8(raebu 12694:20):                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
                   12695:20):                                      if (@blockers > 0) {
                   12696:20):                                          $syval = '';
                   12697:20):                                      } else {
1.1172.2.66  raeburn  12698:                                          $syval = $poss_syval;
                   12699:                                          $realpossible++;
                   12700:                                      }
                   12701:                                  } else {
                   12702:                                      $syval = $poss_syval;
                   12703:                                      $realpossible++;
                   12704:                                  }
1.1172.2.118.  .8(raebu 12705:20):                                  if ($syval) {
                   12706:20):                                      if (ref($possibles) eq 'HASH') {
                   12707:20):                                          $possibles->{$syval} = 1;
                   12708:20):                                      }
                   12709:20):                                  }
1.1172.2.66  raeburn  12710:                              }
1.39      www      12711: 			 }
1.191     harris41 12712:                      }
1.39      www      12713: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12714:                  } else {
                   12715:                      $syval='';
1.37      www      12716:                  }
                   12717: 	      }
1.1172.2.66  raeburn  12718:               untie(%bighash);
1.481     raeburn  12719:            }
1.31      www      12720:         }
1.62      www      12721:         if ($syval) {
1.1172.2.118.  .9(raebu 12722:20): 	    return $env{$cache_str}=$syval;
1.62      www      12723:         }
1.31      www      12724:     }
1.949     raeburn  12725:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12726:     return $env{$cache_str}='';
1.31      www      12727: }
                   12728: 
                   12729: # ---------------------------------------------------------- Return random seed
                   12730: 
1.32      www      12731: sub numval {
                   12732:     my $txt=shift;
                   12733:     $txt=~tr/A-J/0-9/;
                   12734:     $txt=~tr/a-j/0-9/;
                   12735:     $txt=~tr/K-T/0-9/;
                   12736:     $txt=~tr/k-t/0-9/;
                   12737:     $txt=~tr/U-Z/0-5/;
                   12738:     $txt=~tr/u-z/0-5/;
                   12739:     $txt=~s/\D//g;
1.564     albertel 12740:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12741:     return int($txt);
1.368     albertel 12742: }
                   12743: 
1.484     albertel 12744: sub numval2 {
                   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; }
1.564     albertel 12756:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12757:     return int($total);
                   12758: }
                   12759: 
1.575     albertel 12760: sub numval3 {
                   12761:     use integer;
                   12762:     my $txt=shift;
                   12763:     $txt=~tr/A-J/0-9/;
                   12764:     $txt=~tr/a-j/0-9/;
                   12765:     $txt=~tr/K-T/0-9/;
                   12766:     $txt=~tr/k-t/0-9/;
                   12767:     $txt=~tr/U-Z/0-5/;
                   12768:     $txt=~tr/u-z/0-5/;
                   12769:     $txt=~s/\D//g;
                   12770:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12771:     my $total;
                   12772:     foreach my $val (@txts) { $total+=$val; }
                   12773:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12774:     return $total;
                   12775: }
                   12776: 
1.675     albertel 12777: sub digest {
                   12778:     my ($data)=@_;
                   12779:     my $digest=&Digest::MD5::md5($data);
                   12780:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12781:     my ($e,$f);
                   12782:     {
                   12783:         use integer;
                   12784:         $e=($a+$b);
                   12785:         $f=($c+$d);
                   12786:         if ($_64bit) {
                   12787:             $e=(($e<<32)>>32);
                   12788:             $f=(($f<<32)>>32);
                   12789:         }
                   12790:     }
                   12791:     if (wantarray) {
                   12792: 	return ($e,$f);
                   12793:     } else {
                   12794: 	my $g;
                   12795: 	{
                   12796: 	    use integer;
                   12797: 	    $g=($e+$f);
                   12798: 	    if ($_64bit) {
                   12799: 		$g=(($g<<32)>>32);
                   12800: 	    }
                   12801: 	}
                   12802: 	return $g;
                   12803:     }
                   12804: }
                   12805: 
1.368     albertel 12806: sub latest_rnd_algorithm_id {
1.675     albertel 12807:     return '64bit5';
1.366     albertel 12808: }
1.32      www      12809: 
1.503     albertel 12810: sub get_rand_alg {
                   12811:     my ($courseid)=@_;
1.790     albertel 12812:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12813:     if ($courseid) {
1.620     albertel 12814: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12815:     }
                   12816:     return &latest_rnd_algorithm_id();
                   12817: }
                   12818: 
1.562     albertel 12819: sub validCODE {
                   12820:     my ($CODE)=@_;
                   12821:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12822:     return 0;
                   12823: }
                   12824: 
1.491     albertel 12825: sub getCODE {
1.620     albertel 12826:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12827:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12828: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12829: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12830: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12831:     }
                   12832:     return undef;
                   12833: }
1.1133    foxr     12834: #
                   12835: #  Determines the random seed for a specific context:
                   12836: #
                   12837: # parameters:
                   12838: #   symb      - in course context the symb for the seed.
                   12839: #   course_id - The course id of the form domain_coursenum.
                   12840: #   domain    - Domain for the user.
                   12841: #   course    - Course for the user.
                   12842: #   cenv      - environment of the course.
                   12843: #
                   12844: # NOTE:
                   12845: #   All parameters are picked out of the environment if missing
                   12846: #   or not defined.
                   12847: #   If a symb cannot be determined the current time is used instead.
                   12848: #
                   12849: #  For a given well defined symb, courside, domain, username,
                   12850: #  and course environment, the seed is reproducible.
                   12851: #
1.31      www      12852: sub rndseed {
1.1133    foxr     12853:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12854:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12855:     if (!defined($symb)) {
1.366     albertel 12856: 	unless ($symb=$wsymb) { return time; }
                   12857:     }
1.1146    foxr     12858:     if (!defined $courseid) { 
                   12859: 	$courseid=$wcourseid; 
                   12860:     }
                   12861:     if (!defined $domain) { $domain=$wdomain; }
                   12862:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12863: 
                   12864:     my $which;
                   12865:     if (defined($cenv->{'rndseed'})) {
                   12866: 	$which = $cenv->{'rndseed'};
                   12867:     } else {
                   12868: 	$which =&get_rand_alg($courseid);
                   12869:     }
1.491     albertel 12870:     if (defined(&getCODE())) {
1.675     albertel 12871: 	if ($which eq '64bit5') {
                   12872: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12873: 	} elsif ($which eq '64bit4') {
1.575     albertel 12874: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12875: 	} else {
                   12876: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12877: 	}
1.675     albertel 12878:     } elsif ($which eq '64bit5') {
                   12879: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12880:     } elsif ($which eq '64bit4') {
                   12881: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12882:     } elsif ($which eq '64bit3') {
                   12883: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12884:     } elsif ($which eq '64bit2') {
                   12885: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12886:     } elsif ($which eq '64bit') {
                   12887: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12888:     }
                   12889:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12890: }
                   12891: 
                   12892: sub rndseed_32bit {
                   12893:     my ($symb,$courseid,$domain,$username)=@_;
                   12894:     {
                   12895: 	use integer;
                   12896: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12897: 	my $symbseed=numval($symb) << 22;
                   12898: 	my $namechck=unpack("%32C*",$username) << 17;
                   12899: 	my $nameseed=numval($username) << 12;
                   12900: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12901: 	my $courseseed=unpack("%32C*",$courseid);
                   12902: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12903: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12904: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12905: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12906: 	return $num;
                   12907:     }
                   12908: }
                   12909: 
                   12910: sub rndseed_64bit {
                   12911:     my ($symb,$courseid,$domain,$username)=@_;
                   12912:     {
                   12913: 	use integer;
                   12914: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12915: 	my $symbseed=numval($symb) << 10;
                   12916: 	my $namechck=unpack("%32S*",$username);
                   12917: 	
                   12918: 	my $nameseed=numval($username) << 21;
                   12919: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12920: 	my $courseseed=unpack("%32S*",$courseid);
                   12921: 	
                   12922: 	my $num1=$symbchck+$symbseed+$namechck;
                   12923: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12924: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12925: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12926: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12927: 	return "$num1,$num2";
1.155     albertel 12928:     }
1.366     albertel 12929: }
                   12930: 
1.443     albertel 12931: sub rndseed_64bit2 {
                   12932:     my ($symb,$courseid,$domain,$username)=@_;
                   12933:     {
                   12934: 	use integer;
                   12935: 	# strings need to be an even # of cahracters long, it it is odd the
                   12936:         # last characters gets thrown away
                   12937: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12938: 	my $symbseed=numval($symb) << 10;
                   12939: 	my $namechck=unpack("%32S*",$username.' ');
                   12940: 	
                   12941: 	my $nameseed=numval($username) << 21;
1.501     albertel 12942: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12943: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12944: 	
                   12945: 	my $num1=$symbchck+$symbseed+$namechck;
                   12946: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12947: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12948: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12949: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12950: 	return "$num1,$num2";
                   12951:     }
                   12952: }
                   12953: 
                   12954: sub rndseed_64bit3 {
                   12955:     my ($symb,$courseid,$domain,$username)=@_;
                   12956:     {
                   12957: 	use integer;
                   12958: 	# strings need to be an even # of cahracters long, it it is odd the
                   12959:         # last characters gets thrown away
                   12960: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12961: 	my $symbseed=numval2($symb) << 10;
                   12962: 	my $namechck=unpack("%32S*",$username.' ');
                   12963: 	
                   12964: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12965: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12966: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12967: 	
                   12968: 	my $num1=$symbchck+$symbseed+$namechck;
                   12969: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12970: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12971: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12972: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12973: 	
1.503     albertel 12974: 	return "$num1:$num2";
1.443     albertel 12975:     }
                   12976: }
                   12977: 
1.575     albertel 12978: sub rndseed_64bit4 {
                   12979:     my ($symb,$courseid,$domain,$username)=@_;
                   12980:     {
                   12981: 	use integer;
                   12982: 	# strings need to be an even # of cahracters long, it it is odd the
                   12983:         # last characters gets thrown away
                   12984: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12985: 	my $symbseed=numval3($symb) << 10;
                   12986: 	my $namechck=unpack("%32S*",$username.' ');
                   12987: 	
                   12988: 	my $nameseed=numval3($username) << 21;
                   12989: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12990: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12991: 	
                   12992: 	my $num1=$symbchck+$symbseed+$namechck;
                   12993: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12994: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12995: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12996: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12997: 	
1.575     albertel 12998: 	return "$num1:$num2";
                   12999:     }
                   13000: }
                   13001: 
1.675     albertel 13002: sub rndseed_64bit5 {
                   13003:     my ($symb,$courseid,$domain,$username)=@_;
                   13004:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13005:     return "$num1:$num2";
                   13006: }
                   13007: 
1.366     albertel 13008: sub rndseed_CODE_64bit {
                   13009:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13010:     {
1.366     albertel 13011: 	use integer;
1.443     albertel 13012: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13013: 	my $symbseed=numval2($symb);
1.491     albertel 13014: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13015: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13016: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13017: 	my $num1=$symbseed+$CODEchck;
                   13018: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13019: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13020: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13021: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13022: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13023: 	return "$num1:$num2";
1.366     albertel 13024:     }
                   13025: }
                   13026: 
1.575     albertel 13027: sub rndseed_CODE_64bit4 {
                   13028:     my ($symb,$courseid,$domain,$username)=@_;
                   13029:     {
                   13030: 	use integer;
                   13031: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13032: 	my $symbseed=numval3($symb);
                   13033: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13034: 	my $CODEseed=numval3(&getCODE());
                   13035: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13036: 	my $num1=$symbseed+$CODEchck;
                   13037: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13038: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13039: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13040: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13041: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13042: 	return "$num1:$num2";
                   13043:     }
                   13044: }
                   13045: 
1.675     albertel 13046: sub rndseed_CODE_64bit5 {
                   13047:     my ($symb,$courseid,$domain,$username)=@_;
                   13048:     my $code = &getCODE();
                   13049:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13050:     return "$num1:$num2";
                   13051: }
                   13052: 
1.366     albertel 13053: sub setup_random_from_rndseed {
                   13054:     my ($rndseed)=@_;
1.503     albertel 13055:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  13056: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13057:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13058:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13059:         } else {
                   13060:             &Math::Random::random_set_seed($num1,$num2);
                   13061:         }
1.366     albertel 13062:     } else {
                   13063: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13064:     }
1.36      albertel 13065: }
                   13066: 
1.474     albertel 13067: sub latest_receipt_algorithm_id {
1.835     albertel 13068:     return 'receipt3';
1.474     albertel 13069: }
                   13070: 
1.480     www      13071: sub recunique {
                   13072:     my $fucourseid=shift;
                   13073:     my $unique;
1.835     albertel 13074:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13075: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13076: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13077:     } else {
                   13078: 	$unique=$perlvar{'lonReceipt'};
                   13079:     }
                   13080:     return unpack("%32C*",$unique);
                   13081: }
                   13082: 
                   13083: sub recprefix {
                   13084:     my $fucourseid=shift;
                   13085:     my $prefix;
1.835     albertel 13086:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13087: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13088: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13089:     } else {
                   13090: 	$prefix=$perlvar{'lonHostID'};
                   13091:     }
                   13092:     return unpack("%32C*",$prefix);
                   13093: }
                   13094: 
1.76      www      13095: sub ireceipt {
1.474     albertel 13096:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13097: 
                   13098:     my $return =&recprefix($fucourseid).'-';
                   13099: 
                   13100:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13101: 	$env{'request.state'} eq 'construct') {
                   13102: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13103: 	return $return;
                   13104:     }
                   13105: 
1.76      www      13106:     my $cuname=unpack("%32C*",$funame);
                   13107:     my $cudom=unpack("%32C*",$fudom);
                   13108:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13109:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13110:     my $cunique=&recunique($fucourseid);
1.474     albertel 13111:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13112:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13113: 
1.790     albertel 13114: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13115: 			       
                   13116: 	$return.= ($cunique%$cuname+
                   13117: 		   $cunique%$cudom+
                   13118: 		   $cusymb%$cuname+
                   13119: 		   $cusymb%$cudom+
                   13120: 		   $cucourseid%$cuname+
                   13121: 		   $cucourseid%$cudom+
                   13122: 		   $cpart%$cuname+
                   13123: 		   $cpart%$cudom);
                   13124:     } else {
                   13125: 	$return.= ($cunique%$cuname+
                   13126: 		   $cunique%$cudom+
                   13127: 		   $cusymb%$cuname+
                   13128: 		   $cusymb%$cudom+
                   13129: 		   $cucourseid%$cuname+
                   13130: 		   $cucourseid%$cudom);
                   13131:     }
                   13132:     return $return;
1.76      www      13133: }
                   13134: 
                   13135: sub receipt {
1.474     albertel 13136:     my ($part)=@_;
1.790     albertel 13137:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13138:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13139: }
1.260     ng       13140: 
1.790     albertel 13141: sub whichuser {
                   13142:     my ($passedsymb)=@_;
                   13143:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13144:     if (defined($env{'form.grade_symb'})) {
                   13145: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13146: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13147: 	if (!$allowed &&
                   13148: 	    exists($env{'request.course.sec'}) &&
                   13149: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13150: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13151: 			      '/'.$env{'request.course.sec'});
                   13152: 	}
                   13153: 	if ($allowed) {
                   13154: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13155: 	    $courseid=$tmp_courseid;
                   13156: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13157: 	    ($name)=&get_env_multiple('form.grade_username');
                   13158: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13159: 	}
                   13160:     }
                   13161:     if (!$passedsymb) {
                   13162: 	$symb=&symbread();
                   13163:     } else {
                   13164: 	$symb=$passedsymb;
                   13165:     }
                   13166:     $courseid=$env{'request.course.id'};
                   13167:     $domain=$env{'user.domain'};
                   13168:     $name=$env{'user.name'};
                   13169:     if ($name eq 'public' && $domain eq 'public') {
                   13170: 	if (!defined($env{'form.username'})) {
                   13171: 	    $env{'form.username'}.=time.rand(10000000);
                   13172: 	}
                   13173: 	$name.=$env{'form.username'};
                   13174:     }
                   13175:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13176: 
                   13177: }
                   13178: 
1.36      albertel 13179: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13180: # returns either the contents of the file or 
                   13181: # -1 if the file doesn't exist
1.481     raeburn  13182: #
                   13183: # if the target is a file that was uploaded via DOCS, 
                   13184: # a check will be made to see if a current copy exists on the local server,
                   13185: # if it does this will be served, otherwise a copy will be retrieved from
                   13186: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13187: # the local server.   
1.472     albertel 13188: 
1.36      albertel 13189: sub getfile {
1.538     albertel 13190:     my ($file) = @_;
1.609     banghart 13191:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13192:     &repcopy($file);
                   13193:     return &readfile($file);
                   13194: }
                   13195: 
                   13196: sub repcopy_userfile {
                   13197:     my ($file)=@_;
1.1142    raeburn  13198:     my $londocroot = $perlvar{'lonDocRoot'};
                   13199:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13200:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13201:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13202: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13203:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13204:     if (-e "$file") {
1.828     www      13205: # we already have a local copy, check it out
1.538     albertel 13206: 	my @fileinfo = stat($file);
1.828     www      13207: 	my $rtncode;
                   13208: 	my $info;
1.538     albertel 13209: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13210: 	if ($lwpresp ne 'ok') {
1.828     www      13211: # there is no such file anymore, even though we had a local copy
1.482     albertel 13212: 	    if ($rtncode eq '404') {
1.538     albertel 13213: 		unlink($file);
1.482     albertel 13214: 	    }
                   13215: 	    return -1;
                   13216: 	}
                   13217: 	if ($info < $fileinfo[9]) {
1.828     www      13218: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13219: 	    return 'ok';
1.828     www      13220: 	} else {
                   13221: # the file is outdated, get rid of it
                   13222: 	    unlink($file);
1.482     albertel 13223: 	}
1.828     www      13224:     }
                   13225: # one way or the other, at this point, we don't have the file
                   13226: # construct the correct path for the file
                   13227:     my @parts = ($cdom,$cnum); 
                   13228:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13229: 	push @parts, split(/\//,$1);
                   13230:     }
                   13231:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13232:     foreach my $part (@parts) {
                   13233: 	$path .= '/'.$part;
                   13234: 	if (!-e $path) {
                   13235: 	    mkdir($path,0770);
1.482     albertel 13236: 	}
                   13237:     }
1.828     www      13238: # now the path exists for sure
                   13239: # get a user agent
                   13240:     my $ua=new LWP::UserAgent;
                   13241:     my $transferfile=$file.'.in.transfer';
                   13242: # FIXME: this should flock
                   13243:     if (-e $transferfile) { return 'ok'; }
                   13244:     my $request;
                   13245:     $uri=~s/^\///;
1.980     raeburn  13246:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.118.  .3(raebu 13247:20):     my $hostname = &hostname($homeserver);
1.980     raeburn  13248:     my $protocol = $protocol{$homeserver};
                   13249:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu 13250:20):     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      13251:     my $response=$ua->request($request,$transferfile);
                   13252: # did it work?
                   13253:     if ($response->is_error()) {
                   13254: 	unlink($transferfile);
                   13255: 	&logthis("Userfile repcopy failed for $uri");
                   13256: 	return -1;
                   13257:     }
                   13258: # worked, rename the transfer file
                   13259:     rename($transferfile,$file);
1.607     raeburn  13260:     return 'ok';
1.481     raeburn  13261: }
                   13262: 
1.517     albertel 13263: sub tokenwrapper {
                   13264:     my $uri=shift;
1.980     raeburn  13265:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13266:     $uri=~s|^/||;
1.620     albertel 13267:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13268:     my $token=$1;
1.552     albertel 13269:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13270:     if ($udom && $uname && $file) {
                   13271: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13272:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13273:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.118.  .3(raebu 13274:20):         my $hostname = &hostname($homeserver);
1.980     raeburn  13275:         my $protocol = $protocol{$homeserver};
                   13276:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu 13277:20):         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13278:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13279:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13280:     } else {
                   13281:         return '/adm/notfound.html';
                   13282:     }
                   13283: }
                   13284: 
1.828     www      13285: # call with reqtype HEAD: get last modification time
                   13286: # call with reqtype GET: get the file contents
                   13287: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13288: #
1.481     raeburn  13289: sub getuploaded {
                   13290:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13291:     $uri=~s/^\///;
1.980     raeburn  13292:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.118.  .3(raebu 13293:20):     my $hostname = &hostname($homeserver);
1.980     raeburn  13294:     my $protocol = $protocol{$homeserver};
                   13295:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.118.  .3(raebu 13296:20):     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13297:     my $ua=new LWP::UserAgent;
                   13298:     my $request=new HTTP::Request($reqtype,$uri);
                   13299:     my $response=$ua->request($request);
                   13300:     $$rtncode = $response->code;
1.482     albertel 13301:     if (! $response->is_success()) {
                   13302: 	return 'failed';
                   13303:     }      
                   13304:     if ($reqtype eq 'HEAD') {
1.486     www      13305: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13306:     } elsif ($reqtype eq 'GET') {
                   13307: 	$$info = $response->content;
1.472     albertel 13308:     }
1.482     albertel 13309:     return 'ok';
1.36      albertel 13310: }
                   13311: 
1.481     raeburn  13312: sub readfile {
                   13313:     my $file = shift;
                   13314:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13315:     my $fh;
1.1172.2.96  raeburn  13316:     open($fh,"<",$file);
1.481     raeburn  13317:     my $a='';
1.800     albertel 13318:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13319:     return $a;
                   13320: }
                   13321: 
1.36      albertel 13322: sub filelocation {
1.590     banghart 13323:     my ($dir,$file) = @_;
                   13324:     my $location;
                   13325:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13326: 
                   13327:     if ($file =~ m-^/adm/-) {
                   13328: 	$file=~s-^/adm/wrapper/-/-;
                   13329: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13330:     }
1.882     albertel 13331: 
1.1139    www      13332:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13333:         $location = $file;
1.609     banghart 13334:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13335:         my ($udom,$uname,$filename)=
1.811     albertel 13336:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13337:         my $home=&homeserver($uname,$udom);
                   13338:         my $is_me=0;
                   13339:         my @ids=&current_machine_ids();
                   13340:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13341:         if ($is_me) {
1.1117    foxr     13342:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13343:         } else {
                   13344:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13345:   	      $udom.'/'.$uname.'/'.$filename;
                   13346:         }
1.882     albertel 13347:     } elsif ($file =~ m-^/adm/-) {
                   13348: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13349:     } else {
                   13350:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13351:         $file=~s:^/(res|priv)/:/:;
                   13352:         my $space=$1;
1.590     banghart 13353:         if ( !( $file =~ m:^/:) ) {
                   13354:             $location = $dir. '/'.$file;
                   13355:         } else {
1.1142    raeburn  13356:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13357:         }
1.59      albertel 13358:     }
1.590     banghart 13359:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13360:     while ($location=~m{/\.\./}) {
                   13361: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13362: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13363: 	} else {
                   13364: 	    $location=~ s{/\.\./}{/}g;
                   13365: 	}
                   13366:     } #remove dir/..
1.590     banghart 13367:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13368:     return $location;
1.46      www      13369: }
1.36      albertel 13370: 
1.46      www      13371: sub hreflocation {
                   13372:     my ($dir,$file)=@_;
1.980     raeburn  13373:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13374: 	$file=filelocation($dir,$file);
1.700     albertel 13375:     } elsif ($file=~m-^/adm/-) {
                   13376: 	$file=~s-^/adm/wrapper/-/-;
                   13377: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13378:     }
                   13379:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13380: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13381:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13382: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13383: 	        {/uploaded/$1/$2/}x;
1.46      www      13384:     }
1.913     albertel 13385:     if ($file=~ m{^/userfiles/}) {
                   13386: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13387:     }
1.462     albertel 13388:     return $file;
1.465     albertel 13389: }
                   13390: 
1.1139    www      13391: 
                   13392: 
                   13393: 
                   13394: 
1.465     albertel 13395: sub current_machine_domains {
1.853     albertel 13396:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13397: }
                   13398: 
                   13399: sub machine_domains {
                   13400:     my ($hostname) = @_;
1.465     albertel 13401:     my @domains;
1.838     albertel 13402:     my %hostname = &all_hostnames();
1.465     albertel 13403:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13404: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13405: 	if ($hostname eq $name) {
1.844     albertel 13406: 	    push(@domains,&host_domain($id));
1.465     albertel 13407: 	}
                   13408:     }
                   13409:     return @domains;
                   13410: }
                   13411: 
                   13412: sub current_machine_ids {
1.853     albertel 13413:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13414: }
                   13415: 
                   13416: sub machine_ids {
                   13417:     my ($hostname) = @_;
                   13418:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13419:     my @ids;
1.888     albertel 13420:     my %name_to_host = &all_names();
1.889     albertel 13421:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13422: 	return @{ $name_to_host{$hostname} };
                   13423:     }
                   13424:     return;
1.31      www      13425: }
                   13426: 
1.824     raeburn  13427: sub additional_machine_domains {
                   13428:     my @domains;
1.1172.2.96  raeburn  13429:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13430:     while( my $line = <$fh>) {
                   13431:         $line =~ s/\s//g;
                   13432:         push(@domains,$line);
                   13433:     }
                   13434:     return @domains;
                   13435: }
                   13436: 
                   13437: sub default_login_domain {
                   13438:     my $domain = $perlvar{'lonDefDomain'};
                   13439:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13440:     foreach my $posdom (&current_machine_domains(),
                   13441:                         &additional_machine_domains()) {
                   13442:         if (lc($posdom) eq lc($testdomain)) {
                   13443:             $domain=$posdom;
                   13444:             last;
                   13445:         }
                   13446:     }
                   13447:     return $domain;
                   13448: }
                   13449: 
1.1172.2.106  raeburn  13450: sub shared_institution {
1.1172.2.118.  .15(raeb 13451:-21):     my ($dom,$lonhost) = @_;
                   13452:-21):     if ($lonhost eq '') {
                   13453:-21):         $lonhost = $perlvar{'lonHostID'};
                   13454:-21):     }
1.1172.2.106  raeburn  13455:     my $same_intdom;
1.1172.2.118.  .15(raeb 13456:-21):     my $hostintdom = &internet_dom($lonhost);
1.1172.2.106  raeburn  13457:     if ($hostintdom ne '') {
                   13458:         my %iphost = &get_iphost();
                   13459:         my $primary_id = &domain($dom,'primary');
                   13460:         my $primary_ip = &get_host_ip($primary_id);
                   13461:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   13462:             foreach my $id (@{$iphost{$primary_ip}}) {
                   13463:                 my $intdom = &internet_dom($id);
                   13464:                 if ($intdom eq $hostintdom) {
                   13465:                     $same_intdom = 1;
                   13466:                     last;
                   13467:                 }
                   13468:             }
                   13469:         }
                   13470:     }
                   13471:     return $same_intdom;
                   13472: }
                   13473: 
1.1172.2.118.  .3(raebu 13474:20): sub uses_sts {
                   13475:20):     my ($ignore_cache) = @_;
                   13476:20):     my $lonhost = $perlvar{'lonHostID'};
                   13477:20):     my $hostname = &hostname($lonhost);
                   13478:20):     my $sts_on;
                   13479:20):     if ($protocol{$lonhost} eq 'https') {
                   13480:20):         my $cachetime = 12*3600;
                   13481:20):         if (!$ignore_cache) {
                   13482:20):             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   13483:20):             if (defined($cached)) {
                   13484:20):                 return $sts_on;
                   13485:20):             }
                   13486:20):         }
          .4(raebu 13487:20):         my $ua=new LWP::UserAgent;
          .3(raebu 13488:20):         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   13489:20):         my $request=new HTTP::Request('HEAD',$url);
          .4(raebu 13490:20):         my $response=$ua->request($request);
          .3(raebu 13491:20):         if ($response->is_success) {
                   13492:20):             my $has_sts = $response->header('Strict-Transport-Security');
                   13493:20):             if ($has_sts eq '') {
                   13494:20):                 $sts_on = 0;
                   13495:20):             } else {
                   13496:20):                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   13497:20):                     my $maxage = $1;
                   13498:20):                     if ($maxage) {
                   13499:20):                         $sts_on = 1;
                   13500:20):                     } else {
                   13501:20):                         $sts_on = 0;
                   13502:20):                     }
                   13503:20):                 } else {
                   13504:20):                     $sts_on = 0;
                   13505:20):                 }
                   13506:20):             }
                   13507:20):             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   13508:20):         }
                   13509:20):     }
                   13510:20):     return;
                   13511:20): }
                   13512:20): 
          .14(raeb 13513:-21): sub get_requestor_ip {
                   13514:-21):     my ($r,$nolookup,$noproxy) = @_;
                   13515:-21):     my $from_ip;
                   13516:-21):     if (ref($r)) {
                   13517:-21):         $from_ip = $r->get_remote_host($nolookup);
                   13518:-21):     } else {
                   13519:-21):         $from_ip = $ENV{'REMOTE_ADDR'};
                   13520:-21):     }
                   13521:-21):     return $from_ip;
                   13522:-21): }
                   13523:-21): 
1.31      www      13524: # ------------------------------------------------------------- Declutters URLs
                   13525: 
                   13526: sub declutter {
                   13527:     my $thisfn=shift;
1.569     albertel 13528:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  13529:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13530:         $thisfn=~s{^/home/httpd/html}{};
                   13531:     }
1.31      www      13532:     $thisfn=~s/^\///;
1.697     albertel 13533:     $thisfn=~s|^adm/wrapper/||;
                   13534:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13535:     $thisfn=~s/^res\///;
1.1172    bisitz   13536:     $thisfn=~s/^priv\///;
1.1032    raeburn  13537:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13538:         $thisfn=~s/\?.+$//;
                   13539:     }
1.268     www      13540:     return $thisfn;
                   13541: }
                   13542: 
                   13543: # ------------------------------------------------------------- Clutter up URLs
                   13544: 
                   13545: sub clutter {
                   13546:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13547:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13548: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13549:        $thisfn='/res'.$thisfn; 
                   13550:     }
1.1031    raeburn  13551:     if ($thisfn !~m|^/adm|) {
                   13552: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13553: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13554: 	} else {
                   13555: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13556: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13557: 	    if ($embstyle eq 'ssi'
                   13558: 		|| ($embstyle eq 'hdn')
                   13559: 		|| ($embstyle eq 'rat')
                   13560: 		|| ($embstyle eq 'prv')
                   13561: 		|| ($embstyle eq 'ign')) {
                   13562: 		#do nothing with these
                   13563: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13564: 		|| ($embstyle eq 'emb')
                   13565: 		|| ($embstyle eq 'wrp')) {
                   13566: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13567: 	    } elsif ($embstyle eq 'unk'
                   13568: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13569: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13570: 	    } else {
1.718     www      13571: #		&logthis("Got a blank emb style");
1.695     albertel 13572: 	    }
1.694     albertel 13573: 	}
1.1172.2.118.  .1(raebu 13574:20):     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
                   13575:20):         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 13576:     }
1.31      www      13577:     return $thisfn;
1.12      www      13578: }
                   13579: 
1.787     albertel 13580: sub clutter_with_no_wrapper {
                   13581:     my $uri = &clutter(shift);
                   13582:     if ($uri =~ m-^/adm/-) {
                   13583: 	$uri =~ s-^/adm/wrapper/-/-;
                   13584: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13585:     }
                   13586:     return $uri;
                   13587: }
                   13588: 
1.557     albertel 13589: sub freeze_escape {
                   13590:     my ($value)=@_;
                   13591:     if (ref($value)) {
                   13592: 	$value=&nfreeze($value);
                   13593: 	return '__FROZEN__'.&escape($value);
                   13594:     }
                   13595:     return &escape($value);
                   13596: }
                   13597: 
1.11      www      13598: 
1.557     albertel 13599: sub thaw_unescape {
                   13600:     my ($value)=@_;
                   13601:     if ($value =~ /^__FROZEN__/) {
                   13602: 	substr($value,0,10,undef);
                   13603: 	$value=&unescape($value);
                   13604: 	return &thaw($value);
                   13605:     }
                   13606:     return &unescape($value);
                   13607: }
                   13608: 
1.436     albertel 13609: sub correct_line_ends {
                   13610:     my ($result)=@_;
                   13611:     $$result =~s/\r\n/\n/mg;
                   13612:     $$result =~s/\r/\n/mg;
1.415     albertel 13613: }
1.1       albertel 13614: # ================================================================ Main Program
                   13615: 
1.184     www      13616: sub goodbye {
1.204     albertel 13617:    &logthis("Starting Shut down");
1.443     albertel 13618: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13619:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13620: #converted
1.599     albertel 13621: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13622:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13623: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13624: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13625: #1.1 only
1.870     albertel 13626: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13627: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13628: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13629: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13630:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13631:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13632:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13633:    &flushcourselogs();
                   13634:    &logthis("Shutting down");
                   13635: }
                   13636: 
1.852     albertel 13637: sub get_dns {
1.1172.2.17  raeburn  13638:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13639:     if (!$ignore_cache) {
                   13640: 	my ($content,$cached)=
                   13641: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13642: 	if ($cached) {
1.1172.2.17  raeburn  13643: 	    &$func($content,$hashref);
1.869     albertel 13644: 	    return;
                   13645: 	}
                   13646:     }
                   13647: 
                   13648:     my %alldns;
1.1172.2.96  raeburn  13649:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   13650:         foreach my $dns (<$config>) {
                   13651: 	    next if ($dns !~ /^\^(\S*)/x);
                   13652:             my $line = $1;
                   13653:             my ($host,$protocol) = split(/:/,$line);
                   13654:             if ($protocol ne 'https') {
                   13655:                 $protocol = 'http';
                   13656:             }
                   13657: 	    $alldns{$host} = $protocol;
1.979     raeburn  13658:         }
1.1172.2.96  raeburn  13659:         close($config);
1.869     albertel 13660:     }
                   13661:     while (%alldns) {
1.1172.2.52  raeburn  13662: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 13663: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  13664:         $ua->timeout(30);
1.979     raeburn  13665: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 13666: 	my $response=$ua->request($request);
1.979     raeburn  13667:         delete($alldns{$dns});
1.852     albertel 13668: 	next if ($response->is_error());
                   13669: 	my @content = split("\n",$response->content);
1.1172.2.17  raeburn  13670:         unless ($nocache) {
1.1172.2.23  raeburn  13671: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  13672:         }
                   13673: 	&$func(\@content,$hashref);
1.869     albertel 13674: 	return;
1.852     albertel 13675:     }
1.871     albertel 13676:     my $which = (split('/',$url))[3];
                   13677:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  13678:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   13679:         my @content = <$config>;
                   13680:         &$func(\@content,$hashref);
                   13681:     }
1.1172.2.17  raeburn  13682:     return;
                   13683: }
                   13684: 
                   13685: # ------------------------------------------------------Get DNS checksums file
                   13686: sub parse_dns_checksums_tab {
                   13687:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  13688:     my $lonhost = $perlvar{'lonHostID'};
                   13689:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  13690:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  13691:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13692:     my $webconfdir = '/etc/httpd/conf';
                   13693:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13694:         $webconfdir = '/etc/apache2';
                   13695:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13696:         if ($1 >= 10) {
                   13697:             $webconfdir = '/etc/apache2';
                   13698:         }
                   13699:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13700:         if ($1 >= 10.0) {
                   13701:             $webconfdir = '/etc/apache2';
                   13702:         }
                   13703:     }
1.1172.2.17  raeburn  13704:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13705:     my (%chksum,%revnum);
                   13706:     if (ref($lines) eq 'ARRAY') {
                   13707:         chomp(@{$lines});
1.1172.2.34  raeburn  13708:         my $version = shift(@{$lines});
                   13709:         if ($version eq $release) {
1.1172.2.17  raeburn  13710:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  13711:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  13712:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13713:                     if ($webconfdir eq '/etc/apache2') {
                   13714:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13715:                     }
                   13716:                 }
1.1172.2.34  raeburn  13717:                 $chksum{$file} = $shasum;
                   13718:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  13719:             }
                   13720:             if (ref($hashref) eq 'HASH') {
                   13721:                 %{$hashref} = (
                   13722:                                 sums     => \%chksum,
                   13723:                                 versions => \%revnum,
                   13724:                               );
                   13725:             }
                   13726:         }
                   13727:     }
1.869     albertel 13728:     return;
1.852     albertel 13729: }
1.1172.2.17  raeburn  13730: 
                   13731: sub fetch_dns_checksums {
                   13732:     my %checksums;
1.1172.2.34  raeburn  13733:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  13734:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  13735:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13736:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  13737:              \%checksums);
                   13738:     return \%checksums;
                   13739: }
                   13740: 
1.327     albertel 13741: # ------------------------------------------------------------ Read domain file
                   13742: {
1.852     albertel 13743:     my $loaded;
1.846     albertel 13744:     my %domain;
                   13745: 
1.852     albertel 13746:     sub parse_domain_tab {
                   13747: 	my ($lines) = @_;
                   13748: 	foreach my $line (@$lines) {
                   13749: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13750: 
1.846     albertel 13751: 	    chomp($line);
1.852     albertel 13752: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13753: 	    my %this_domain;
                   13754: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13755: 			       'lang_def', 'city', 'longi', 'lati',
                   13756: 			       'primary') {
                   13757: 		$this_domain{$field} = shift(@elements);
                   13758: 	    }
                   13759: 	    $domain{$name} = \%this_domain;
1.852     albertel 13760: 	}
                   13761:     }
1.864     albertel 13762: 
                   13763:     sub reset_domain_info {
                   13764: 	undef($loaded);
                   13765: 	undef(%domain);
                   13766:     }
                   13767: 
1.852     albertel 13768:     sub load_domain_tab {
1.1172.2.70  raeburn  13769: 	my ($ignore_cache,$nocache) = @_;
                   13770: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13771: 	my $fh;
1.1172.2.96  raeburn  13772: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13773: 	    my @lines = <$fh>;
                   13774: 	    &parse_domain_tab(\@lines);
1.448     albertel 13775: 	}
1.852     albertel 13776: 	close($fh);
                   13777: 	$loaded = 1;
1.327     albertel 13778:     }
1.846     albertel 13779: 
                   13780:     sub domain {
1.852     albertel 13781: 	&load_domain_tab() if (!$loaded);
                   13782: 
1.846     albertel 13783: 	my ($name,$what) = @_;
                   13784: 	return if ( !exists($domain{$name}) );
                   13785: 
                   13786: 	if (!$what) {
                   13787: 	    return $domain{$name}{'description'};
                   13788: 	}
                   13789: 	return $domain{$name}{$what};
                   13790:     }
1.974     raeburn  13791: 
                   13792:     sub domain_info {
                   13793:         &load_domain_tab() if (!$loaded);
                   13794:         return %domain;
                   13795:     }
                   13796: 
1.327     albertel 13797: }
                   13798: 
                   13799: 
1.1       albertel 13800: # ------------------------------------------------------------- Read hosts file
                   13801: {
1.838     albertel 13802:     my %hostname;
1.844     albertel 13803:     my %hostdom;
1.845     albertel 13804:     my %libserv;
1.852     albertel 13805:     my $loaded;
1.888     albertel 13806:     my %name_to_host;
1.1074    raeburn  13807:     my %internetdom;
1.1107    raeburn  13808:     my %LC_dns_serv;
1.852     albertel 13809: 
                   13810:     sub parse_hosts_tab {
                   13811: 	my ($file) = @_;
                   13812: 	foreach my $configline (@$file) {
                   13813: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13814:             chomp($configline);
                   13815: 	    if ($configline =~ /^\^/) {
                   13816:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13817:                     $LC_dns_serv{$1} = 1;
                   13818:                 }
                   13819:                 next;
                   13820:             }
1.1074    raeburn  13821: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13822: 	    $name=~s/\s//g;
                   13823: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  13824:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13825:                     my $curr = $hostname{$id};
                   13826:                     my $skip;
                   13827:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13828:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13829:                             $skip = 1;
                   13830:                         } else {
                   13831:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13832:                         }
                   13833:                     }
                   13834:                     unless ($skip) {
                   13835:                         push(@{$name_to_host{$name}},$id);
                   13836:                     }
                   13837:                 } else {
                   13838:                     push(@{$name_to_host{$name}},$id);
                   13839:                 }
1.852     albertel 13840: 		$hostname{$id}=$name;
                   13841: 		$hostdom{$id}=$domain;
                   13842: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13843:                 if (defined($protocol)) {
                   13844:                     if ($protocol eq 'https') {
                   13845:                         $protocol{$id} = $protocol;
                   13846:                     } else {
                   13847:                         $protocol{$id} = 'http'; 
                   13848:                     }
1.968     raeburn  13849:                 } else {
1.969     raeburn  13850:                     $protocol{$id} = 'http';
1.968     raeburn  13851:                 }
1.1074    raeburn  13852:                 if (defined($intdom)) {
                   13853:                     $internetdom{$id} = $intdom;
                   13854:                 }
1.852     albertel 13855: 	    }
                   13856: 	}
                   13857:     }
1.864     albertel 13858:     
                   13859:     sub reset_hosts_info {
1.897     albertel 13860: 	&purge_remembered();
1.864     albertel 13861: 	&reset_domain_info();
                   13862: 	&reset_hosts_ip_info();
1.892     albertel 13863: 	undef(%name_to_host);
1.864     albertel 13864: 	undef(%hostname);
                   13865: 	undef(%hostdom);
                   13866: 	undef(%libserv);
                   13867: 	undef($loaded);
                   13868:     }
1.1       albertel 13869: 
1.852     albertel 13870:     sub load_hosts_tab {
1.1172.2.70  raeburn  13871: 	my ($ignore_cache,$nocache) = @_;
                   13872: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  13873: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13874: 	my @config = <$config>;
                   13875: 	&parse_hosts_tab(\@config);
                   13876: 	close($config);
                   13877: 	$loaded=1;
1.1       albertel 13878:     }
1.852     albertel 13879: 
1.838     albertel 13880:     sub hostname {
1.852     albertel 13881: 	&load_hosts_tab() if (!$loaded);
                   13882: 
1.838     albertel 13883: 	my ($lonid) = @_;
                   13884: 	return $hostname{$lonid};
                   13885:     }
1.845     albertel 13886: 
1.838     albertel 13887:     sub all_hostnames {
1.852     albertel 13888: 	&load_hosts_tab() if (!$loaded);
                   13889: 
1.838     albertel 13890: 	return %hostname;
                   13891:     }
1.845     albertel 13892: 
1.888     albertel 13893:     sub all_names {
1.1172.2.70  raeburn  13894:         my ($ignore_cache,$nocache) = @_;
                   13895: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13896: 
                   13897: 	return %name_to_host;
                   13898:     }
                   13899: 
1.974     raeburn  13900:     sub all_host_domain {
                   13901:         &load_hosts_tab() if (!$loaded);
                   13902:         return %hostdom;
                   13903:     }
                   13904: 
1.845     albertel 13905:     sub is_library {
1.852     albertel 13906: 	&load_hosts_tab() if (!$loaded);
                   13907: 
1.845     albertel 13908: 	return exists($libserv{$_[0]});
                   13909:     }
                   13910: 
                   13911:     sub all_library {
1.852     albertel 13912: 	&load_hosts_tab() if (!$loaded);
                   13913: 
1.845     albertel 13914: 	return %libserv;
                   13915:     }
                   13916: 
1.1062    droeschl 13917:     sub unique_library {
                   13918: 	#2x reverse removes all hostnames that appear more than once
                   13919:         my %unique = reverse &all_library();
                   13920:         return reverse %unique;
                   13921:     }
                   13922: 
1.841     albertel 13923:     sub get_servers {
1.852     albertel 13924: 	&load_hosts_tab() if (!$loaded);
                   13925: 
1.841     albertel 13926: 	my ($domain,$type) = @_;
                   13927: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13928: 	                                          : %hostname;
                   13929: 	my %result;
1.842     albertel 13930: 	if (ref($domain) eq 'ARRAY') {
                   13931: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13932: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13933: 		    $result{$host} = $hostname;
                   13934: 		}
                   13935: 	    }
                   13936: 	} else {
                   13937: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13938: 		if ($hostdom{$host} eq $domain) {
                   13939: 		    $result{$host} = $hostname;
                   13940: 		}
1.841     albertel 13941: 	    }
                   13942: 	}
                   13943: 	return %result;
                   13944:     }
1.845     albertel 13945: 
1.1062    droeschl 13946:     sub get_unique_servers {
                   13947:         my %unique = reverse &get_servers(@_);
                   13948: 	return reverse %unique;
                   13949:     }
                   13950: 
1.844     albertel 13951:     sub host_domain {
1.852     albertel 13952: 	&load_hosts_tab() if (!$loaded);
                   13953: 
1.844     albertel 13954: 	my ($lonid) = @_;
                   13955: 	return $hostdom{$lonid};
                   13956:     }
                   13957: 
1.841     albertel 13958:     sub all_domains {
1.852     albertel 13959: 	&load_hosts_tab() if (!$loaded);
                   13960: 
1.841     albertel 13961: 	my %seen;
                   13962: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13963: 	return @uniq;
                   13964:     }
1.1074    raeburn  13965: 
                   13966:     sub internet_dom {
                   13967:         &load_hosts_tab() if (!$loaded);
                   13968: 
                   13969:         my ($lonid) = @_;
                   13970:         return $internetdom{$lonid};
                   13971:     }
1.1107    raeburn  13972: 
                   13973:     sub is_LC_dns {
                   13974:         &load_hosts_tab() if (!$loaded);
                   13975: 
                   13976:         my ($hostname) = @_;
                   13977:         return exists($LC_dns_serv{$hostname});
                   13978:     }
                   13979: 
1.1       albertel 13980: }
                   13981: 
1.847     albertel 13982: { 
                   13983:     my %iphost;
1.856     albertel 13984:     my %name_to_ip;
                   13985:     my %lonid_to_ip;
1.869     albertel 13986: 
1.847     albertel 13987:     sub get_hosts_from_ip {
                   13988: 	my ($ip) = @_;
                   13989: 	my %iphosts = &get_iphost();
                   13990: 	if (ref($iphosts{$ip})) {
                   13991: 	    return @{$iphosts{$ip}};
                   13992: 	}
                   13993: 	return;
1.839     albertel 13994:     }
1.864     albertel 13995:     
                   13996:     sub reset_hosts_ip_info {
                   13997: 	undef(%iphost);
                   13998: 	undef(%name_to_ip);
                   13999: 	undef(%lonid_to_ip);
                   14000:     }
1.856     albertel 14001: 
                   14002:     sub get_host_ip {
                   14003: 	my ($lonid) = @_;
                   14004: 	if (exists($lonid_to_ip{$lonid})) {
                   14005: 	    return $lonid_to_ip{$lonid};
                   14006: 	}
                   14007: 	my $name=&hostname($lonid);
                   14008:    	my $ip = gethostbyname($name);
                   14009: 	return if (!$ip || length($ip) ne 4);
                   14010: 	$ip=inet_ntoa($ip);
                   14011: 	$name_to_ip{$name}   = $ip;
                   14012: 	$lonid_to_ip{$lonid} = $ip;
                   14013: 	return $ip;
                   14014:     }
1.847     albertel 14015:     
                   14016:     sub get_iphost {
1.1172.2.70  raeburn  14017: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14018: 
1.869     albertel 14019: 	if (!$ignore_cache) {
                   14020: 	    if (%iphost) {
                   14021: 		return %iphost;
                   14022: 	    }
                   14023: 	    my ($ip_info,$cached)=
                   14024: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14025: 	    if ($cached) {
                   14026: 		%iphost      = %{$ip_info->[0]};
                   14027: 		%name_to_ip  = %{$ip_info->[1]};
                   14028: 		%lonid_to_ip = %{$ip_info->[2]};
                   14029: 		return %iphost;
                   14030: 	    }
                   14031: 	}
1.894     albertel 14032: 
                   14033: 	# get yesterday's info for fallback
                   14034: 	my %old_name_to_ip;
                   14035: 	my ($ip_info,$cached)=
                   14036: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14037: 	if ($cached) {
                   14038: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14039: 	}
                   14040: 
1.1172.2.70  raeburn  14041: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14042: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14043: 	    my $ip;
                   14044: 	    if (!exists($name_to_ip{$name})) {
                   14045: 		$ip = gethostbyname($name);
                   14046: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14047: 		    if (defined($old_name_to_ip{$name})) {
                   14048: 			$ip = $old_name_to_ip{$name};
                   14049: 			&logthis("Can't find $name defaulting to old $ip");
                   14050: 		    } else {
                   14051: 			&logthis("Name $name no IP found");
                   14052: 			next;
                   14053: 		    }
                   14054: 		} else {
                   14055: 		    $ip=inet_ntoa($ip);
1.847     albertel 14056: 		}
                   14057: 		$name_to_ip{$name} = $ip;
                   14058: 	    } else {
                   14059: 		$ip = $name_to_ip{$name};
1.653     albertel 14060: 	    }
1.888     albertel 14061: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14062: 		$lonid_to_ip{$id} = $ip;
                   14063: 	    }
                   14064: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14065: 	}
1.1172.2.70  raeburn  14066:         unless ($nocache) {
                   14067: 	    &do_cache_new('iphost','iphost',
                   14068: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14069: 		          48*60*60);
                   14070:         }
1.869     albertel 14071: 
1.847     albertel 14072: 	return %iphost;
1.598     albertel 14073:     }
                   14074: 
1.992     raeburn  14075:     #
                   14076:     #  Given a DNS returns the loncapa host name for that DNS 
                   14077:     # 
                   14078:     sub host_from_dns {
                   14079:         my ($dns) = @_;
                   14080:         my @hosts;
                   14081:         my $ip;
                   14082: 
1.993     raeburn  14083:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14084:             $ip = $name_to_ip{$dns};
                   14085:         }
                   14086:         if (!$ip) {
                   14087:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14088:             if (length($ip) == 4) { 
                   14089: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14090:             }
                   14091:         }
                   14092:         if ($ip) {
                   14093: 	    @hosts = get_hosts_from_ip($ip);
                   14094: 	    return $hosts[0];
                   14095:         }
                   14096:         return undef;
1.986     foxr     14097:     }
1.992     raeburn  14098: 
1.1074    raeburn  14099:     sub get_internet_names {
                   14100:         my ($lonid) = @_;
                   14101:         return if ($lonid eq '');
                   14102:         my ($idnref,$cached)=
                   14103:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14104:         if ($cached) {
                   14105:             return $idnref;
                   14106:         }
                   14107:         my $ip = &get_host_ip($lonid);
                   14108:         my @hosts = &get_hosts_from_ip($ip);
                   14109:         my %iphost = &get_iphost();
                   14110:         my (@idns,%seen);
                   14111:         foreach my $id (@hosts) {
                   14112:             my $dom = &host_domain($id);
                   14113:             my $prim_id = &domain($dom,'primary');
                   14114:             my $prim_ip = &get_host_ip($prim_id);
                   14115:             next if ($seen{$prim_ip});
                   14116:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14117:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14118:                     my $intdom = &internet_dom($id);
                   14119:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14120:                         push(@idns,$intdom);
                   14121:                     }
                   14122:                 }
                   14123:             }
                   14124:             $seen{$prim_ip} = 1;
                   14125:         }
1.1172.2.23  raeburn  14126:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14127:     }
                   14128: 
1.986     foxr     14129: }
                   14130: 
1.1079    raeburn  14131: sub all_loncaparevs {
1.1172.2.39  raeburn  14132:     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  14133: }
                   14134: 
1.1172.2.27  raeburn  14135: # ------------------------------------------------------- Read loncaparev table
                   14136: {
                   14137:     sub load_loncaparevs {
                   14138:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  14139:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  14140:                 while (my $configline=<$config>) {
                   14141:                     chomp($configline);
                   14142:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14143:                     $loncaparevs{$hostid}=$loncaparev;
                   14144:                 }
                   14145:                 close($config);
                   14146:             }
                   14147:         }
                   14148:     }
                   14149: }
                   14150: 
                   14151: # ----------------------------------------------------- Read serverhostID table
                   14152: {
                   14153:     sub load_serverhomeIDs {
                   14154:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  14155:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  14156:                 while (my $configline=<$config>) {
                   14157:                     chomp($configline);
                   14158:                     my ($name,$id)=split(/:/,$configline);
                   14159:                     $serverhomeIDs{$name}=$id;
                   14160:                 }
                   14161:                 close($config);
                   14162:             }
                   14163:         }
                   14164:     }
                   14165: }
                   14166: 
                   14167: 
1.862     albertel 14168: BEGIN {
                   14169: 
                   14170: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14171:     unless ($readit) {
                   14172: {
                   14173:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14174:     %perlvar = (%perlvar,%{$configvars});
                   14175: }
                   14176: 
                   14177: 
1.1       albertel 14178: # ------------------------------------------------------ Read spare server file
                   14179: {
1.1172.2.96  raeburn  14180:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14181: 
                   14182:     while (my $configline=<$config>) {
                   14183:        chomp($configline);
1.284     matthew  14184:        if ($configline) {
1.784     albertel 14185: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14186: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14187: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14188:        }
                   14189:     }
1.448     albertel 14190:     close($config);
1.1       albertel 14191: }
1.11      www      14192: # ------------------------------------------------------------ Read permissions
                   14193: {
1.1172.2.96  raeburn  14194:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14195: 
                   14196:     while (my $configline=<$config>) {
1.448     albertel 14197: 	chomp($configline);
                   14198: 	if ($configline) {
                   14199: 	    my ($role,$perm)=split(/ /,$configline);
                   14200: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14201: 	}
1.11      www      14202:     }
1.448     albertel 14203:     close($config);
1.11      www      14204: }
                   14205: 
                   14206: # -------------------------------------------- Read plain texts for permissions
                   14207: {
1.1172.2.96  raeburn  14208:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14209: 
                   14210:     while (my $configline=<$config>) {
1.448     albertel 14211: 	chomp($configline);
                   14212: 	if ($configline) {
1.742     raeburn  14213: 	    my ($short,@plain)=split(/:/,$configline);
                   14214:             %{$prp{$short}} = ();
                   14215: 	    if (@plain > 0) {
                   14216:                 $prp{$short}{'std'} = $plain[0];
                   14217:                 for (my $i=1; $i<@plain; $i++) {
                   14218:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14219:                 }
                   14220:             }
1.448     albertel 14221: 	}
1.135     www      14222:     }
1.448     albertel 14223:     close($config);
1.135     www      14224: }
                   14225: 
                   14226: # ---------------------------------------------------------- Read package table
                   14227: {
1.1172.2.96  raeburn  14228:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14229: 
                   14230:     while (my $configline=<$config>) {
1.483     albertel 14231: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14232: 	chomp($configline);
                   14233: 	my ($short,$plain)=split(/:/,$configline);
                   14234: 	my ($pack,$name)=split(/\&/,$short);
                   14235: 	if ($plain ne '') {
                   14236: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14237: 	    $packagetab{$short}=$plain; 
                   14238: 	}
1.11      www      14239:     }
1.448     albertel 14240:     close($config);
1.329     matthew  14241: }
                   14242: 
1.1172.2.27  raeburn  14243: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  14244: 
1.1172.2.27  raeburn  14245: &load_loncaparevs();
                   14246: 
                   14247: # ------------------------------------------------------- Read serverhostID table
                   14248: 
                   14249: &load_serverhomeIDs();
1.1074    raeburn  14250: 
1.1172.2.27  raeburn  14251: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14252: {
                   14253:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14254:     if (-e $file) {
                   14255:         my $parser = HTML::LCParser->new($file);
                   14256:         while (my $token = $parser->get_token()) {
                   14257:             if ($token->[0] eq 'S') {
                   14258:                 my $item = $token->[1];
                   14259:                 my $name = $token->[2]{'name'};
                   14260:                 my $value = $token->[2]{'value'};
                   14261:                 if ($item ne '' && $name ne '' && $value ne '') {
                   14262:                     my $release = $parser->get_text();
                   14263:                     $release =~ s/(^\s*|\s*$ )//gx;
                   14264:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   14265:                 }
                   14266:             }
                   14267:         }
                   14268:     }
1.1073    raeburn  14269: }
                   14270: 
1.1138    raeburn  14271: # ---------------------------------------------------------- Read managers table
                   14272: {
                   14273:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  14274:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14275:             while (my $configline=<$config>) {
                   14276:                 chomp($configline);
                   14277:                 next if ($configline =~ /^\#/);
                   14278:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14279:                     $managerstab{$configline} = 1;
                   14280:                 }
                   14281:             }
                   14282:             close($config);
                   14283:         }
                   14284:     }
                   14285: }
                   14286: 
1.329     matthew  14287: # ------------- set up temporary directory
                   14288: {
1.1117    foxr     14289:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14290: 
1.11      www      14291: }
                   14292: 
1.1172.2.104  raeburn  14293: # ------------- set default texengine (domain default overrides this)
                   14294: {
                   14295:     $deftex = LONCAPA::texengine();
                   14296: }
                   14297: 
1.1172.2.114  raeburn  14298: # ------------- set default minimum length for passwords for internal auth users
                   14299: {
                   14300:     $passwdmin = LONCAPA::passwd_min();
                   14301: }
                   14302: 
1.794     albertel 14303: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14304: 				'compress_threshold'=> 20_000,
                   14305:  			        });
1.185     www      14306: 
1.281     www      14307: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14308: $dumpcount=0;
1.958     www      14309: $locknum=0;
1.22      www      14310: 
1.163     harris41 14311: &logtouch();
1.672     albertel 14312: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14313: $readit=1;
1.564     albertel 14314:     {
                   14315: 	use integer;
                   14316: 	my $test=(2**32)+1;
1.568     albertel 14317: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14318: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14319:     }
1.195     www      14320: }
1.1       albertel 14321: }
1.179     www      14322: 
1.1       albertel 14323: 1;
1.191     harris41 14324: __END__
                   14325: 
1.243     albertel 14326: =pod
                   14327: 
1.191     harris41 14328: =head1 NAME
                   14329: 
1.243     albertel 14330: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14331: 
                   14332: =head1 SYNOPSIS
                   14333: 
1.243     albertel 14334: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14335: 
                   14336:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14337: 
1.243     albertel 14338: Common parameters:
                   14339: 
                   14340: =over 4
                   14341: 
                   14342: =item *
                   14343: 
                   14344: $uname : an internal username (if $cname expecting a course Id specifically)
                   14345: 
                   14346: =item *
                   14347: 
                   14348: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14349: 
                   14350: =item *
                   14351: 
                   14352: $symb : a resource instance identifier
                   14353: 
                   14354: =item *
                   14355: 
                   14356: $namespace : the name of a .db file that contains the data needed or
                   14357: being set.
                   14358: 
                   14359: =back
                   14360: 
1.394     bowersj2 14361: =head1 OVERVIEW
1.191     harris41 14362: 
1.394     bowersj2 14363: lonnet provides subroutines which interact with the
                   14364: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14365: about classes, users, and resources.
1.243     albertel 14366: 
                   14367: For many of these objects you can also use this to store data about
                   14368: them or modify them in various ways.
1.191     harris41 14369: 
1.394     bowersj2 14370: =head2 Symbs
1.191     harris41 14371: 
1.394     bowersj2 14372: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14373: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14374: map, the resource number of the resource in the map, and the URL of
                   14375: the resource itself. The latter is somewhat redundant, but might help
                   14376: if maps change.
                   14377: 
                   14378: An example is
                   14379: 
                   14380:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14381: 
                   14382: The respective map entry is
                   14383: 
                   14384:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14385:   title="Problem 2">
                   14386:  </resource>
                   14387: 
                   14388: Symbs are used by the random number generator, as well as to store and
                   14389: restore data specific to a certain instance of for example a problem.
                   14390: 
                   14391: =head2 Storing And Retrieving Data
                   14392: 
                   14393: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14394: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14395: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14396: is is the non-critical message twin of cstore. These functions are for
                   14397: handlers to store a perl hash to a user's permanent data space in an
                   14398: easy manner, and to retrieve it again on another call. It is expected
                   14399: that a handler would use this once at the beginning to retrieve data,
                   14400: and then again once at the end to send only the new data back.
                   14401: 
                   14402: The data is stored in the user's data directory on the user's
                   14403: homeserver under the ID of the course.
                   14404: 
                   14405: The hash that is returned by restore will have all of the previous
                   14406: value for all of the elements of the hash.
                   14407: 
                   14408: Example:
                   14409: 
                   14410:  #creating a hash
                   14411:  my %hash;
                   14412:  $hash{'foo'}='bar';
                   14413: 
                   14414:  #storing it
                   14415:  &Apache::lonnet::cstore(\%hash);
                   14416: 
                   14417:  #changing a value
                   14418:  $hash{'foo'}='notbar';
                   14419: 
                   14420:  #adding a new value
                   14421:  $hash{'bar'}='foo';
                   14422:  &Apache::lonnet::cstore(\%hash);
                   14423: 
                   14424:  #retrieving the hash
                   14425:  my %history=&Apache::lonnet::restore();
                   14426: 
                   14427:  #print the hash
                   14428:  foreach my $key (sort(keys(%history))) {
                   14429:    print("\%history{$key} = $history{$key}");
                   14430:  }
                   14431: 
                   14432: Will print out:
1.191     harris41 14433: 
1.394     bowersj2 14434:  %history{1:foo} = bar
                   14435:  %history{1:keys} = foo:timestamp
                   14436:  %history{1:timestamp} = 990455579
                   14437:  %history{2:bar} = foo
                   14438:  %history{2:foo} = notbar
                   14439:  %history{2:keys} = foo:bar:timestamp
                   14440:  %history{2:timestamp} = 990455580
                   14441:  %history{bar} = foo
                   14442:  %history{foo} = notbar
                   14443:  %history{timestamp} = 990455580
                   14444:  %history{version} = 2
                   14445: 
                   14446: Note that the special hash entries C<keys>, C<version> and
                   14447: C<timestamp> were added to the hash. C<version> will be equal to the
                   14448: total number of versions of the data that have been stored. The
                   14449: C<timestamp> attribute will be the UNIX time the hash was
                   14450: stored. C<keys> is available in every historical section to list which
                   14451: keys were added or changed at a specific historical revision of a
                   14452: hash.
                   14453: 
                   14454: B<Warning>: do not store the hash that restore returns directly. This
                   14455: will cause a mess since it will restore the historical keys as if the
                   14456: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14457: 
1.394     bowersj2 14458: Calling convention:
1.191     harris41 14459: 
1.1172.2.27  raeburn  14460:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  14461:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14462: 
1.394     bowersj2 14463: For more detailed information, see lonnet specific documentation.
1.191     harris41 14464: 
1.394     bowersj2 14465: =head1 RETURN MESSAGES
1.191     harris41 14466: 
1.394     bowersj2 14467: =over 4
1.191     harris41 14468: 
1.394     bowersj2 14469: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14470: 
1.394     bowersj2 14471: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14472: when the connection is brought back up
1.191     harris41 14473: 
1.394     bowersj2 14474: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14475: for later delivery
1.191     harris41 14476: 
1.967     bisitz   14477: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14478: 
1.394     bowersj2 14479: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14480: that was requested
1.191     harris41 14481: 
1.243     albertel 14482: =back
1.191     harris41 14483: 
1.243     albertel 14484: =head1 PUBLIC SUBROUTINES
1.191     harris41 14485: 
1.243     albertel 14486: =head2 Session Environment Functions
1.191     harris41 14487: 
1.243     albertel 14488: =over 4
1.191     harris41 14489: 
1.394     bowersj2 14490: =item * 
                   14491: X<appenv()>
1.949     raeburn  14492: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14493: the user envirnoment file, and will be restored for each access this
1.620     albertel 14494: user makes during this session, also modifies the %env for the current
1.949     raeburn  14495: process. Optional rolesarrayref - if defined contains a reference to an array
                   14496: of roles which are exempt from the restriction on modifying user.role entries 
                   14497: in the user's environment.db and in %env.    
1.191     harris41 14498: 
                   14499: =item *
1.394     bowersj2 14500: X<delenv()>
1.987     raeburn  14501: B<delenv($delthis,$regexp)>: removes all items from the session
                   14502: environment file that begin with $delthis. If the 
                   14503: optional second arg - $regexp - is true, $delthis is treated as a 
                   14504: regular expression, otherwise \Q$delthis\E is used. 
                   14505: The values are also deleted from the current processes %env.
1.191     harris41 14506: 
1.795     albertel 14507: =item * get_env_multiple($name) 
                   14508: 
                   14509: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14510: values may be defined and end up as an array ref.
                   14511: 
                   14512: returns an array of values
                   14513: 
1.243     albertel 14514: =back
                   14515: 
                   14516: =head2 User Information
1.191     harris41 14517: 
1.243     albertel 14518: =over 4
1.191     harris41 14519: 
                   14520: =item *
1.394     bowersj2 14521: X<queryauthenticate()>
                   14522: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14523: authentication scheme
                   14524: 
                   14525: =item *
1.394     bowersj2 14526: X<authenticate()>
1.1073    raeburn  14527: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14528: authenticate user from domain's lib servers (first use the current
                   14529: one). C<$upass> should be the users password.
1.1073    raeburn  14530: $checkdefauth is optional (value is 1 if a check should be made to
                   14531:    authenticate user using default authentication method, and allow
                   14532:    account creation if username does not have account in the domain).
                   14533: $clientcancheckhost is optional (value is 1 if checking whether the
                   14534:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14535: 
                   14536: =item *
1.394     bowersj2 14537: X<homeserver()>
                   14538: B<homeserver($uname,$udom)>: find the server which has
                   14539: the user's directory and files (there must be only one), this caches
                   14540: the answer, and also caches if there is a borken connection.
1.191     harris41 14541: 
                   14542: =item *
1.394     bowersj2 14543: X<idget()>
                   14544: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   14545: (IDs are a unique resource in a domain, there must be only 1 ID per
                   14546: username, and only 1 username per ID in a specific domain) (returns
                   14547: hash: id=>name,id=>name)
1.191     harris41 14548: 
                   14549: =item *
1.394     bowersj2 14550: X<idrget()>
                   14551: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14552: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14553: 
                   14554: =item *
1.394     bowersj2 14555: X<idput()>
                   14556: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 14557: 
                   14558: =item *
1.394     bowersj2 14559: X<rolesinit()>
1.1169    droeschl 14560: B<rolesinit($udom,$username)>: get user privileges.
                   14561: returns user role, first access and timer interval hashes
1.243     albertel 14562: 
                   14563: =item *
1.1171    droeschl 14564: X<privileged()>
                   14565: B<privileged($username,$domain)>: returns a true if user has a
                   14566: privileged and active role (i.e. su or dc), false otherwise.
                   14567: 
                   14568: =item *
1.551     albertel 14569: X<getsection()>
                   14570: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14571: course $cname, return section name/number or '' for "not in course"
                   14572: and '-1' for "no section"
                   14573: 
                   14574: =item *
1.394     bowersj2 14575: X<userenvironment()>
                   14576: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14577: passed in @what from the requested user's environment, returns a hash
                   14578: 
1.858     raeburn  14579: =item * 
                   14580: X<userlog_query()>
1.859     albertel 14581: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14582: activity.log file. %filters defines filters applied when parsing the
                   14583: log file. These can be start or end timestamps, or the type of action
                   14584: - log to look for Login or Logout events, check for Checkin or
                   14585: Checkout, role for role selection. The response is in the form
                   14586: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14587: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14588: 
1.243     albertel 14589: =back
                   14590: 
                   14591: =head2 User Roles
                   14592: 
                   14593: =over 4
                   14594: 
                   14595: =item *
                   14596: 
1.1172.2.65  raeburn  14597: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14598: returns codes for allowed actions.
                   14599: 
                   14600: The first argument is required, all others are optional.
                   14601: 
                   14602: $priv is the privilege being checked.
                   14603: $uri contains additional information about what is being checked for access (e.g.,
                   14604: URL, course ID etc.).
                   14605: $symb is the unique resource instance identifier in a course; if needed,
                   14606: but not provided, it will be retrieved via a call to &symbread().
                   14607: $role is the role for which a priv is being checked (only used if priv is evb).
                   14608: $clientip is the user's IP address (only used when checking for access to portfolio
                   14609: files).
                   14610: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   14611: prevents recursive calls to &allowed.
                   14612: 
1.243     albertel 14613:  F: full access
                   14614:  U,I,K: authentication modes (cxx only)
                   14615:  '': forbidden
                   14616:  1: user needs to choose course
                   14617:  2: browse allowed
1.766     albertel 14618:  A: passphrase authentication needed
1.1172.2.65  raeburn  14619:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14620: 
                   14621: =item *
                   14622: 
1.1172.2.13  raeburn  14623: constructaccess($url,$setpriv) : check for access to construction space URL
                   14624: 
                   14625: See if the owner domain and name in the URL match those in the
                   14626: expected environment.  If so, return three element list
                   14627: ($ownername,$ownerdomain,$ownerhome).
                   14628: 
                   14629: Otherwise return the null string.
                   14630: 
                   14631: If second argument 'setpriv' is true, it assigns the privileges,
                   14632: and returns the same three element list, unless the owner has
                   14633: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14634: in which case the null string is returned.
                   14635: 
                   14636: =item *
                   14637: 
1.1172.2.84  raeburn  14638: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14639: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14640: for system, domain, and course level. $uname and $udom are optional (current
                   14641: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14642: 
                   14643: =item *
                   14644: 
1.988     raeburn  14645: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14646: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14647: $type is Course (default) or Community.
1.988     raeburn  14648: If $forcedefault evaluates to true, text returned will be default 
                   14649: text for $type. Otherwise, if this is a course, the text returned 
                   14650: will be a custom name for the role (if defined in the course's 
                   14651: environment).  If no custom name is defined the default is returned.
                   14652:    
1.832     raeburn  14653: =item *
                   14654: 
1.1172.2.23  raeburn  14655: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14656: All arguments are optional. Returns a hash of a roles, either for
                   14657: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14658: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14659: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14660: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14661: For each key, value is set to colon-separated start and end times for
                   14662: the role.  If no username and domain are specified, will default to
1.934     raeburn  14663: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14664: of role statuses (active, future or previous), roles 
                   14665: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14666: to restrict the list of roles reported. If no array ref is 
                   14667: provided for types, will default to return only active roles.
1.834     albertel 14668: 
1.1172.2.13  raeburn  14669: =item *
                   14670: 
                   14671: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   14672: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   14673: 
                   14674: Additional optional arguments are: $type (if role checking is to be restricted
                   14675: to certain user status types -- previous (expired roles), active (currently
                   14676: available roles) or future (roles available in the future), and
                   14677: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  14678: have active Domain Coordinator role in course's domain or in additional
                   14679: domains (specified in 'Domains to check for privileged users' in course
                   14680: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14681: 
                   14682: =item *
                   14683: 
                   14684: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14685: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14686: $possdomains and $possroles are optional array refs -- to domains to check and
                   14687: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14688: users' roles.db to check for a dc or su role in any domain. This can be
                   14689: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14690: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14691: this then allows &privileged_by_domain() to be used, which caches the identity
                   14692: of privileged users, eliminating the need for repeated calls to &dump().
                   14693: 
                   14694: =item *
                   14695: 
                   14696: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14697: where the outer hash keys are domains specified in the $possdomains array ref,
                   14698: next inner hash keys are privileged roles specified in the $roles array ref,
                   14699: and the innermost hash contains key = value pairs for username:domain = end:start
                   14700: for active or future "privileged" users with that role in that domain. To avoid
                   14701: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14702: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  14703: 
1.243     albertel 14704: =back
                   14705: 
                   14706: =head2 User Modification
                   14707: 
                   14708: =over 4
                   14709: 
                   14710: =item *
                   14711: 
1.957     raeburn  14712: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14713: user for the level given by URL.  Optional start and end dates (leave empty
                   14714: string or zero for "no date")
1.191     harris41 14715: 
                   14716: =item *
                   14717: 
1.243     albertel 14718: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14719: change a users, password, possible return values are: ok,
                   14720: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14721: refused
1.191     harris41 14722: 
                   14723: =item *
                   14724: 
1.243     albertel 14725: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14726: 
                   14727: =item *
                   14728: 
1.1058    raeburn  14729: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14730:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14731: 
                   14732: will update user information (firstname,middlename,lastname,generation,
                   14733: permanentemail), and if forceid is true, student/employee ID also.
                   14734: A user's institutional affiliation(s) can also be updated.
                   14735: User information fields will not be overwritten with empty entries 
                   14736: unless the field is included in the $candelete array reference.
                   14737: This array is included when a single user is modified via "Manage Users",
                   14738: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14739: 
                   14740: =item *
                   14741: 
1.286     matthew  14742: modifystudent
                   14743: 
1.957     raeburn  14744: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  14745: The course id is resolved based on the current user's environment.  
                   14746: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14747: associated with a course.
                   14748: 
1.297     matthew  14749: This call is essentially a wrapper for lonnet::modifyuser and
                   14750: lonnet::modify_student_enrollment
1.286     matthew  14751: 
                   14752: Inputs: 
                   14753: 
                   14754: =over 4
                   14755: 
1.957     raeburn  14756: =item B<$udom> Student's loncapa domain
1.286     matthew  14757: 
1.957     raeburn  14758: =item B<$uname> Student's loncapa login name
1.286     matthew  14759: 
1.964     bisitz   14760: =item B<$uid> Student/Employee ID
1.286     matthew  14761: 
1.957     raeburn  14762: =item B<$umode> Student's authentication mode
1.286     matthew  14763: 
1.957     raeburn  14764: =item B<$upass> Student's password
1.286     matthew  14765: 
1.957     raeburn  14766: =item B<$first> Student's first name
1.286     matthew  14767: 
1.957     raeburn  14768: =item B<$middle> Student's middle name
1.286     matthew  14769: 
1.957     raeburn  14770: =item B<$last> Student's last name
1.286     matthew  14771: 
1.957     raeburn  14772: =item B<$gene> Student's generation
1.286     matthew  14773: 
1.957     raeburn  14774: =item B<$usec> Student's section in course
1.286     matthew  14775: 
                   14776: =item B<$end> Unix time of the roles expiration
                   14777: 
                   14778: =item B<$start> Unix time of the roles start date
                   14779: 
                   14780: =item B<$forceid> If defined, allow $uid to be changed
                   14781: 
                   14782: =item B<$desiredhome> server to use as home server for student
                   14783: 
1.957     raeburn  14784: =item B<$email> Student's permanent e-mail address
                   14785: 
                   14786: =item B<$type> Type of enrollment (auto or manual)
                   14787: 
1.963     raeburn  14788: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14789: 
                   14790: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14791: 
1.963     raeburn  14792: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14793: 
1.963     raeburn  14794: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14795: 
1.1172.2.19  raeburn  14796: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14797: 
                   14798: =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  14799: 
1.286     matthew  14800: =back
1.297     matthew  14801: 
                   14802: =item *
                   14803: 
                   14804: modify_student_enrollment
                   14805: 
1.1172.2.31  raeburn  14806: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14807: 'role.request.course' must be defined for this function to proceed.
                   14808: 
                   14809: Inputs:
                   14810: 
                   14811: =over 4
                   14812: 
1.1172.2.31  raeburn  14813: =item $udom, student's domain
1.297     matthew  14814: 
1.1172.2.31  raeburn  14815: =item $uname, student's name
1.297     matthew  14816: 
1.1172.2.31  raeburn  14817: =item $uid, student's user id
1.297     matthew  14818: 
1.1172.2.31  raeburn  14819: =item $first, student's first name
1.297     matthew  14820: 
                   14821: =item $middle
                   14822: 
                   14823: =item $last
                   14824: 
                   14825: =item $gene
                   14826: 
                   14827: =item $usec
                   14828: 
                   14829: =item $end
                   14830: 
                   14831: =item $start
                   14832: 
1.957     raeburn  14833: =item $type
                   14834: 
                   14835: =item $locktype
                   14836: 
                   14837: =item $cid
                   14838: 
                   14839: =item $selfenroll
                   14840: 
                   14841: =item $context
                   14842: 
1.1172.2.19  raeburn  14843: =item $credits, number of credits student will earn from this class
                   14844: 
1.1172.2.76  raeburn  14845: =item $instsec, institutional course section code for student
                   14846: 
1.297     matthew  14847: =back
                   14848: 
1.191     harris41 14849: 
                   14850: =item *
                   14851: 
1.243     albertel 14852: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14853: custom role; give a custom role to a user for the level given by URL.  Specify
                   14854: name and domain of role author, and role name
1.191     harris41 14855: 
                   14856: =item *
                   14857: 
1.243     albertel 14858: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14859: 
                   14860: =item *
                   14861: 
1.243     albertel 14862: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14863: 
                   14864: =back
                   14865: 
                   14866: =head2 Course Infomation
                   14867: 
                   14868: =over 4
1.191     harris41 14869: 
                   14870: =item *
                   14871: 
1.1118    foxr     14872: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14873: specified course id, including all environment settings for the
                   14874: course, the description of the course will be in the hash under the
                   14875: key 'description'
1.191     harris41 14876: 
1.1118    foxr     14877: $options is an optional parameter that if supplied is a hash reference that controls
                   14878: what how this function works.  It has the following key/values:
                   14879: 
                   14880: =over 4
                   14881: 
                   14882: =item freshen_cache
                   14883: 
                   14884: If defined, and the environment cache for the course is valid, it is 
                   14885: returned in the returned hash.
                   14886: 
                   14887: =item one_time
                   14888: 
                   14889: If defined, the last cache time is set to _now_
                   14890: 
                   14891: =item user
                   14892: 
                   14893: If defined, the supplied username is used instead of the current user.
                   14894: 
                   14895: 
                   14896: =back
                   14897: 
1.191     harris41 14898: =item *
                   14899: 
1.624     albertel 14900: resdata($name,$domain,$type,@which) : request for current parameter
                   14901: setting for a specific $type, where $type is either 'course' or 'user',
                   14902: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  14903: answers for 10 minutes.
1.243     albertel 14904: 
1.877     foxr     14905: =item *
                   14906: 
                   14907: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14908: data base, returning a hash that is keyed by the resource name and has
                   14909: values that are the resource value.  I believe that the timestamps and
                   14910: versions are also returned.
                   14911: 
1.1172.2.31  raeburn  14912: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14913: supplemental content area. This routine caches the number of files for
                   14914: 10 minutes.
                   14915: 
1.243     albertel 14916: =back
                   14917: 
                   14918: =head2 Course Modification
                   14919: 
                   14920: =over 4
1.191     harris41 14921: 
                   14922: =item *
                   14923: 
1.243     albertel 14924: writecoursepref($courseid,%prefs) : write preferences (environment
                   14925: database) for a course
1.191     harris41 14926: 
                   14927: =item *
                   14928: 
1.1011    raeburn  14929: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14930: 
                   14931: =item *
                   14932: 
1.1038    raeburn  14933: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14934: 
1.1167    droeschl 14935: =item *
                   14936: 
                   14937: is_course($courseid), is_course($cdom, $cnum)
                   14938: 
                   14939: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14940: two component version $cdom, $cnum. It checks if the specified course exists.
                   14941: 
                   14942: Returns:
                   14943:     undef if the course doesn't exist, otherwise
                   14944:     in scalar context the combined courseid.
                   14945:     in list context the two components of the course identifier, domain and 
                   14946:     courseid.    
                   14947: 
1.243     albertel 14948: =back
                   14949: 
1.1172.2.109  raeburn  14950: =head2 Bubblesheet Configuration
                   14951: 
                   14952: =over 4
                   14953: 
                   14954: =item *
                   14955: 
                   14956: get_scantron_config($which)
                   14957: 
                   14958: $which - the name of the configuration to parse from the file.
                   14959: 
                   14960: Parses and returns the bubblesheet configuration line selected as a
                   14961: hash of configuration file fields.
                   14962: 
                   14963: 
                   14964: Returns:
                   14965:     If the named configuration is not in the file, an empty
                   14966:     hash is returned.
                   14967: 
                   14968:     a hash with the fields
                   14969:       name         - internal name for the this configuration setup
                   14970:       description  - text to display to operator that describes this config
                   14971:       CODElocation - if 0 or the string 'none'
                   14972:                           - no CODE exists for this config
                   14973:                      if -1 || the string 'letter'
                   14974:                           - a CODE exists for this config and is
                   14975:                             a string of letters
                   14976:                      Unsupported value (but planned for future support)
                   14977:                           if a positive integer
                   14978:                                - The CODE exists as the first n items from
                   14979:                                  the question section of the form
                   14980:                           if the string 'number'
                   14981:                                - The CODE exists for this config and is
                   14982:                                  a string of numbers
                   14983:       CODEstart   - (only matter if a CODE exists) column in the line where
                   14984:                      the CODE starts
                   14985:       CODElength  - length of the CODE
                   14986:       IDstart     - column where the student/employee ID starts
                   14987:       IDlength    - length of the student/employee ID info
                   14988:       Qstart      - column where the information from the bubbled
                   14989:                     'questions' start
                   14990:       Qlength     - number of columns comprising a single bubble line from
                   14991:                     the sheet. (usually either 1 or 10)
                   14992:       Qon         - either a single character representing the character used
                   14993:                     to signal a bubble was chosen in the positional setup, or
                   14994:                     the string 'letter' if the letter of the chosen bubble is
                   14995:                     in the final, or 'number' if a number representing the
                   14996:                     chosen bubble is in the file (1->A 0->J)
                   14997:       Qoff        - the character used to represent that a bubble was
                   14998:                     left blank
                   14999:       PaperID     - if the scanning process generates a unique number for each
                   15000:                     sheet scanned the column that this ID number starts in
                   15001:       PaperIDlength - number of columns that comprise the unique ID number
                   15002:                       for the sheet of paper
                   15003:       FirstName   - column that the first name starts in
                   15004:       FirstNameLength - number of columns that the first name spans
                   15005:       LastName    - column that the last name starts in
                   15006:       LastNameLength - number of columns that the last name spans
                   15007:       BubblesPerRow - number of bubbles available in each row used to
                   15008:                       bubble an answer. (If not specified, 10 assumed).
                   15009: 
                   15010: 
                   15011: =item *
                   15012: 
                   15013: get_scantronformat_file($cdom)
                   15014: 
                   15015: $cdom - the course's domain (optional); if not supplied, uses
                   15016: domain for current $env{'request.course.id'}.
                   15017: 
                   15018: Returns an array containing lines from the scantron format file for
                   15019: the domain of the course.
                   15020: 
                   15021: If a url for a custom.tab file is listed in domain's configuration.db,
                   15022: lines are from this file.
                   15023: 
                   15024: Otherwise, if a default.tab has been published in RES space by the
                   15025: domainconfig user, lines are from this file.
                   15026: 
                   15027: Otherwise, fall back to getting lines from the legacy file on the
                   15028: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   15029: 
                   15030: =back
                   15031: 
1.243     albertel 15032: =head2 Resource Subroutines
                   15033: 
                   15034: =over 4
1.191     harris41 15035: 
                   15036: =item *
                   15037: 
1.243     albertel 15038: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 15039: 
                   15040: =item *
                   15041: 
1.243     albertel 15042: repcopy($filename) : subscribes to the requested file, and attempts to
                   15043: replicate from the owning library server, Might return
1.607     raeburn  15044: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   15045: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 15046: resource. Expects the local filesystem pathname
                   15047: (/home/httpd/html/res/....)
                   15048: 
                   15049: =back
                   15050: 
                   15051: =head2 Resource Information
                   15052: 
                   15053: =over 4
1.191     harris41 15054: 
                   15055: =item *
                   15056: 
1.1172.2.28  raeburn  15057: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   15058: and returns the value of a variety of different possible values,
                   15059: $varname should be a request string, and the other parameters can be
                   15060: used to specify who and what one is asking about. Ordinarily, $cid 
                   15061: does not need to be specified, as it is retrived from 
                   15062: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   15063: within lonuserstate::loadmap() when initializing a course, before
                   15064: $env{'request.course.id'} has been set, so it needs to be provided
                   15065: in that one case.
1.243     albertel 15066: 
                   15067: Possible values for $varname are environment.lastname (or other item
                   15068: from the envirnment hash), user.name (or someother aspect about the
                   15069: user), resource.0.maxtries (or some other part and parameter of a
                   15070: resource)
1.204     albertel 15071: 
                   15072: =item *
                   15073: 
1.243     albertel 15074: directcondval($number) : get current value of a condition; reads from a state
                   15075: string
1.204     albertel 15076: 
                   15077: =item *
                   15078: 
1.243     albertel 15079: condval($condidx) : value of condition index based on state
1.204     albertel 15080: 
                   15081: =item *
                   15082: 
1.243     albertel 15083: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   15084: resource's metadata, $what should be either a specific key, or either
                   15085: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   15086: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   15087: 
                   15088: this function automatically caches all requests
1.191     harris41 15089: 
                   15090: =item *
                   15091: 
1.243     albertel 15092: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15093: network of library servers; returns file handle of where SQL and regex results
                   15094: will be stored for query
1.191     harris41 15095: 
                   15096: =item *
                   15097: 
1.1172.2.66  raeburn  15098: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   15099: return symbolic list entry (all arguments optional).
                   15100: 
                   15101: Args: filename is the filename (including path) for the file for which a symb
                   15102: is required; donotrecurse, if true will prevent calls to allowed() being made
                   15103: to check access status if more than one resource was found in the bighash
                   15104: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   15105: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   15106: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15107: cause possible symbs to be checked to determine if they are subject to content
                   15108: blocking, if so they will not be included as possible symbs; possibles is a
                   15109: ref to a hash, which, as a side effect, will be populated with all possible
                   15110: symbs (content blocking not tested).
                   15111: 
1.243     albertel 15112: returns the data handle
1.191     harris41 15113: 
                   15114: =item *
                   15115: 
1.1172.2.17  raeburn  15116: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  15117: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15118: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  15119: on failure, user must be in a course, as it assumes the existence of
                   15120: the course initial hash, and uses $env('request.course.id'}.  The third
                   15121: arg is an optional reference to a scalar.  If this arg is passed in the
                   15122: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15123: encrypted; otherwise it will be null.
1.243     albertel 15124: 
1.191     harris41 15125: =item *
                   15126: 
1.243     albertel 15127: symbclean($symb) : removes versions numbers from a symb, returns the
                   15128: cleaned symb
1.191     harris41 15129: 
                   15130: =item *
                   15131: 
1.243     albertel 15132: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15133: course map, user must be in a course for it to work.
1.191     harris41 15134: 
                   15135: =item *
                   15136: 
1.243     albertel 15137: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15138: 
                   15139: =item *
                   15140: 
1.243     albertel 15141: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15142: a random seed, all arguments are optional, if they aren't sent it uses the
                   15143: environment to derive them. Note: if symb isn't sent and it can't get one
                   15144: from &symbread it will use the current time as its return value
1.191     harris41 15145: 
                   15146: =item *
                   15147: 
1.243     albertel 15148: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15149: unfakeable, receipt
1.191     harris41 15150: 
                   15151: =item *
                   15152: 
1.620     albertel 15153: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15154: 
                   15155: =item *
                   15156: 
1.243     albertel 15157: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15158: 
                   15159: =item *
                   15160: 
1.243     albertel 15161: 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 15162: 
                   15163: =item *
                   15164: 
1.243     albertel 15165: 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 15166: 
                   15167: =item *
                   15168: 
1.243     albertel 15169: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15170: 
                   15171: =item *
                   15172: 
1.243     albertel 15173: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15174: forcing spreadsheet to reevaluate the resource scores next time.
                   15175: 
1.1172.2.13  raeburn  15176: =item *
                   15177: 
                   15178: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15179: when viewing in course context.
                   15180: 
                   15181:  input: six args -- filename (decluttered), course number, course domain,
                   15182:                     url, symb (if registered) and group (if this is a
                   15183:                     group item -- e.g., bulletin board, group page etc.).
                   15184: 
                   15185:  output: array of five scalars --
                   15186:          $cfile -- url for file editing if editable on current server
                   15187:          $home -- homeserver of resource (i.e., for author if published,
                   15188:                                           or course if uploaded.).
                   15189:          $switchserver --  1 if server switch will be needed.
                   15190:          $forceedit -- 1 if icon/link should be to go to edit mode
                   15191:          $forceview -- 1 if icon/link should be to go to view mode
                   15192: 
                   15193: =item *
                   15194: 
                   15195: is_course_upload($file,$cnum,$cdom)
                   15196: 
                   15197: Used in course context to determine if current file was uploaded to
                   15198: the course (i.e., would be found in /userfiles/docs on the course's
                   15199: homeserver.
                   15200: 
                   15201:   input: 3 args -- filename (decluttered), course number and course domain.
                   15202:   output: boolean -- 1 if file was uploaded.
                   15203: 
1.243     albertel 15204: =back
                   15205: 
                   15206: =head2 Storing/Retreiving Data
                   15207: 
                   15208: =over 4
1.191     harris41 15209: 
                   15210: =item *
                   15211: 
1.1172.2.64  raeburn  15212: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   15213: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15214: the remaining args aren't required and if they aren't passed or are '' they will
                   15215: be derived from the env (with the exception of $laststore, which is an
                   15216: optional arg used when a user's submission is stored in grading).
                   15217: $laststore is $version=$timestamp, where $version is the most recent version
                   15218: number retrieved for the corresponding $symb in the $namespace db file, and
                   15219: $timestamp is the timestamp for that transaction (UNIX time).
                   15220: $laststore is currently only passed when cstore() is called by
                   15221: structuretags::finalize_storage().
1.191     harris41 15222: 
                   15223: =item *
                   15224: 
1.1172.2.64  raeburn  15225: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   15226: but uses critical subroutine
1.191     harris41 15227: 
                   15228: =item *
                   15229: 
1.243     albertel 15230: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15231: all args are optional
1.191     harris41 15232: 
                   15233: =item *
                   15234: 
1.717     albertel 15235: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15236: dumps the complete (or key matching regexp) namespace into a hash
                   15237: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15238: normally &store()ed into
                   15239: 
                   15240: $range should be either an integer '100' (give me the first 100
                   15241:                                            matching records)
                   15242:               or be  two integers sperated by a - with no spaces
                   15243:                  '30-50' (give me the 30th through the 50th matching
                   15244:                           records)
                   15245: 
                   15246: 
                   15247: =item *
                   15248: 
1.1172.2.59  raeburn  15249: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15250: replaces a &store() version of data with a replacement set of data
                   15251: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  15252: reference. If $tolog is true, the transaction is logged in the courselog
                   15253: with an action=PUTSTORE.
1.717     albertel 15254: 
                   15255: =item *
                   15256: 
1.243     albertel 15257: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15258: works very similar to store/cstore, but all data is stored in a
                   15259: temporary location and can be reset using tmpreset, $storehash should
                   15260: be a hash reference, returns nothing on success
1.191     harris41 15261: 
                   15262: =item *
                   15263: 
1.243     albertel 15264: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15265: similar to restore, but all data is stored in a temporary location and
                   15266: can be reset using tmpreset. Returns a hash of values on success,
                   15267: error string otherwise.
1.191     harris41 15268: 
                   15269: =item *
                   15270: 
1.243     albertel 15271: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15272: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15273: 
                   15274: =item *
                   15275: 
1.243     albertel 15276: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15277: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15278: 
                   15279: =item *
                   15280: 
1.243     albertel 15281: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15282: namesp ($udom and $uname are optional)
1.191     harris41 15283: 
                   15284: =item *
                   15285: 
1.702     albertel 15286: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15287: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15288: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15289: 
1.702     albertel 15290: $range should be either an integer '100' (give me the first 100
                   15291:                                            matching records)
                   15292:               or be  two integers sperated by a - with no spaces
                   15293:                  '30-50' (give me the 30th through the 50th matching
                   15294:                           records)
1.449     matthew  15295: =item *
                   15296: 
                   15297: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15298: $store can be a scalar, an array reference, or if the amount to be 
                   15299: incremented is > 1, a hash reference.
                   15300: 
                   15301: ($udom and $uname are optional)
1.191     harris41 15302: 
                   15303: =item *
                   15304: 
1.243     albertel 15305: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15306: ($udom and $uname are optional)
1.191     harris41 15307: 
                   15308: =item *
                   15309: 
1.243     albertel 15310: cput($namespace,$storehash,$udom,$uname) : critical put
                   15311: ($udom and $uname are optional)
1.191     harris41 15312: 
                   15313: =item *
                   15314: 
1.748     albertel 15315: newput($namespace,$storehash,$udom,$uname) :
                   15316: 
                   15317: Attempts to store the items in the $storehash, but only if they don't
                   15318: currently exist, if this succeeds you can be certain that you have 
                   15319: successfully created a new key value pair in the $namespace db.
                   15320: 
                   15321: 
                   15322: Args:
                   15323:  $namespace: name of database to store values to
                   15324:  $storehash: hashref to store to the db
                   15325:  $udom: (optional) domain of user containing the db
                   15326:  $uname: (optional) name of user caontaining the db
                   15327: 
                   15328: Returns:
                   15329:  'ok' -> succeeded in storing all keys of $storehash
                   15330:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15331:                         least <key> already existed in the db (other
                   15332:                         requested keys may also already exist)
1.967     bisitz   15333:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15334:  'con_lost' -> unable to contact request server
                   15335:  'refused' -> action was not allowed by remote machine
                   15336: 
                   15337: 
                   15338: =item *
                   15339: 
1.243     albertel 15340: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15341: reference filled in from namesp (encrypts the return communication)
                   15342: ($udom and $uname are optional)
1.191     harris41 15343: 
                   15344: =item *
                   15345: 
1.243     albertel 15346: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15347: critical subroutine
                   15348: 
1.806     raeburn  15349: =item *
                   15350: 
1.860     raeburn  15351: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15352: array reference filled in from namespace found in domain level on either
                   15353: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15354: 
                   15355: =item *
                   15356: 
1.860     raeburn  15357: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15358: domain level either on specified domain server ($uhome) or primary domain 
                   15359: server ($udom and $uhome are optional)
1.806     raeburn  15360: 
1.943     raeburn  15361: =item * 
                   15362: 
1.1172.2.35  raeburn  15363: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   15364: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15365: the target domain.
                   15366: 
                   15367: May also include additional key => value pairs for the following groups:
                   15368: 
                   15369: =over
                   15370: 
                   15371: =item
                   15372: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15373: 
                   15374: =over
                   15375: 
                   15376: =item defaultquota, authorquota
                   15377: 
                   15378: =back
                   15379: 
                   15380: =item
                   15381: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15382: portfolio for users).
                   15383: 
                   15384: =over
                   15385: 
                   15386: =item
                   15387: aboutme, blog, webdav, portfolio
                   15388: 
                   15389: =back
                   15390: 
                   15391: =item
                   15392: requestcourses: ability to request courses, and how requests are processed.
                   15393: 
                   15394: =over
                   15395: 
                   15396: =item
1.1172.2.37  raeburn  15397: official, unofficial, community, textbook
1.1172.2.35  raeburn  15398: 
                   15399: =back
                   15400: 
                   15401: =item
                   15402: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15403: 
                   15404: =over
                   15405: 
                   15406: =item
1.1172.2.44  raeburn  15407: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  15408: 
                   15409: =back
                   15410: 
                   15411: =item
                   15412: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15413: for course's uploaded content.
                   15414: 
                   15415: =over
                   15416: 
                   15417: =item
1.1172.2.68  raeburn  15418: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   15419: communityquota, textbookquota
1.1172.2.35  raeburn  15420: 
                   15421: =back
                   15422: 
                   15423: =item
                   15424: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15425: on your servers.
                   15426: 
                   15427: =over
                   15428: 
                   15429: =item
                   15430: remotesessions, hostedsessions
                   15431: 
                   15432: =back
                   15433: 
                   15434: =back
                   15435: 
                   15436: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15437: utility to create a configuration.db file on a domain's primary library server
                   15438: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15439: -- corresponding values are authentication type (internal, krb4, krb5,
                   15440: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   15441: will be available. Values are retrieved from cache (if current), unless the
                   15442: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15443: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15444: 
                   15445: Typical usage:
1.943     raeburn  15446: 
1.1172.2.35  raeburn  15447: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15448: 
1.243     albertel 15449: =back
                   15450: 
                   15451: =head2 Network Status Functions
                   15452: 
                   15453: =over 4
1.191     harris41 15454: 
                   15455: =item *
                   15456: 
1.1137    raeburn  15457: dirlist() : return directory list based on URI (first arg).
                   15458: 
                   15459: Inputs: 1 required, 5 optional.
                   15460: 
                   15461: =over
                   15462: 
                   15463: =item 
                   15464: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15465: 
                   15466: =item
                   15467: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15468: 
                   15469: =item
                   15470: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15471: 
                   15472: =item
                   15473: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15474: 
                   15475: =item
                   15476: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15477: 
                   15478: =item 
                   15479: $alternateRoot - path to prepend in place of path from $uri.
                   15480: 
                   15481: =back
                   15482: 
                   15483: Returns: Array of up to two items.
                   15484: 
                   15485: =over
                   15486: 
                   15487: a reference to an array of files/subdirectories
                   15488: 
                   15489: =over
                   15490: 
                   15491: Each element in the array of files/subdirectories is a & separated list of
                   15492: item name and the result of running stat on the item.  If dirlist was requested
                   15493: for a file instead of a directory, the item name will be ''. For a directory 
                   15494: listing, if the item is a metadata file, the element will end &N&M 
                   15495: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15496: default copyright set (1).  
                   15497: 
                   15498: =back
                   15499: 
                   15500: a scalar containing error condition (if encountered).
                   15501: 
                   15502: =over
                   15503: 
                   15504: =item 
                   15505: no_host (no homeserver identified for $username:$domain).
                   15506: 
                   15507: =item 
                   15508: no_such_host (server contacted for listing not identified as valid host).
                   15509: 
                   15510: =item 
                   15511: con_lost (connection to remote server failed).
                   15512: 
                   15513: =item 
                   15514: refused (invalid $username:$domain received on lond side).
                   15515: 
                   15516: =item 
                   15517: no_such_dir (directory at specified path on lond side does not exist). 
                   15518: 
                   15519: =item 
                   15520: empty (directory at specified path on lond side is empty).
                   15521: 
                   15522: =over
                   15523: 
                   15524: This is currently not encountered because the &ls3, &ls2, 
                   15525: &ls (_handler) routines on the lond side do not filter out
                   15526: . and .. from a directory listing. 
                   15527: 
                   15528: =back
                   15529: 
                   15530: =back
                   15531: 
                   15532: =back
1.191     harris41 15533: 
                   15534: =item *
                   15535: 
1.243     albertel 15536: spareserver() : find server with least workload from spare.tab
                   15537: 
1.986     foxr     15538: 
                   15539: =item *
                   15540: 
                   15541: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15542: if there is no corresponding loncapa host.
                   15543: 
1.243     albertel 15544: =back
                   15545: 
1.986     foxr     15546: 
1.243     albertel 15547: =head2 Apache Request
                   15548: 
                   15549: =over 4
1.191     harris41 15550: 
                   15551: =item *
                   15552: 
1.243     albertel 15553: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15554: localhost, posts hash
                   15555: 
                   15556: =back
                   15557: 
                   15558: =head2 Data to String to Data
                   15559: 
                   15560: =over 4
1.191     harris41 15561: 
                   15562: =item *
                   15563: 
1.243     albertel 15564: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15565: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15566: 
                   15567: =item *
                   15568: 
1.243     albertel 15569: hashref2str($hashref) : convert a hashref into a string complete with
                   15570: escaping and '=' and '&' separators, supports elements that are
                   15571: arrayrefs and hashrefs
1.191     harris41 15572: 
                   15573: =item *
                   15574: 
1.243     albertel 15575: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15576: with escaping and '&' separators, supports elements that are arrayrefs
                   15577: and hashrefs
1.191     harris41 15578: 
                   15579: =item *
                   15580: 
1.243     albertel 15581: str2hash($string) : convert string to hash using unescaping and
                   15582: splitting on '=' and '&', supports elements that are arrayrefs and
                   15583: hashrefs
1.191     harris41 15584: 
                   15585: =item *
                   15586: 
1.243     albertel 15587: str2array($string) : convert string to hash using unescaping and
                   15588: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15589: 
                   15590: =back
                   15591: 
                   15592: =head2 Logging Routines
                   15593: 
                   15594: 
                   15595: These routines allow one to make log messages in the lonnet.log and
                   15596: lonnet.perm logfiles.
1.191     harris41 15597: 
1.1119    foxr     15598: =over 4
                   15599: 
1.191     harris41 15600: =item *
                   15601: 
1.243     albertel 15602: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15603: 
                   15604: =item *
                   15605: 
1.243     albertel 15606: logthis() : append message to the normal lonnet.log file, it gets
                   15607: preiodically rolled over and deleted.
1.191     harris41 15608: 
                   15609: =item *
                   15610: 
1.243     albertel 15611: logperm() : append a permanent message to lonnet.perm.log, this log
                   15612: file never gets deleted by any automated portion of the system, only
                   15613: messages of critical importance should go in here.
                   15614: 
1.1119    foxr     15615: 
1.243     albertel 15616: =back
                   15617: 
                   15618: =head2 General File Helper Routines
                   15619: 
                   15620: =over 4
1.191     harris41 15621: 
                   15622: =item *
                   15623: 
1.481     raeburn  15624: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15625: (a) files in /uploaded
                   15626:   (i) If a local copy of the file exists - 
                   15627:       compares modification date of local copy with last-modified date for 
                   15628:       definitive version stored on home server for course. If local copy is 
                   15629:       stale, requests a new version from the home server and stores it. 
                   15630:       If the original has been removed from the home server, then local copy 
                   15631:       is unlinked.
                   15632:   (ii) If local copy does not exist -
                   15633:       requests the file from the home server and stores it. 
                   15634:   
                   15635:   If $caller is 'uploadrep':  
                   15636:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15637:     for request for files originally uploaded via DOCS. 
                   15638:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15639:   
                   15640:   Otherwise:
                   15641:      This indicates a call from the content generation phase of the request.
                   15642:      -  returns the entire contents of the file or -1.
                   15643:      
                   15644: (b) files in /res
                   15645:    - returns the entire contents of a file or -1; 
                   15646:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15647: 
1.712     albertel 15648: 
                   15649: =item *
                   15650: 
                   15651: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15652:                   reference
                   15653: 
                   15654: returns either a stat() list of data about the file or an empty list
                   15655: if the file doesn't exist or couldn't find out about it (connection
                   15656: problems or user unknown)
                   15657: 
1.191     harris41 15658: =item *
                   15659: 
1.243     albertel 15660: filelocation($dir,$file) : returns file system location of a file
                   15661: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15662: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15663: and a file of ../bob will become /a/bob)
1.191     harris41 15664: 
                   15665: =item *
                   15666: 
                   15667: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15668: filelocation except for hrefs
                   15669: 
                   15670: =item *
                   15671: 
1.1172.2.49  raeburn  15672: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15673: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15674: 
1.243     albertel 15675: =back
                   15676: 
1.608     albertel 15677: =head2 Usererfile file routines (/uploaded*)
                   15678: 
                   15679: =over 4
                   15680: 
                   15681: =item *
                   15682: 
                   15683: userfileupload(): main rotine for putting a file in a user or course's
                   15684:                   filespace, arguments are,
                   15685: 
1.620     albertel 15686:  formname - required - this is the name of the element in $env where the
1.608     albertel 15687:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15688:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15689:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15690:  context - if coursedoc, store the file in the course of the active role
                   15691:              of the current user; 
                   15692:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15693:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15694:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15695:          if undefined, it will be placed in "unknown"
                   15696: 
                   15697:  (This routine calls clean_filename() to remove any dangerous
                   15698:  characters from the filename, and then calls finuserfileupload() to
                   15699:  complete the transaction)
                   15700: 
                   15701:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15702:  and /adm/notfound.html if unsuccessful
                   15703: 
                   15704: =item *
                   15705: 
                   15706: clean_filename(): routine for cleaing a filename up for storage in
                   15707:                  userfile space, argument is:
                   15708: 
                   15709:  filename - proposed filename
                   15710: 
                   15711: returns: the new clean filename
                   15712: 
                   15713: =item *
                   15714: 
1.1090    raeburn  15715: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15716: userspace, probably shouldn't be called directly
                   15717: 
                   15718:   docuname: username or courseid of destination for the file
                   15719:   docudom: domain of user/course of destination for the file
                   15720:   formname: same as for userfileupload()
1.1090    raeburn  15721:   fname: filename (including subdirectories) for the file
                   15722:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  15723:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  15724:   allfiles: reference to hash used to store objects found by parser
                   15725:   codebase: reference to hash used for codebases of java objects found by parser
                   15726:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15727:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15728:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15729:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15730:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15731:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15732:   mimetype: reference to scalar to accommodate mime type determined
                   15733:             from File::MMagic if $parser = parse.
1.608     albertel 15734: 
                   15735:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15736:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15737:  was 'overwrite').
                   15738:  
1.608     albertel 15739: 
                   15740: =item *
                   15741: 
                   15742: renameuserfile(): renames an existing userfile to a new name
                   15743: 
                   15744:   Args:
                   15745:    docuname: username or courseid of destination for the file
                   15746:    docudom: domain of user/course of destination for the file
                   15747:    old: current file name (including any subdirs under userfiles)
                   15748:    new: desired file name (including any subdirs under userfiles)
                   15749: 
                   15750: =item *
                   15751: 
                   15752: mkdiruserfile(): creates a directory is a userfiles dir
                   15753: 
                   15754:   Args:
                   15755:    docuname: username or courseid of destination for the file
                   15756:    docudom: domain of user/course of destination for the file
                   15757:    dir: dir to create (including any subdirs under userfiles)
                   15758: 
                   15759: =item *
                   15760: 
                   15761: removeuserfile(): removes a file that exists in userfiles
                   15762: 
                   15763:   Args:
                   15764:    docuname: username or courseid of destination for the file
                   15765:    docudom: domain of user/course of destination for the file
                   15766:    fname: filname to delete (including any subdirs under userfiles)
                   15767: 
                   15768: =item *
                   15769: 
                   15770: removeuploadedurl(): convience function for removeuserfile()
                   15771: 
                   15772:   Args:
                   15773:    url:  a full /uploaded/... url to delete
                   15774: 
1.747     albertel 15775: =item * 
                   15776: 
                   15777: get_portfile_permissions():
                   15778:   Args:
                   15779:     domain: domain of user or course contain the portfolio files
                   15780:     user: name of user or num of course contain the portfolio files
                   15781:   Returns:
                   15782:     hashref of a dump of the proper file_permissions.db
                   15783:    
                   15784: 
                   15785: =item * 
                   15786: 
                   15787: get_access_controls():
                   15788: 
                   15789: Args:
                   15790:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15791:   group: (optional) the group you want the files associated with
                   15792:   file: (optional) the file you want access info on
                   15793: 
                   15794: Returns:
1.749     raeburn  15795:     a hash (keys are file names) of hashes containing
                   15796:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15797:         values are XML containing access control settings (see below) 
1.747     albertel 15798: 
                   15799: Internal notes:
                   15800: 
1.749     raeburn  15801:  access controls are stored in file_permissions.db as key=value pairs.
                   15802:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15803:         where scope -> public,guest,course,group,domains or users.
                   15804:               end -> UNIX time for end of access (0 -> no end date)
                   15805:               start -> UNIX time for start of access
                   15806: 
                   15807:     value -> XML description of access control
                   15808:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15809:             <start></start>
                   15810:             <end></end>
                   15811: 
                   15812:             <password></password>  for scope type = guest
                   15813: 
                   15814:             <domain></domain>     for scope type = course or group
                   15815:             <number></number>
                   15816:             <roles id="">
                   15817:              <role></role>
                   15818:              <access></access>
                   15819:              <section></section>
                   15820:              <group></group>
                   15821:             </roles>
                   15822: 
                   15823:             <dom></dom>         for scope type = domains
                   15824: 
                   15825:             <users>             for scope type = users
                   15826:              <user>
                   15827:               <uname></uname>
                   15828:               <udom></udom>
                   15829:              </user>
                   15830:             </users>
                   15831:            </scope> 
                   15832:               
                   15833:  Access data is also aggregated for each file in an additional key=value pair:
                   15834:  key -> path to file/file_name\0accesscontrol 
                   15835:  value -> reference to hash
                   15836:           hash contains key = value pairs
                   15837:           where key = uniqueID:scope_end_start
                   15838:                 value = UNIX time record was last updated
                   15839: 
                   15840:           Used to improve speed of look-ups of access controls for each file.  
                   15841:  
                   15842:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15843: 
1.1172.2.13  raeburn  15844: =item *
                   15845: 
1.749     raeburn  15846: modify_access_controls():
                   15847: 
                   15848: Modifies access controls for a portfolio file
                   15849: Args
                   15850: 1. file name
                   15851: 2. reference to hash of required changes,
                   15852: 3. domain
                   15853: 4. username
                   15854:   where domain,username are the domain of the portfolio owner 
                   15855:   (either a user or a course) 
                   15856: 
                   15857: Returns:
                   15858: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15859: 2. result of deletions ('ok' or 'error', with error message).
                   15860: 3. reference to hash of any new or updated access controls.
                   15861: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15862:    key = integer (inbound ID)
1.1172.2.13  raeburn  15863:    value = uniqueID
                   15864: 
                   15865: =item *
                   15866: 
                   15867: get_timebased_id():
                   15868: 
                   15869: Attempts to get a unique timestamp-based suffix for use with items added to a
                   15870: course via the Course Editor (e.g., folders, composite pages,
                   15871: group bulletin boards).
                   15872: 
                   15873: Args: (first three required; six others optional)
                   15874: 
                   15875: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15876:    docssequence, or name of group
                   15877: 
                   15878: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15879:    e.g., num, boardids
                   15880: 
                   15881: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   15882:    file will be named nohist_namespace.db
                   15883: 
                   15884: 4. cdom: domain of course; default is current course domain from %env
                   15885: 
                   15886: 5. cnum: course number; default is current course number from %env
                   15887: 
                   15888: 6. idtype: set to concat if an additional digit is to be appended to the
                   15889:    unix timestamp to form the suffix, if the plain timestamp is already
                   15890:    in use.  Default is to not do this, but simply increment the unix
                   15891:    timestamp by 1 until a unique key is obtained.
                   15892: 
                   15893: 7. who: holder of locking key; defaults to user:domain for user.
                   15894: 
                   15895: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   15896:    retrying); default is 3.
                   15897: 
                   15898: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   15899: 
                   15900: Returns:
                   15901: 
                   15902: 1. suffix obtained (numeric)
                   15903: 
                   15904: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15905: 
                   15906: 3. error: contains (localized) error message if an error occurred.
                   15907: 
1.747     albertel 15908: 
1.608     albertel 15909: =back
                   15910: 
1.243     albertel 15911: =head2 HTTP Helper Routines
                   15912: 
                   15913: =over 4
                   15914: 
1.191     harris41 15915: =item *
                   15916: 
                   15917: escape() : unpack non-word characters into CGI-compatible hex codes
                   15918: 
                   15919: =item *
                   15920: 
                   15921: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15922: 
1.243     albertel 15923: =back
                   15924: 
                   15925: =head1 PRIVATE SUBROUTINES
                   15926: 
                   15927: =head2 Underlying communication routines (Shouldn't call)
                   15928: 
                   15929: =over 4
                   15930: 
                   15931: =item *
                   15932: 
                   15933: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15934: 
                   15935: =item *
                   15936: 
                   15937: reply() : uses subreply to send a message to remote machine, logs all failures
                   15938: 
                   15939: =item *
                   15940: 
                   15941: critical() : passes a critical message to another server; if cannot
                   15942: get through then place message in connection buffer directory and
                   15943: returns con_delayed, if incapable of saving message, returns
                   15944: con_failed
                   15945: 
                   15946: =item *
                   15947: 
                   15948: reconlonc() : tries to reconnect lonc client processes.
                   15949: 
                   15950: =back
                   15951: 
                   15952: =head2 Resource Access Logging
                   15953: 
                   15954: =over 4
                   15955: 
                   15956: =item *
                   15957: 
                   15958: flushcourselogs() : flush (save) buffer logs and access logs
                   15959: 
                   15960: =item *
                   15961: 
                   15962: courselog($what) : save message for course in hash
                   15963: 
                   15964: =item *
                   15965: 
                   15966: courseacclog($what) : save message for course using &courselog().  Perform
                   15967: special processing for specific resource types (problems, exams, quizzes, etc).
                   15968: 
1.191     harris41 15969: =item *
                   15970: 
                   15971: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15972: as a PerlChildExitHandler
1.243     albertel 15973: 
                   15974: =back
                   15975: 
                   15976: =head2 Other
                   15977: 
                   15978: =over 4
                   15979: 
                   15980: =item *
                   15981: 
                   15982: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15983: 
                   15984: =back
                   15985: 
                   15986: =cut
1.877     foxr     15987: 

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