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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.146.  .3(raebu    4:22): # $Id: lonnet.pm,v 1.1172.2.146.2.2 2022/01/05 01:50:06 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
1.1172.2.107  raeburn    77: use CGI::Cookie;
1.977     amueller   78: 
1.1172.2.104  raeburn    79: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
1.1138    raeburn    80:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
1.1172.2.114  raeburn    81:             %managerstab $passwdmin);
1.871     albertel   82: 
                     83: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     84:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     85:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        86:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        87: 
1.1       albertel   88: use IO::Socket;
1.31      www        89: use GDBM_File;
1.208     albertel   90: use HTML::LCParser;
1.88      www        91: use Fcntl qw(:flock);
1.870     albertel   92: use Storable qw(thaw nfreeze);
1.1172.2.79  raeburn    93: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   94: use Cache::Memcached;
1.676     albertel   95: use Digest::MD5;
1.790     albertel   96: use Math::Random;
1.1024    raeburn    97: use File::MMagic;
1.1172.2.142  raeburn    98: use Net::CIDR;
                     99: use Sys::Hostname::FQDN();
1.807     albertel  100: use LONCAPA qw(:DEFAULT :match);
1.740     www       101: use LONCAPA::Configuration;
1.1160    www       102: use LONCAPA::lonmetadata;
1.1172.2.22  raeburn   103: use LONCAPA::Lond;
1.1172.2.110  raeburn   104: use LONCAPA::transliterate;
1.1117    foxr      105: 
1.1090    raeburn   106: use File::Copy;
1.676     albertel  107: 
1.195     www       108: my $readit;
1.1172.2.79  raeburn   109: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  110: 
1.619     albertel  111: require Exporter;
                    112: 
                    113: our @ISA = qw (Exporter);
                    114: our @EXPORT = qw(%env);
                    115: 
1.1172.2.9  raeburn   116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       117: {
                    118:     my $logid;
1.1172.2.9  raeburn   119:     sub write_log {
                    120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    121:         if ($context eq 'course') {
                    122:             if (($cnum eq '') || ($cdom eq '')) {
                    123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    125:             }
1.957     raeburn   126:         }
1.1172.2.13  raeburn   127: 	$logid ++;
1.957     raeburn   128:         my $now = time();
                    129: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.146.  .1(raebu  130:22):         my $ip = &get_requestor_ip();
1.1172.2.9  raeburn   131:         my $logentry = {
                    132:                          $id => {
                    133:                                   'exe_uname' => $env{'user.name'},
                    134:                                   'exe_udom'  => $env{'user.domain'},
                    135:                                   'exe_time'  => $now,
1.1172.2.134  raeburn   136:                                   'exe_ip'    => $ip,
1.1172.2.9  raeburn   137:                                   'delflag'   => $delflag,
                    138:                                   'logentry'  => $storehash,
                    139:                                   'uname'     => $uname,
                    140:                                   'udom'      => $udom,
                    141:                                 }
                    142:                        };
                    143:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       144:     }
                    145: }
1.1       albertel  146: 
1.163     harris41  147: sub logtouch {
                    148:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  149:     unless (-e "$execdir/logs/lonnet.log") {	
1.1172.2.96  raeburn   150: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  151: 	close $fh;
                    152:     }
                    153:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    154:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    155: }
                    156: 
1.1       albertel  157: sub logthis {
                    158:     my $message=shift;
                    159:     my $execdir=$perlvar{'lonDaemons'};
                    160:     my $now=time;
                    161:     my $local=localtime($now);
1.1172.2.96  raeburn   162:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      163: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    164: 	print $fh $logstring;
1.448     albertel  165: 	close($fh);
                    166:     }
1.1       albertel  167:     return 1;
                    168: }
                    169: 
                    170: sub logperm {
                    171:     my $message=shift;
                    172:     my $execdir=$perlvar{'lonDaemons'};
                    173:     my $now=time;
                    174:     my $local=localtime($now);
1.1172.2.96  raeburn   175:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  176: 	print $fh "$now:$message:$local\n";
                    177: 	close($fh);
                    178:     }
1.1       albertel  179:     return 1;
                    180: }
                    181: 
1.850     albertel  182: sub create_connection {
1.853     albertel  183:     my ($hostname,$lonid) = @_;
1.851     albertel  184:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  185: 				     Type    => SOCK_STREAM,
                    186: 				     Timeout => 10);
                    187:     return 0 if (!$client);
1.890     albertel  188:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  189:     my $result = <$client>;
                    190:     chomp($result);
                    191:     return 1 if ($result eq 'done');
                    192:     return 0;
                    193: }
                    194: 
1.983     raeburn   195: sub get_server_timezone {
                    196:     my ($cnum,$cdom) = @_;
                    197:     my $home=&homeserver($cnum,$cdom);
                    198:     if ($home ne 'no_host') {
                    199:         my $cachetime = 24*3600;
                    200:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    201:         if (defined($cached)) {
                    202:             return $timezone;
                    203:         } else {
                    204:             my $timezone = &reply('servertimezone',$home);
                    205:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    206:         }
                    207:     }
                    208: }
1.850     albertel  209: 
1.1106    raeburn   210: sub get_server_distarch {
                    211:     my ($lonhost,$ignore_cache) = @_;
                    212:     if (defined($lonhost)) {
                    213:         if (!defined(&hostname($lonhost))) {
                    214:             return;
                    215:         }
                    216:         my $cachetime = 12*3600;
                    217:         if (!$ignore_cache) {
                    218:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    219:             if (defined($cached)) {
                    220:                 return $distarch;
                    221:             }
                    222:         }
                    223:         my $rep = &reply('serverdistarch',$lonhost);
                    224:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    225:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    226:                 $rep eq '') {
                    227:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    228:         }
                    229:     }
                    230:     return;
                    231: }
                    232: 
1.993     raeburn   233: sub get_server_loncaparev {
1.1073    raeburn   234:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   235:     if (defined($lonhost)) {
                    236:         if (!defined(&hostname($lonhost))) {
                    237:             undef($lonhost);
                    238:         }
                    239:     }
                    240:     if (!defined($lonhost)) {
                    241:         if (defined(&domain($dom,'primary'))) {
                    242:             $lonhost=&domain($dom,'primary');
                    243:             if ($lonhost eq 'no_host') {
                    244:                 undef($lonhost);
                    245:             }
                    246:         }
                    247:     }
                    248:     if (defined($lonhost)) {
1.1073    raeburn   249:         my $cachetime = 12*3600;
                    250:         if (!$ignore_cache) {
                    251:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    252:             if (defined($cached)) {
                    253:                 return $loncaparev;
                    254:             }
                    255:         }
                    256:         my ($answer,$loncaparev);
                    257:         my @ids=&current_machine_ids();
                    258:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    259:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   260:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   261:                 $loncaparev = $1;
                    262:             }
                    263:         } else {
                    264:             $answer = &reply('serverloncaparev',$lonhost);
                    265:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    266:                 if ($caller eq 'loncron') {
                    267:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   268:                     $ua->timeout(4);
1.1172.2.120  raeburn   269:                     my $hostname = &hostname($lonhost);
1.1073    raeburn   270:                     my $protocol = $protocol{$lonhost};
                    271:                     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn   272:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073    raeburn   273:                     my $request=new HTTP::Request('GET',$url);
                    274:                     my $response=$ua->request($request);
                    275:                     unless ($response->is_error()) {
                    276:                         my $content = $response->content;
1.1081    raeburn   277:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   278:                             $loncaparev = $1;
                    279:                         }
                    280:                     }
                    281:                 } else {
                    282:                     $loncaparev = $loncaparevs{$lonhost};
                    283:                 }
1.1081    raeburn   284:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   285:                 $loncaparev = $1;
                    286:             }
1.993     raeburn   287:         }
1.1073    raeburn   288:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   289:     }
                    290: }
                    291: 
1.1074    raeburn   292: sub get_server_homeID {
                    293:     my ($hostname,$ignore_cache,$caller) = @_;
                    294:     unless ($ignore_cache) {
                    295:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    296:         if (defined($cached)) {
                    297:             return $serverhomeID;
                    298:         }
                    299:     }
                    300:     my $cachetime = 12*3600;
                    301:     my $serverhomeID;
                    302:     if ($caller eq 'loncron') { 
                    303:         my @machine_ids = &machine_ids($hostname);
                    304:         foreach my $id (@machine_ids) {
                    305:             my $response = &reply('serverhomeID',$id);
                    306:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    307:                 $serverhomeID = $response;
                    308:                 last;
                    309:             }
                    310:         }
                    311:         if ($serverhomeID eq '') {
                    312:             $serverhomeID = $machine_ids[-1];
                    313:         }
                    314:     } else {
                    315:         $serverhomeID = $serverhomeIDs{$hostname};
                    316:     }
                    317:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    318: }
                    319: 
1.1121    raeburn   320: sub get_remote_globals {
                    321:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   322:     my ($result,%returnhash,%whatneeded);
                    323:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   324:         foreach my $what (sort(keys(%{$whathash}))) {
                    325:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   326:             my ($response,$cached);
1.1121    raeburn   327:             unless ($ignore_cache) {
1.1125    raeburn   328:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   329:             }
                    330:             if (defined($cached)) {
1.1125    raeburn   331:                 $returnhash{$what} = $response;
1.1121    raeburn   332:             } else {
1.1125    raeburn   333:                 $whatneeded{$what} = 1;
1.1121    raeburn   334:             }
                    335:         }
1.1125    raeburn   336:         if (keys(%whatneeded) == 0) {
                    337:             $result = 'ok';
                    338:         } else {
1.1121    raeburn   339:             my $requested = &freeze_escape(\%whatneeded);
                    340:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   341:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    342:                 ($rep eq 'unknown_cmd')) {
                    343:                 $result = $rep;
                    344:             } else {
                    345:                 $result = 'ok';
1.1121    raeburn   346:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   347:                 foreach my $item (@pairs) {
                    348:                     my ($key,$value)=split(/=/,$item,2);
                    349:                     my $what = &unescape($key);
                    350:                     my $hashid = $lonhost.'-'.$what;
                    351:                     $returnhash{$what}=&thaw_unescape($value);
                    352:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   353:                 }
                    354:             }
                    355:         }
                    356:     }
1.1125    raeburn   357:     return ($result,\%returnhash);
1.1121    raeburn   358: }
                    359: 
1.1124    raeburn   360: sub remote_devalidate_cache {
1.1172.2.35  raeburn   361:     my ($lonhost,$cachekeys) = @_;
                    362:     my $items;
                    363:     return unless (ref($cachekeys) eq 'ARRAY');
                    364:     my $cachestr = join('&',@{$cachekeys});
                    365:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   366: }
                    367: 
1.1       albertel  368: # -------------------------------------------------- Non-critical communication
                    369: sub subreply {
                    370:     my ($cmd,$server)=@_;
1.838     albertel  371:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      372:     #
                    373:     #  With loncnew process trimming, there's a timing hole between lonc server
                    374:     #  process exit and the master server picking up the listen on the AF_UNIX
                    375:     #  socket.  In that time interval, a lock file will exist:
                    376: 
                    377:     my $lockfile=$peerfile.".lock";
                    378:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1172.2.79  raeburn   379: 	sleep(0.1);
1.549     foxr      380:     }
                    381:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      382:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      383:     #
1.550     foxr      384:     #   We'll give the connection a few tries before abandoning it.  If
                    385:     #   connection is not possible, we'll con_lost back to the client.
                    386:     #   
                    387:     my $client;
                    388:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    389: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    390: 				      Type    => SOCK_STREAM,
                    391: 				      Timeout => 10);
1.869     albertel  392: 	if ($client) {
1.550     foxr      393: 	    last;		# Connected!
1.850     albertel  394: 	} else {
1.853     albertel  395: 	    &create_connection(&hostname($server),$server);
1.550     foxr      396: 	}
1.1172.2.79  raeburn   397:         sleep(0.1);		# Try again later if failed connection.
1.550     foxr      398:     }
                    399:     my $answer;
                    400:     if ($client) {
1.704     albertel  401: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      402: 	$answer=<$client>;
                    403: 	if (!$answer) { $answer="con_lost"; }
                    404: 	chomp($answer);
                    405:     } else {
                    406: 	$answer = 'con_lost';	# Failed connection.
                    407:     }
1.1       albertel  408:     return $answer;
                    409: }
                    410: 
                    411: sub reply {
                    412:     my ($cmd,$server)=@_;
1.838     albertel  413:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  414:     my $answer=subreply($cmd,$server);
1.65      www       415:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1172.2.111  raeburn   416:         my $logged = $cmd;
                    417:         if ($cmd =~ /^encrypt:([^:]+):/) {
                    418:             my $subcmd = $1;
                    419:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
                    420:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    421:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
                    422:                 (undef,undef,my @rest) = split(/:/,$cmd);
                    423:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
                    424:                     splice(@rest,2,1,'Hidden');
                    425:                 } elsif ($subcmd eq 'passwd') {
                    426:                     splice(@rest,2,2,('Hidden','Hidden'));
                    427:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
                    428:                          ($subcmd eq 'autoexportgrades')) {
                    429:                     splice(@rest,3,1,'Hidden');
                    430:                 }
                    431:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
                    432:             }
                    433:         }
                    434:         &logthis("<font color=\"blue\">WARNING:".
                    435:                  " $logged to $server returned $answer</font>");
1.12      www       436:     }
1.1       albertel  437:     return $answer;
                    438: }
                    439: 
                    440: # ----------------------------------------------------------- Send USR1 to lonc
                    441: 
                    442: sub reconlonc {
1.891     albertel  443:     my ($lonid) = @_;
                    444:     if ($lonid) {
1.1172.2.72  raeburn   445:         my $hostname = &hostname($lonid);
1.891     albertel  446: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    447: 	if ($hostname && -e $peerfile) {
                    448: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    449: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    450: 					     Type    => SOCK_STREAM,
                    451: 					     Timeout => 10);
                    452: 	    if ($client) {
                    453: 		print $client ("reset_retries\n");
                    454: 		my $answer=<$client>;
                    455: 		#reset just this one.
                    456: 	    }
                    457: 	}
                    458: 	return;
                    459:     }
                    460: 
1.836     www       461:     &logthis("Trying to reconnect lonc");
1.1       albertel  462:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96  raeburn   463:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  464: 	my $loncpid=<$fh>;
                    465:         chomp($loncpid);
                    466:         if (kill 0 => $loncpid) {
                    467: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    468:             kill USR1 => $loncpid;
                    469:             sleep 1;
1.836     www       470:          } else {
1.12      www       471: 	    &logthis(
1.672     albertel  472:                "<font color=\"blue\">WARNING:".
1.12      www       473:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  474:         }
                    475:     } else {
1.836     www       476: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  477:     }
                    478: }
                    479: 
                    480: # ------------------------------------------------------ Critical communication
1.12      www       481: 
1.1       albertel  482: sub critical {
                    483:     my ($cmd,$server)=@_;
1.838     albertel  484:     unless (&hostname($server)) {
1.672     albertel  485:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       486:                " Critical message to unknown server ($server)</font>");
                    487:         return 'no_such_host';
                    488:     }
1.1       albertel  489:     my $answer=reply($cmd,$server);
                    490:     if ($answer eq 'con_lost') {
1.1172.2.72  raeburn   491: 	&reconlonc($server);
1.589     albertel  492: 	my $answer=reply($cmd,$server);
1.1       albertel  493:         if ($answer eq 'con_lost') {
                    494:             my $now=time;
                    495:             my $middlename=$cmd;
1.5       www       496:             $middlename=substr($middlename,0,16);
1.1       albertel  497:             $middlename=~s/\W//g;
                    498:             my $dfilename=
1.305     www       499:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    500:             $dumpcount++;
1.1       albertel  501:             {
1.448     albertel  502: 		my $dfh;
1.1172.2.96  raeburn   503: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  504: 		    print $dfh "$cmd\n"; 
                    505: 		    close($dfh);
                    506: 		}
1.1       albertel  507:             }
1.1172.2.79  raeburn   508:             sleep 1;
1.1       albertel  509:             my $wcmd='';
                    510:             {
1.448     albertel  511: 		my $dfh;
1.1172.2.96  raeburn   512: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  513: 		    $wcmd=<$dfh>; 
                    514: 		    close($dfh);
                    515: 		}
1.1       albertel  516:             }
                    517:             chomp($wcmd);
1.7       www       518:             if ($wcmd eq $cmd) {
1.672     albertel  519: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       520:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  521:                 &logperm("D:$server:$cmd");
                    522: 	        return 'con_delayed';
                    523:             } else {
1.672     albertel  524:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       525:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  526:                 &logperm("F:$server:$cmd");
                    527:                 return 'con_failed';
                    528:             }
                    529:         }
                    530:     }
                    531:     return $answer;
1.405     albertel  532: }
                    533: 
1.755     albertel  534: # ------------------------------------------- check if return value is an error
                    535: 
                    536: sub error {
                    537:     my ($result) = @_;
1.756     albertel  538:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  539: 	if ($2 == 2) { return undef; }
                    540: 	return $1;
                    541:     }
                    542:     return undef;
                    543: }
                    544: 
1.783     albertel  545: sub convert_and_load_session_env {
                    546:     my ($lonidsdir,$handle)=@_;
                    547:     my @profile;
                    548:     {
1.917     albertel  549: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    550: 	if (!$opened) {
1.915     albertel  551: 	    return 0;
                    552: 	}
1.783     albertel  553: 	flock($idf,LOCK_SH);
                    554: 	@profile=<$idf>;
                    555: 	close($idf);
                    556:     }
                    557:     my %temp_env;
                    558:     foreach my $line (@profile) {
1.786     albertel  559: 	if ($line !~ m/=/) {
                    560: 	    return 0;
                    561: 	}
1.783     albertel  562: 	chomp($line);
                    563: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    564: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    565:     }
                    566:     unlink("$lonidsdir/$handle.id");
                    567:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    568: 	    0640)) {
                    569: 	%disk_env = %temp_env;
                    570: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    571: 	untie(%disk_env);
                    572:     }
1.786     albertel  573:     return 1;
1.783     albertel  574: }
                    575: 
1.374     www       576: # ------------------------------------------- Transfer profile into environment
1.780     albertel  577: my $env_loaded;
                    578: sub transfer_profile_to_env {
1.788     albertel  579:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    580:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       581: 
1.720     albertel  582:     if (!defined($lonidsdir)) {
                    583: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    584:     }
                    585:     if (!defined($handle)) {
                    586:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    587:     }
                    588: 
1.786     albertel  589:     my $convert;
                    590:     {
1.917     albertel  591:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    592: 	if (!$opened) {
1.915     albertel  593: 	    return;
                    594: 	}
1.786     albertel  595: 	flock($idf,LOCK_SH);
                    596: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    597: 		&GDBM_READER(),0640)) {
                    598: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    599: 	    untie(%disk_env);
                    600: 	} else {
                    601: 	    $convert = 1;
                    602: 	}
                    603:     }
                    604:     if ($convert) {
                    605: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    606: 	    &logthis("Failed to load session, or convert session.");
                    607: 	}
1.374     www       608:     }
1.783     albertel  609: 
1.786     albertel  610:     my %remove;
1.783     albertel  611:     while ( my $envname = each(%env) ) {
1.433     matthew   612:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    613:             if ($time < time-300) {
1.783     albertel  614:                 $remove{$key}++;
1.433     matthew   615:             }
                    616:         }
                    617:     }
1.783     albertel  618: 
1.619     albertel  619:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  620:     $env_loaded=1;
1.783     albertel  621:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   622:         &delenv($expired_key);
1.374     www       623:     }
1.1       albertel  624: }
                    625: 
1.916     albertel  626: # ---------------------------------------------------- Check for valid session 
                    627: sub check_for_valid_session {
1.1172.2.96  raeburn   628:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  629:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1172.2.108  raeburn   630:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
1.1155    raeburn   631:     if ($name eq 'lonDAV') {
                    632:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    633:     } else {
                    634:         $lonidsdir=$r->dir_config('lonIDsDir');
1.1172.2.108  raeburn   635:         if ($name eq '') {
                    636:             $name = 'lonID';
                    637:         }
                    638:     }
                    639:     if ($name eq 'lonID') {
                    640:         $secure = 'lonSID';
                    641:         $linkname = 'lonLinkID';
                    642:         $pubname = 'lonPubID';
                    643:         if (exists($cookies{$secure})) {
                    644:             $lonid=$cookies{$secure};
                    645:         } elsif (exists($cookies{$name})) {
                    646:             $lonid=$cookies{$name};
                    647:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
                    648:             $lonid=$cookies{$linkname};
                    649:         } elsif (exists($cookies{$pubname})) {
                    650:             $lonid=$cookies{$pubname};
                    651:         }
                    652:     } else {
                    653:         $lonid=$cookies{$name};
                    654:     }
                    655:     return undef if (!$lonid);
                    656: 
                    657:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    658:     if (-l "$lonidsdir/$handle.id") {
                    659:         my $link = readlink("$lonidsdir/$handle.id");
                    660:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    661:             $handle = $1;
                    662:         }
1.1155    raeburn   663:     }
1.1172.2.96  raeburn   664:     if (!-e "$lonidsdir/$handle.id") {
                    665:         if ((ref($domref)) && ($name eq 'lonID') &&
                    666:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    667:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    668:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    669:                 $$domref = $possudom;
                    670:             }
                    671:         }
                    672:         return undef;
                    673:     }
1.916     albertel  674: 
1.917     albertel  675:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    676:     return undef if (!$opened);
1.916     albertel  677: 
                    678:     flock($idf,LOCK_SH);
                    679:     my %disk_env;
                    680:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    681: 	    &GDBM_READER(),0640)) {
                    682: 	return undef;	
                    683:     }
                    684: 
                    685:     if (!defined($disk_env{'user.name'})
                    686: 	|| !defined($disk_env{'user.domain'})) {
1.1172.2.107  raeburn   687:         untie(%disk_env);
1.916     albertel  688: 	return undef;
                    689:     }
1.1172.2.18  raeburn   690: 
1.1172.2.36  raeburn   691:     if (ref($userhashref) eq 'HASH') {
                    692:         $userhashref->{'name'} = $disk_env{'user.name'};
                    693:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.142  raeburn   694:         if ($disk_env{'request.role'}) {
                    695:             $userhashref->{'role'} = $disk_env{'request.role'};
                    696:         }
1.1172.2.18  raeburn   697:     }
1.1172.2.107  raeburn   698:     untie(%disk_env);
1.1172.2.18  raeburn   699: 
1.916     albertel  700:     return $handle;
                    701: }
                    702: 
1.830     albertel  703: sub timed_flock {
                    704:     my ($file,$lock_type) = @_;
                    705:     my $failed=0;
                    706:     eval {
                    707: 	local $SIG{__DIE__}='DEFAULT';
                    708: 	local $SIG{ALRM}=sub {
                    709: 	    $failed=1;
                    710: 	    die("failed lock");
                    711: 	};
                    712: 	alarm(13);
                    713: 	flock($file,$lock_type);
                    714: 	alarm(0);
                    715:     };
                    716:     if ($failed) {
                    717: 	return undef;
                    718:     } else {
                    719: 	return 1;
                    720:     }
                    721: }
                    722: 
1.1172.2.107  raeburn   723: sub get_sessionfile_vars {
                    724:     my ($handle,$lonidsdir,$storearr) = @_;
                    725:     my %returnhash;
                    726:     unless (ref($storearr) eq 'ARRAY') {
                    727:         return %returnhash;
                    728:     }
                    729:     if (-l "$lonidsdir/$handle.id") {
                    730:         my $link = readlink("$lonidsdir/$handle.id");
                    731:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    732:             $handle = $1;
                    733:         }
                    734:     }
                    735:     if ((-e "$lonidsdir/$handle.id") &&
                    736:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    737:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    738:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    739:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    740:                 flock($idf,LOCK_SH);
                    741:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    742:                         &GDBM_READER(),0640)) {
                    743:                     foreach my $item (@{$storearr}) {
                    744:                         $returnhash{$item} = $disk_env{$item};
                    745:                     }
                    746:                     untie(%disk_env);
                    747:                 }
                    748:             }
                    749:         }
                    750:     }
                    751:     return %returnhash;
                    752: }
                    753: 
1.5       www       754: # ---------------------------------------------------------- Append Environment
                    755: 
                    756: sub appenv {
1.949     raeburn   757:     my ($newenv,$roles) = @_;
                    758:     if (ref($newenv) eq 'HASH') {
                    759:         foreach my $key (keys(%{$newenv})) {
                    760:             my $refused = 0;
                    761: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    762:                 $refused = 1;
                    763:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   764:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   765:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    766:                         $refused = 0;
                    767:                     }
                    768:                 }
                    769:             }
                    770:             if ($refused) {
                    771:                 &logthis("<font color=\"blue\">WARNING: ".
                    772:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    773:                          .'</font>');
                    774: 	        delete($newenv->{$key});
                    775:             } else {
                    776:                 $env{$key}=$newenv->{$key};
                    777:             }
                    778:         }
1.1172.2.96  raeburn   779:         my $lonids = $perlvar{'lonIDsDir'};
                    780:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    781:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    782:             if ($opened
                    783: 	        && &timed_flock($env_file,LOCK_EX)
                    784: 	        &&
                    785: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    786: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    787: 	        while (my ($key,$value) = each(%{$newenv})) {
                    788: 	            $disk_env{$key} = $value;
                    789: 	        }
                    790: 	        untie(%disk_env);
                    791:             }
1.35      www       792:         }
1.191     harris41  793:     }
1.56      www       794:     return 'ok';
                    795: }
                    796: # ----------------------------------------------------- Delete from Environment
                    797: 
                    798: sub delenv {
1.1104    raeburn   799:     my ($delthis,$regexp,$roles) = @_;
                    800:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    801:         my $refused = 1;
                    802:         if (ref($roles) eq 'ARRAY') {
                    803:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    804:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    805:                 $refused = 0;
                    806:             }
                    807:         }
                    808:         if ($refused) {
                    809:             &logthis("<font color=\"blue\">WARNING: ".
                    810:                      "Attempt to delete from environment ".$delthis);
                    811:             return 'error';
                    812:         }
1.56      www       813:     }
1.917     albertel  814:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    815:     if ($opened
1.915     albertel  816: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  817: 	&&
                    818: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    819: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  820: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   821: 	    if ($regexp) {
                    822:                 if ($key=~/^$delthis/) {
                    823:                     delete($env{$key});
                    824:                     delete($disk_env{$key});
                    825:                 } 
                    826:             } else {
                    827:                 if ($key=~/^\Q$delthis\E/) {
                    828: 		    delete($env{$key});
                    829: 		    delete($disk_env{$key});
                    830: 	        }
                    831:             }
1.448     albertel  832: 	}
1.783     albertel  833: 	untie(%disk_env);
1.5       www       834:     }
                    835:     return 'ok';
1.369     albertel  836: }
                    837: 
1.790     albertel  838: sub get_env_multiple {
                    839:     my ($name) = @_;
                    840:     my @values;
                    841:     if (defined($env{$name})) {
                    842:         # exists is it an array
                    843:         if (ref($env{$name})) {
                    844:             @values=@{ $env{$name} };
                    845:         } else {
                    846:             $values[0]=$env{$name};
                    847:         }
                    848:     }
                    849:     return(@values);
                    850: }
                    851: 
1.958     www       852: # ------------------------------------------------------------------- Locking
                    853: 
                    854: sub set_lock {
                    855:     my ($text)=@_;
                    856:     $locknum++;
                    857:     my $id=$$.'-'.$locknum;
                    858:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    859:              'session.lock.'.$id => $text});
                    860:     return $id;
                    861: }
                    862: 
                    863: sub get_locks {
                    864:     my $num=0;
                    865:     my %texts=();
                    866:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    867:        if ($lock=~/\w/) {
                    868:           $num++;
                    869:           $texts{$lock}=$env{'session.lock.'.$lock};
                    870:        }
                    871:    }
                    872:    return ($num,%texts);
                    873: }
                    874: 
                    875: sub remove_lock {
                    876:     my ($id)=@_;
                    877:     my $newlocks='';
                    878:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    879:        if (($lock=~/\w/) && ($lock ne $id)) {
                    880:           $newlocks.=','.$lock;
                    881:        }
                    882:     }
                    883:     &appenv({'session.locks' => $newlocks});
                    884:     &delenv('session.lock.'.$id);
                    885: }
                    886: 
                    887: sub remove_all_locks {
                    888:     my $activelocks=$env{'session.locks'};
                    889:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    890:        if ($lock=~/\w/) {
                    891:           &remove_lock($lock);
                    892:        }
                    893:     }
                    894: }
                    895: 
                    896: 
1.369     albertel  897: # ------------------------------------------ Find out current server userload
                    898: sub userload {
                    899:     my $numusers=0;
                    900:     {
                    901: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    902: 	my $filename;
                    903: 	my $curtime=time;
                    904: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  905: 	    next if ($filename eq '.' || $filename eq '..');
                    906: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1172.2.112  raeburn   907:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel  908: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  909: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  910: 	}
                    911: 	closedir(LONIDS);
                    912:     }
                    913:     my $userloadpercent=0;
                    914:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    915:     if ($maxuserload) {
1.371     albertel  916: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  917:     }
1.372     albertel  918:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  919:     return $userloadpercent;
1.283     www       920: }
                    921: 
1.1       albertel  922: # ------------------------------ Find server with least workload from spare.tab
1.11      www       923: 
1.1       albertel  924: sub spareserver {
1.1172.2.142  raeburn   925:     my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  926:     my $spare_server;
1.370     albertel  927:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  928:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    929:                                                      :  $userloadpercent;
1.1083    raeburn   930:     my ($uint_dom,$remotesessions);
                    931:     if (($udom ne '') && (&domain($udom) ne '')) {
                    932:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    933:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    934:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    935:         $remotesessions = $udomdefaults{'remotesessions'};
                    936:     }
1.1123    raeburn   937:     my $spareshash = &this_host_spares($udom);
                    938:     if (ref($spareshash) eq 'HASH') {
                    939:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    940:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62  raeburn   941:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    942:                                              $try_server));
1.1123    raeburn   943: 	        ($spare_server, $lowest_load) =
                    944: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    945:             }
1.1083    raeburn   946:         }
1.784     albertel  947: 
1.1123    raeburn   948:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    949: 
                    950:         if (!$found_server) {
                    951:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    952: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62  raeburn   953:                     next unless (&spare_can_host($udom,$uint_dom,
                    954:                                                  $remotesessions,$try_server));
1.1123    raeburn   955: 	            ($spare_server, $lowest_load) =
                    956: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    957:                 }
                    958: 	    }
                    959:         }
1.784     albertel  960:     }
                    961: 
                    962:     if (!$want_server_name) {
1.1001    raeburn   963:         if (defined($spare_server)) {
                    964:             my $hostname = &hostname($spare_server);
1.1083    raeburn   965:             if (defined($hostname)) {
1.1172.2.120  raeburn   966:                 my $protocol = 'http';
                    967:                 if ($protocol{$spare_server} eq 'https') {
                    968:                     $protocol = $protocol{$spare_server};
                    969:                 }
1.1172.2.142  raeburn   970:                 my $alias = &Apache::lonnet::use_proxy_alias($r,$spare_server);
                    971:                 $hostname = $alias if ($alias ne '');
1.1001    raeburn   972: 	        $spare_server = $protocol.'://'.$hostname;
                    973:             }
                    974:         }
1.784     albertel  975:     }
                    976:     return $spare_server;
                    977: }
                    978: 
                    979: sub compare_server_load {
1.1172.2.41  raeburn   980:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    981: 
                    982:     if ($required) {
                    983:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    984:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    985:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    986:         if (($major eq '' && $minor eq '') ||
                    987:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    988:             return ($spare_server,$lowest_load);
                    989:         }
                    990:     }
1.784     albertel  991: 
                    992:     my $loadans     = &reply('load',    $try_server);
                    993:     my $userloadans = &reply('userload',$try_server);
                    994: 
                    995:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   996: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  997:     }
                    998: 
                    999:     my $load;
                   1000:     if ($loadans =~ /\d/) {
                   1001: 	if ($userloadans =~ /\d/) {
                   1002: 	    #both are numbers, pick the bigger one
                   1003: 	    $load = ($loadans > $userloadans) ? $loadans 
                   1004: 		                              : $userloadans;
1.411     albertel 1005: 	} else {
1.784     albertel 1006: 	    $load = $loadans;
1.411     albertel 1007: 	}
1.784     albertel 1008:     } else {
                   1009: 	$load = $userloadans;
                   1010:     }
                   1011: 
                   1012:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1013: 	$spare_server = $try_server;
                   1014: 	$lowest_load  = $load;
1.370     albertel 1015:     }
1.784     albertel 1016:     return ($spare_server,$lowest_load);
1.202     matthew  1017: }
1.914     albertel 1018: 
                   1019: # --------------------------- ask offload servers if user already has a session
                   1020: sub find_existing_session {
                   1021:     my ($udom,$uname) = @_;
1.1123    raeburn  1022:     my $spareshash = &this_host_spares($udom);
                   1023:     if (ref($spareshash) eq 'HASH') {
                   1024:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1025:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1026:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1027:             }
                   1028:         }
                   1029:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1030:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1031:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1032:             }
                   1033:         }
1.914     albertel 1034:     }
                   1035:     return;
                   1036: }
                   1037: 
1.1172.2.107  raeburn  1038: # check if user's browser sent load balancer cookie and server still has session
                   1039: # and is not overloaded.
                   1040: sub check_for_balancer_cookie {
                   1041:     my ($r,$update_mtime) = @_;
                   1042:     my ($otherserver,$cookie);
                   1043:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1044:     if (exists($cookies{'balanceID'})) {
                   1045:         my $balid = $cookies{'balanceID'};
                   1046:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1047:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1048:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1049:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1050:                 my ($possudom,$possuname) = ($1,$2);
                   1051:                 my $has_session = 0;
                   1052:                 if ((&domain($possudom) ne '') &&
                   1053:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1054:                     my $try_server;
                   1055:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1056:                     if ($opened) {
                   1057:                         flock($idf,LOCK_SH);
                   1058:                         while (my $line = <$idf>) {
                   1059:                             chomp($line);
                   1060:                             if (&hostname($line) ne '') {
                   1061:                                 $try_server = $line;
                   1062:                                 last;
                   1063:                             }
                   1064:                         }
                   1065:                         close($idf);
                   1066:                         if (($try_server) &&
                   1067:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1068:                             my $lowest_load = 30000;
                   1069:                             ($otherserver,$lowest_load) =
                   1070:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1071:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1072:                                 $has_session = 1;
                   1073:                             } else {
                   1074:                                 undef($otherserver);
                   1075:                             }
                   1076:                         }
                   1077:                     }
                   1078:                 }
                   1079:                 if ($has_session) {
                   1080:                     if ($update_mtime) {
                   1081:                         my $atime = my $mtime = time;
                   1082:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1083:                     }
                   1084:                 } else {
                   1085:                     unlink("$balancedir/$cookie.id");
                   1086:                 }
                   1087:             }
                   1088:         }
                   1089:     }
                   1090:     return ($otherserver,$cookie);
                   1091: }
                   1092: 
1.1172.2.130  raeburn  1093: sub updatebalcookie {
                   1094:     my ($cookie,$balancer,$lastentry)=@_;
                   1095:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1096:         my ($udom,$uname) = ($1,$2);
                   1097:         my $uprimary_id = &domain($udom,'primary');
                   1098:         my $uintdom = &internet_dom($uprimary_id);
                   1099:         my $intdom = &internet_dom($balancer);
                   1100:         my $serverhomedom = &host_domain($balancer);
                   1101:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1102:             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
                   1103:         }
                   1104:     }
                   1105:     return;
                   1106: }
                   1107: 
1.1172.2.107  raeburn  1108: sub delbalcookie {
                   1109:     my ($cookie,$balancer) =@_;
                   1110:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1111:         my ($udom,$uname) = ($1,$2);
                   1112:         my $uprimary_id = &domain($udom,'primary');
                   1113:         my $uintdom = &internet_dom($uprimary_id);
                   1114:         my $intdom = &internet_dom($balancer);
                   1115:         my $serverhomedom = &host_domain($balancer);
                   1116:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1172.2.130  raeburn  1117:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1172.2.107  raeburn  1118:         }
                   1119:     }
                   1120: }
                   1121: 
1.914     albertel 1122: # -------------------------------- ask if server already has a session for user
                   1123: sub has_user_session {
                   1124:     my ($lonid,$udom,$uname) = @_;
                   1125:     my $result = &reply(join(':','userhassession',
                   1126: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1127:     return 1 if ($result eq 'ok');
                   1128: 
                   1129:     return 0;
                   1130: }
                   1131: 
1.1076    raeburn  1132: # --------- determine least loaded server in a user's domain which allows login
                   1133: 
                   1134: sub choose_server {
1.1172.2.47  raeburn  1135:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1136:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1137:     my %servers = &get_servers($udom);
1.1076    raeburn  1138:     my $lowest_load = 30000;
1.1172.2.47  raeburn  1139:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1140:     if ($skiploadbal) {
                   1141:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1142:         unless (defined($cached)) {
                   1143:             my $cachetime = 60*60*24;
                   1144:             my %domconfig =
                   1145:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1146:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1147:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1148:                                            $cachetime);
                   1149:             }
                   1150:         }
                   1151:     }
1.1076    raeburn  1152:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn  1153:         my $loginvia;
1.1172.2.47  raeburn  1154:         if ($skiploadbal) {
                   1155:             if (ref($balancers) eq 'HASH') {
                   1156:                 next if (exists($balancers->{$lonhost}));
                   1157:             }
                   1158:         }
1.1115    raeburn  1159:         if ($checkloginvia) {
                   1160:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1161:             if ($loginvia) {
                   1162:                 my ($server,$path) = split(/:/,$loginvia);
                   1163:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1164:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1165:                 if ($login_host eq $server) {
                   1166:                     $portal_path = $path;
1.1151    raeburn  1167:                     $isredirect = 1;
1.1116    raeburn  1168:                 }
                   1169:             } else {
                   1170:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1171:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1172:                 if ($login_host eq $lonhost) {
                   1173:                     $portal_path = '';
1.1151    raeburn  1174:                     $isredirect = ''; 
1.1116    raeburn  1175:                 }
                   1176:             }
                   1177:         } else {
1.1076    raeburn  1178:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1179:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1180:         }
                   1181:     }
                   1182:     if ($login_host ne '') {
1.1116    raeburn  1183:         $hostname = &hostname($login_host);
1.1076    raeburn  1184:     }
1.1172.2.88  raeburn  1185:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1186: }
                   1187: 
1.1172.2.123  raeburn  1188: sub get_course_sessions {
                   1189:     my ($cnum,$cdom,$lastactivity) = @_;
                   1190:     my %servers = &internet_dom_servers($cdom);
                   1191:     my %returnhash;
                   1192:     foreach my $server (sort(keys(%servers))) {
                   1193:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
                   1194:         my @pairs=split(/\&/,$rep);
                   1195:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
                   1196:             foreach my $item (@pairs) {
                   1197:                 my ($key,$value)=split(/=/,$item,2);
                   1198:                 $key = &unescape($key);
                   1199:                 next if ($key =~ /^error: 2 /);
                   1200:                 if (exists($returnhash{$key})) {
                   1201:                     next if ($value < $returnhash{$key});
                   1202:                 }
                   1203:                 $returnhash{$key}=$value;
                   1204:             }
                   1205:         }
                   1206:     }
                   1207:     return %returnhash;
                   1208: }
                   1209: 
1.202     matthew  1210: # --------------------------------------------- Try to change a user's password
                   1211: 
                   1212: sub changepass {
1.799     raeburn  1213:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1214:     $currentpass = &escape($currentpass);
                   1215:     $newpass     = &escape($newpass);
1.1030    raeburn  1216:     my $lonhost = $perlvar{'lonHostID'};
                   1217:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1218: 		       $server);
                   1219:     if (! $answer) {
                   1220: 	&logthis("No reply on password change request to $server ".
                   1221: 		 "by $uname in domain $udom.");
                   1222:     } elsif ($answer =~ "^ok") {
                   1223:         &logthis("$uname in $udom successfully changed their password ".
                   1224: 		 "on $server.");
                   1225:     } elsif ($answer =~ "^pwchange_failure") {
                   1226: 	&logthis("$uname in $udom was unable to change their password ".
                   1227: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1228: 		 "or pwchange");
                   1229:     } elsif ($answer =~ "^non_authorized") {
                   1230:         &logthis("$uname in $udom did not get their password correct when ".
                   1231: 		 "attempting to change it on $server.");
                   1232:     } elsif ($answer =~ "^auth_mode_error") {
                   1233:         &logthis("$uname in $udom attempted to change their password despite ".
                   1234: 		 "not being locally or internally authenticated on $server.");
                   1235:     } elsif ($answer =~ "^unknown_user") {
                   1236:         &logthis("$uname in $udom attempted to change their password ".
                   1237: 		 "on $server but were unable to because $server is not ".
                   1238: 		 "their home server.");
                   1239:     } elsif ($answer =~ "^refused") {
                   1240: 	&logthis("$server refused to change $uname in $udom password because ".
                   1241: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1242:     } elsif ($answer =~ "invalid_client") {
                   1243:         &logthis("$server refused to change $uname in $udom password because ".
                   1244:                  "it was a reset by e-mail originating from an invalid server.");
1.1172.2.113  raeburn  1245:     } elsif ($answer =~ "^prioruse") {
                   1246:        &logthis("$server refused to change $uname in $udom password because ".
                   1247:                 "the password had been used before");
1.202     matthew  1248:     }
                   1249:     return $answer;
1.1       albertel 1250: }
                   1251: 
1.169     harris41 1252: # ----------------------- Try to determine user's current authentication scheme
                   1253: 
                   1254: sub queryauthenticate {
                   1255:     my ($uname,$udom)=@_;
1.456     albertel 1256:     my $uhome=&homeserver($uname,$udom);
                   1257:     if (!$uhome) {
                   1258: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1259: 	return 'no_host';
                   1260:     }
                   1261:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1262:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1263: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1264:     }
1.456     albertel 1265:     return $answer;
1.169     harris41 1266: }
                   1267: 
1.1       albertel 1268: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1269: 
1.1       albertel 1270: sub authenticate {
1.1073    raeburn  1271:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1272:     $upass=&escape($upass);
                   1273:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1274:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1275:     my $newhome;
1.836     www      1276:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1277: # Maybe the machine was offline and only re-appeared again recently?
                   1278:         &reconlonc();
                   1279: # One more
1.952     raeburn  1280: 	$uhome=&homeserver($uname,$udom,1);
                   1281:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1282:             if (defined(&domain($udom,'primary'))) {
                   1283:                 $newhome=&domain($udom,'primary');
                   1284:             }
                   1285:             if ($newhome ne '') {
                   1286:                 $uhome = $newhome;
                   1287:             }
                   1288:         }
1.836     www      1289: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1290: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1291: 	    return 'no_host';
                   1292:         }
1.1       albertel 1293:     }
1.1073    raeburn  1294:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1295:     if ($answer eq 'authorized') {
1.952     raeburn  1296:         if ($newhome) {
                   1297:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1298:             return 'no_account_on_host'; 
                   1299:         } else {
                   1300:             &logthis("User $uname at $udom authorized by $uhome");
                   1301:             return $uhome;
                   1302:         }
1.471     albertel 1303:     }
                   1304:     if ($answer eq 'non_authorized') {
                   1305: 	&logthis("User $uname at $udom rejected by $uhome");
                   1306: 	return 'no_host'; 
1.9       www      1307:     }
1.471     albertel 1308:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1309:     return 'no_host';
                   1310: }
                   1311: 
1.1073    raeburn  1312: sub can_host_session {
1.1074    raeburn  1313:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1314:     my $canhost = 1;
1.1074    raeburn  1315:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1316:     if (ref($remotesessions) eq 'HASH') {
                   1317:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1318:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1319:                 $canhost = 0;
                   1320:             } else {
                   1321:                 $canhost = 1;
                   1322:             }
                   1323:         }
                   1324:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1325:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1326:                 $canhost = 1;
                   1327:             } else {
                   1328:                 $canhost = 0;
                   1329:             }
                   1330:         }
                   1331:         if ($canhost) {
                   1332:             if ($remotesessions->{'version'} ne '') {
                   1333:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1334:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1335:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1336:                         my $major = $1;
                   1337:                         my $minor = $2;
                   1338:                         if (($major < $reqmajor ) ||
                   1339:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1340:                             $canhost = 0;
                   1341:                         }
                   1342:                     } else {
                   1343:                         $canhost = 0;
                   1344:                     }
                   1345:                 }
                   1346:             }
                   1347:         }
                   1348:     }
                   1349:     if ($canhost) {
                   1350:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1351:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1352:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1353:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1354:                 if (($uint_dom ne '') && 
                   1355:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1356:                     $canhost = 0;
                   1357:                 } else {
                   1358:                     $canhost = 1;
                   1359:                 }
                   1360:             }
                   1361:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1362:                 if (($uint_dom ne '') && 
                   1363:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1364:                     $canhost = 1;
                   1365:                 } else {
                   1366:                     $canhost = 0;
                   1367:                 }
                   1368:             }
                   1369:         }
                   1370:     }
                   1371:     return $canhost;
                   1372: }
                   1373: 
1.1083    raeburn  1374: sub spare_can_host {
                   1375:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1376:     my $canhost=1;
1.1172.2.62  raeburn  1377:     my $try_server_hostname = &hostname($try_server);
                   1378:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1379:     my $serverhomedom = &host_domain($serverhomeID);
                   1380:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1381:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1382:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1383:             $canhost = 0;
                   1384:         }
                   1385:     }
1.1172.2.136  raeburn  1386:     if ($canhost) {
                   1387:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
                   1388:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
                   1389:                 unless (&shared_institution($udom,$try_server)) {
                   1390:                     $canhost = 0;
                   1391:                 }
                   1392:             }
                   1393:         }
                   1394:     }
1.1172.2.62  raeburn  1395:     if (($canhost) && ($uint_dom)) {
                   1396:         my @intdoms;
                   1397:         my $internet_names = &get_internet_names($try_server);
                   1398:         if (ref($internet_names) eq 'ARRAY') {
                   1399:             @intdoms = @{$internet_names};
                   1400:         }
                   1401:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1402:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1403:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1404:                                          $remotesessions,
                   1405:                                          $defdomdefaults{'hostedsessions'});
                   1406:         }
1.1083    raeburn  1407:     }
                   1408:     return $canhost;
                   1409: }
                   1410: 
1.1123    raeburn  1411: sub this_host_spares {
                   1412:     my ($dom) = @_;
1.1126    raeburn  1413:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1414:     my @hosts = &current_machine_ids();
                   1415:     foreach my $lonhost (@hosts) {
                   1416:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1417:             $dom_in_use = $dom;
                   1418:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1419:             last;
                   1420:         }
                   1421:     }
1.1126    raeburn  1422:     if ($dom_in_use ne '') {
                   1423:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1424:     }
                   1425:     if (ref($result) ne 'HASH') {
                   1426:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1427:         $dom_in_use = &host_domain($lonhost_in_use);
                   1428:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1429:         if (ref($result) ne 'HASH') {
                   1430:             $result = \%spareid;
                   1431:         }
                   1432:     }
                   1433:     return $result;
                   1434: }
                   1435: 
                   1436: sub spares_for_offload  {
                   1437:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1438:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1439:     if (defined($cached)) {
                   1440:         return $result;
                   1441:     } else {
1.1126    raeburn  1442:         my $cachetime = 60*60*24;
                   1443:         my %domconfig =
                   1444:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1445:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1446:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1447:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1448:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1449:                 }
                   1450:             }
                   1451:         }
                   1452:     }
1.1126    raeburn  1453:     return;
1.1123    raeburn  1454: }
                   1455: 
1.1129    raeburn  1456: sub get_lonbalancer_config {
                   1457:     my ($servers) = @_;
                   1458:     my ($currbalancer,$currtargets);
                   1459:     if (ref($servers) eq 'HASH') {
                   1460:         foreach my $server (keys(%{$servers})) {
                   1461:             my %what = (
                   1462:                          spareid => 1,
                   1463:                          perlvar => 1,
                   1464:                        );
                   1465:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1466:             if ($result eq 'ok') {
                   1467:                 if (ref($returnhash) eq 'HASH') {
                   1468:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1469:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1470:                             $currbalancer = $server;
                   1471:                             $currtargets = {};
                   1472:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1473:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1474:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1475:                                 }
                   1476:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1477:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1478:                                 }
                   1479:                             }
                   1480:                             last;
                   1481:                         }
                   1482:                     }
                   1483:                 }
                   1484:             }
                   1485:         }
                   1486:     }
                   1487:     return ($currbalancer,$currtargets);
                   1488: }
                   1489: 
                   1490: sub check_loadbalancing {
1.1172.2.88  raeburn  1491:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1492:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107  raeburn  1493:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129    raeburn  1494:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1495:     my @hosts = &current_machine_ids();
1.1129    raeburn  1496:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1497:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1498:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1499:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1500:     my $domneedscache; 
1.1129    raeburn  1501:     my $cachetime = 60*60*24;
                   1502: 
                   1503:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1504:         $dom_in_use = $udom;
                   1505:         $homeintdom = 1;
                   1506:     } else {
                   1507:         $dom_in_use = $serverhomedom;
                   1508:     }
                   1509:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1510:     unless (defined($cached)) {
                   1511:         my %domconfig =
                   1512:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1513:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1514:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1515:         } else {
                   1516:             $domneedscache = $dom_in_use;
1.1129    raeburn  1517:         }
                   1518:     }
                   1519:     if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1520:         ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1521:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1522:         if ($is_balancer) {
                   1523:             if (ref($currrules) eq 'HASH') {
                   1524:                 if ($homeintdom) {
                   1525:                     if ($uname ne '') {
                   1526:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1527:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1528:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1529:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1530:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1531:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1532:                             }
                   1533:                         }
                   1534:                         if ($rule_in_effect eq '') {
                   1535:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1536:                             if ($userenv{'inststatus'} ne '') {
                   1537:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1538:                                 my ($othertitle,$usertypes,$types) =
                   1539:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1540:                                 if (ref($types) eq 'ARRAY') {
                   1541:                                     foreach my $type (@{$types}) {
                   1542:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1543:                                             if (exists($currrules->{$type})) {
                   1544:                                                 $rule_in_effect = $currrules->{$type};
                   1545:                                             }
                   1546:                                         }
                   1547:                                     }
                   1548:                                 }
                   1549:                             } else {
                   1550:                                 if (exists($currrules->{'default'})) {
                   1551:                                     $rule_in_effect = $currrules->{'default'};
                   1552:                                 }
                   1553:                             }
                   1554:                         }
                   1555:                     } else {
                   1556:                         if (exists($currrules->{'default'})) {
                   1557:                             $rule_in_effect = $currrules->{'default'};
                   1558:                         }
                   1559:                     }
                   1560:                 } else {
                   1561:                     if ($currrules->{'_LC_external'} ne '') {
                   1562:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1563:                     }
                   1564:                 }
                   1565:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1566:                                                        $uname,$udom);
                   1567:             }
                   1568:         }
                   1569:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1570:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1571:         unless (defined($cached)) {
                   1572:             my %domconfig =
                   1573:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1574:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1575:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1576:             } else {
                   1577:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1578:             }
                   1579:         }
                   1580:         if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1581:             ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1582:                 &check_balancer_result($result,@hosts);
                   1583:             if ($is_balancer) {
1.1129    raeburn  1584:                 if (ref($currrules) eq 'HASH') {
                   1585:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1586:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1587:                     }
                   1588:                 }
                   1589:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1590:                                                        $uname,$udom);
                   1591:             }
                   1592:         } else {
                   1593:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1594:                 $is_balancer = 1;
                   1595:                 $offloadto = &this_host_spares($dom_in_use);
                   1596:             }
1.1172.2.75  raeburn  1597:             unless (defined($cached)) {
                   1598:                 $domneedscache = $serverhomedom;
                   1599:             }
1.1129    raeburn  1600:         }
                   1601:     } else {
                   1602:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1603:             $is_balancer = 1;
                   1604:             $offloadto = &this_host_spares($dom_in_use);
                   1605:         }
1.1172.2.75  raeburn  1606:         unless (defined($cached)) {
                   1607:             $domneedscache = $serverhomedom;
                   1608:         }
                   1609:     }
                   1610:     if ($domneedscache) {
                   1611:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1612:     }
1.1172.2.130  raeburn  1613:     if (($is_balancer) && ($caller ne 'switchserver')) {
1.1172.2.5  raeburn  1614:         my $lowest_load = 30000;
                   1615:         if (ref($offloadto) eq 'HASH') {
                   1616:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1617:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1618:                     ($otherserver,$lowest_load) =
                   1619:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1620:                 }
1.1129    raeburn  1621:             }
1.1172.2.5  raeburn  1622:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1623: 
1.1172.2.5  raeburn  1624:             if (!$found_server) {
                   1625:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1626:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1627:                         ($otherserver,$lowest_load) =
                   1628:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1629:                     }
                   1630:                 }
                   1631:             }
                   1632:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1633:             if (@{$offloadto} == 1) {
                   1634:                 $otherserver = $offloadto->[0];
                   1635:             } elsif (@{$offloadto} > 1) {
                   1636:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1637:                     ($otherserver,$lowest_load) =
                   1638:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1639:                 }
                   1640:             }
                   1641:         }
1.1172.2.88  raeburn  1642:         unless ($caller eq 'login') {
                   1643:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1644:                 $is_balancer = 0;
                   1645:                 if ($uname ne '' && $udom ne '') {
                   1646:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1647:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1648:                                  'user.loadbalcheck.time' => time});
                   1649:                     }
1.1172.2.5  raeburn  1650:                 }
1.1129    raeburn  1651:             }
                   1652:         }
1.1172.2.130  raeburn  1653:     }
                   1654:     if (($is_balancer) && (!$homeintdom)) {
                   1655:         undef($setcookie);
1.1129    raeburn  1656:     }
1.1172.2.107  raeburn  1657:     return ($is_balancer,$otherserver,$setcookie);
1.1129    raeburn  1658: }
                   1659: 
1.1172.2.12  raeburn  1660: sub check_balancer_result {
                   1661:     my ($result,@hosts) = @_;
1.1172.2.107  raeburn  1662:     my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1663:     if (ref($result) eq 'HASH') {
                   1664:         if ($result->{'lonhost'} ne '') {
                   1665:             my $currbalancer = $result->{'lonhost'};
                   1666:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1667:                 $is_balancer = 1;
                   1668:                 $currtargets = $result->{'targets'};
                   1669:                 $currrules = $result->{'rules'};
                   1670:             }
                   1671:         } else {
                   1672:             foreach my $key (keys(%{$result})) {
                   1673:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1674:                     (ref($result->{$key}) eq 'HASH')) {
                   1675:                     $is_balancer = 1;
                   1676:                     $currrules = $result->{$key}{'rules'};
                   1677:                     $currtargets = $result->{$key}{'targets'};
1.1172.2.107  raeburn  1678:                     $setcookie = $result->{$key}{'cookie'};
1.1172.2.12  raeburn  1679:                     last;
                   1680:                 }
                   1681:             }
                   1682:         }
                   1683:     }
1.1172.2.107  raeburn  1684:     return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1685: }
                   1686: 
1.1129    raeburn  1687: sub get_loadbalancer_targets {
                   1688:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1689:     my $offloadto;
1.1172.2.4  raeburn  1690:     if ($rule_in_effect eq 'none') {
                   1691:         return [$perlvar{'lonHostID'}];
                   1692:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1693:         $offloadto = $currtargets;
                   1694:     } else {
                   1695:         if ($rule_in_effect eq 'homeserver') {
                   1696:             my $homeserver = &homeserver($uname,$udom);
                   1697:             if ($homeserver ne 'no_host') {
                   1698:                 $offloadto = [$homeserver];
                   1699:             }
                   1700:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1701:             my %domconfig =
                   1702:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1703:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1704:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1705:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1706:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1707:                     }
                   1708:                 }
                   1709:             } else {
1.1172.2.7  raeburn  1710:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1711:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1712:                 if (&hostname($remotebalancer) ne '') {
                   1713:                     $offloadto = [$remotebalancer];
                   1714:                 }
                   1715:             }
                   1716:         } elsif (&hostname($rule_in_effect) ne '') {
                   1717:             $offloadto = [$rule_in_effect];
                   1718:         }
                   1719:     }
                   1720:     return $offloadto;
                   1721: }
                   1722: 
1.1127    raeburn  1723: sub internet_dom_servers {
                   1724:     my ($dom) = @_;
                   1725:     my (%uniqservers,%servers);
                   1726:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1727:     my @machinedoms = &machine_domains($primaryserver);
                   1728:     foreach my $mdom (@machinedoms) {
                   1729:         my %currservers = %servers;
                   1730:         my %server = &get_servers($mdom);
                   1731:         %servers = (%currservers,%server);
                   1732:     }
                   1733:     my %by_hostname;
                   1734:     foreach my $id (keys(%servers)) {
                   1735:         push(@{$by_hostname{$servers{$id}}},$id);
                   1736:     }
                   1737:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1738:         if (@{$by_hostname{$hostname}} > 1) {
                   1739:             my $match = 0;
                   1740:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1741:                 if (&host_domain($id) eq $dom) {
                   1742:                     $uniqservers{$id} = $hostname;
                   1743:                     $match = 1;
                   1744:                 }
                   1745:             }
                   1746:             unless ($match) {
                   1747:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1748:             }
                   1749:         } else {
                   1750:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1751:         }
                   1752:     }
                   1753:     return %uniqservers;
                   1754: }
                   1755: 
1.1       albertel 1756: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1757: 
1.599     albertel 1758: my %homecache;
1.1       albertel 1759: sub homeserver {
1.230     stredwic 1760:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1761:     my $index="$uname:$udom";
1.426     albertel 1762: 
1.599     albertel 1763:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1764: 
                   1765:     my %servers = &get_servers($udom,'library');
                   1766:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1767:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1768: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1769: 
                   1770: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1771: 	if ($answer eq 'found') {
                   1772: 	    delete($badServerCache{$tryserver}); 
                   1773: 	    return $homecache{$index}=$tryserver;
                   1774: 	} elsif ($answer eq 'no_host') {
                   1775: 	    $badServerCache{$tryserver}=1;
                   1776: 	}
1.1       albertel 1777:     }    
                   1778:     return 'no_host';
1.70      www      1779: }
                   1780: 
                   1781: # ------------------------------------- Find the usernames behind a list of IDs
                   1782: 
                   1783: sub idget {
                   1784:     my ($udom,@ids)=@_;
                   1785:     my %returnhash=();
                   1786:     
1.841     albertel 1787:     my %servers = &get_servers($udom,'library');
                   1788:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1789: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1790: 	$idlist=~tr/A-Z/a-z/; 
                   1791: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1792: 	my @answer=();
                   1793: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1794: 	    @answer=split(/\&/,$reply);
                   1795: 	}                    ;
                   1796: 	my $i;
                   1797: 	for ($i=0;$i<=$#ids;$i++) {
                   1798: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1799: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1800: 	    } 
                   1801: 	}
                   1802:     } 
1.70      www      1803:     return %returnhash;
                   1804: }
                   1805: 
                   1806: # ------------------------------------- Find the IDs behind a list of usernames
                   1807: 
                   1808: sub idrget {
                   1809:     my ($udom,@unames)=@_;
                   1810:     my %returnhash=();
1.800     albertel 1811:     foreach my $uname (@unames) {
                   1812:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1813:     }
1.70      www      1814:     return %returnhash;
                   1815: }
                   1816: 
                   1817: # ------------------------------- Store away a list of names and associated IDs
                   1818: 
                   1819: sub idput {
                   1820:     my ($udom,%ids)=@_;
                   1821:     my %servers=();
1.800     albertel 1822:     foreach my $uname (keys(%ids)) {
                   1823: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1824:         my $uhom=&homeserver($uname,$udom);
1.70      www      1825:         if ($uhom ne 'no_host') {
1.800     albertel 1826:             my $id=&escape($ids{$uname});
1.70      www      1827:             $id=~tr/A-Z/a-z/;
1.800     albertel 1828:             my $esc_unam=&escape($uname);
1.70      www      1829: 	    if ($servers{$uhom}) {
1.800     albertel 1830: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1831:             } else {
1.800     albertel 1832:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1833:             }
                   1834:         }
1.191     harris41 1835:     }
1.800     albertel 1836:     foreach my $server (keys(%servers)) {
                   1837:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1838:     }
1.344     www      1839: }
                   1840: 
1.1172.2.30  raeburn  1841: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1842: 
                   1843: sub iddel {
                   1844:     my ($udom,$idshashref,$uhome)=@_;
                   1845:     my %result=();
                   1846:     unless (ref($idshashref) eq 'HASH') {
                   1847:         return %result;
                   1848:     }
                   1849:     my %servers=();
                   1850:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1851:         my $uhom;
                   1852:         if ($uhome) {
                   1853:             $uhom = $uhome;
                   1854:         } else {
                   1855:             $uhom=&homeserver($uname,$udom);
                   1856:         }
                   1857:         if ($uhom ne 'no_host') {
                   1858:             if ($servers{$uhom}) {
                   1859:                 $servers{$uhom}.='&'.&escape($id);
                   1860:             } else {
                   1861:                 $servers{$uhom}=&escape($id);
                   1862:             }
                   1863:         }
                   1864:     }
                   1865:     foreach my $server (keys(%servers)) {
                   1866:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1867:     }
                   1868:     return %result;
                   1869: }
                   1870: 
1.1023    raeburn  1871: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1872: sub dump_dom {
1.1165    droeschl 1873:     my ($namespace, $udom, $regexp) = @_;
                   1874: 
                   1875:     $udom ||= $env{'user.domain'};
                   1876: 
                   1877:     return () unless $udom;
                   1878: 
                   1879:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1880: }
                   1881: 
1.1023    raeburn  1882: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1883: 
                   1884: sub get_dom {
1.1172.2.146.  .1(raebu 1885:22):     my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
1.1172.2.57  raeburn  1886:     return if ($udom eq 'public');
1.806     raeburn  1887:     my $items='';
                   1888:     foreach my $item (@$storearr) {
                   1889:         $items.=&escape($item).'&';
                   1890:     }
                   1891:     $items=~s/\&$//;
1.860     raeburn  1892:     if (!$udom) {
                   1893:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1894:         return if ($udom eq 'public');
1.860     raeburn  1895:         if (defined(&domain($udom,'primary'))) {
                   1896:             $uhome=&domain($udom,'primary');
                   1897:         } else {
1.874     albertel 1898:             undef($uhome);
1.860     raeburn  1899:         }
                   1900:     } else {
                   1901:         if (!$uhome) {
                   1902:             if (defined(&domain($udom,'primary'))) {
                   1903:                 $uhome=&domain($udom,'primary');
                   1904:             }
                   1905:         }
                   1906:     }
                   1907:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1172.2.139  raeburn  1908:         my $rep;
                   1909:         if (grep { $_ eq $uhome } &current_machine_ids()) {
                   1910:             # domain information is hosted on this machine
                   1911:             $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
1.1172.2.146.  .1(raebu 1912:22):         } else {
                   1913:22):             if ($encrypt) {
                   1914:22):                 $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   1915:22):             } else {
                   1916:22):                 $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   1917:22):             }
1.1172.2.139  raeburn  1918:         }
1.866     raeburn  1919:         my %returnhash;
1.875     albertel 1920:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1921:             return %returnhash;
                   1922:         }
1.806     raeburn  1923:         my @pairs=split(/\&/,$rep);
                   1924:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1925:             return @pairs;
                   1926:         }
                   1927:         my $i=0;
                   1928:         foreach my $item (@$storearr) {
                   1929:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1930:             $i++;
                   1931:         }
                   1932:         return %returnhash;
                   1933:     } else {
1.880     banghart 1934:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1935:     }
                   1936: }
                   1937: 
                   1938: # -------------------------------------------- put items in domain db files 
                   1939: 
                   1940: sub put_dom {
1.1172.2.146.  .1(raebu 1941:22):     my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
1.860     raeburn  1942:     if (!$udom) {
                   1943:         $udom=$env{'user.domain'};
                   1944:         if (defined(&domain($udom,'primary'))) {
                   1945:             $uhome=&domain($udom,'primary');
                   1946:         } else {
1.874     albertel 1947:             undef($uhome);
1.860     raeburn  1948:         }
                   1949:     } else {
                   1950:         if (!$uhome) {
                   1951:             if (defined(&domain($udom,'primary'))) {
                   1952:                 $uhome=&domain($udom,'primary');
                   1953:             }
                   1954:         }
                   1955:     } 
                   1956:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1957:         my $items='';
                   1958:         foreach my $item (keys(%$storehash)) {
                   1959:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1960:         }
                   1961:         $items=~s/\&$//;
1.1172.2.146.  .1(raebu 1962:22):         if ($encrypt) {
                   1963:22):             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   1964:22):         } else {
                   1965:22):             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1966:22):         }
1.806     raeburn  1967:     } else {
1.860     raeburn  1968:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1969:     }
                   1970: }
                   1971: 
1.1023    raeburn  1972: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1973: sub newput_dom {
1.1023    raeburn  1974:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1975:     my $result;
                   1976:     if (!$udom) {
                   1977:         $udom=$env{'user.domain'};
                   1978:     }
1.1023    raeburn  1979:     if ($udom) {
                   1980:         my $uname = &get_domainconfiguser($udom);
                   1981:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1982:     }
                   1983:     return $result;
                   1984: }
                   1985: 
1.1023    raeburn  1986: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1987: sub del_dom {
1.1023    raeburn  1988:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1989:     if (ref($storearr) eq 'ARRAY') {
                   1990:         if (!$udom) {
                   1991:             $udom=$env{'user.domain'};
                   1992:         }
1.1023    raeburn  1993:         if ($udom) {
                   1994:             my $uname = &get_domainconfiguser($udom); 
                   1995:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1996:         }
                   1997:     }
                   1998: }
                   1999: 
1.1023    raeburn  2000: # ----------------------------------construct domainconfig user for a domain 
                   2001: sub get_domainconfiguser {
                   2002:     my ($udom) = @_;
                   2003:     return $udom.'-domainconfig';
                   2004: }
                   2005: 
1.837     raeburn  2006: sub retrieve_inst_usertypes {
                   2007:     my ($udom) = @_;
                   2008:     my (%returnhash,@order);
1.989     raeburn  2009:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2010:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2011:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  2012:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2013:     } else {
                   2014:         if (defined(&domain($udom,'primary'))) {
                   2015:             my $uhome=&domain($udom,'primary');
                   2016:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2017:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  2018:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2019:                 return (\%returnhash,\@order);
                   2020:             }
                   2021:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2022:             my @pairs=split(/\&/,$hashitems);
                   2023:             foreach my $item (@pairs) {
                   2024:                 my ($key,$value)=split(/=/,$item,2);
                   2025:                 $key = &unescape($key);
                   2026:                 next if ($key =~ /^error: 2 /);
                   2027:                 $returnhash{$key}=&thaw_unescape($value);
                   2028:             }
                   2029:             my @esc_order = split(/\&/,$orderitems);
                   2030:             foreach my $item (@esc_order) {
                   2031:                 push(@order,&unescape($item));
                   2032:             }
                   2033:         } else {
1.1172.2.44  raeburn  2034:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2035:         }
1.1172.2.44  raeburn  2036:         return (\%returnhash,\@order);
1.837     raeburn  2037:     }
                   2038: }
                   2039: 
1.868     raeburn  2040: sub is_domainimage {
                   2041:     my ($url) = @_;
1.1172.2.142  raeburn  2042:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
1.868     raeburn  2043:         if (&domain($1) ne '') {
                   2044:             return '1';
                   2045:         }
                   2046:     }
                   2047:     return;
                   2048: }
                   2049: 
1.899     raeburn  2050: sub inst_directory_query {
                   2051:     my ($srch) = @_;
                   2052:     my $udom = $srch->{'srchdomain'};
                   2053:     my %results;
                   2054:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2055:     my $outcome;
1.899     raeburn  2056:     if ($homeserver ne '') {
1.1172.2.116  raeburn  2057:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2058:             if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2059:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116  raeburn  2060:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
                   2061:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2062:                     (($major == 2) && ($minor < 11)) ||
                   2063:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
                   2064:                     return;
                   2065:                 }
                   2066:             }
                   2067:         }
1.904     albertel 2068: 	my $queryid=&reply("querysend:instdirsearch:".
                   2069: 			   &escape($srch->{'srchby'}).':'.
                   2070: 			   &escape($srch->{'srchterm'}).':'.
                   2071: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2072: 	my $host=&hostname($homeserver);
                   2073: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  2074: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2075: 	    return;
                   2076: 	}
                   2077: 	my $response = &get_query_reply($queryid);
                   2078: 	my $maxtries = 5;
                   2079: 	my $tries = 1;
                   2080: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2081: 	    $response = &get_query_reply($queryid);
                   2082: 	    $tries ++;
                   2083: 	}
                   2084: 
                   2085:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2086:             if ($response eq 'unavailable') {
                   2087:                 $outcome = $response;
                   2088:             } else {
                   2089:                 $outcome = 'ok';
                   2090:                 my @matches = split(/\n/,$response);
                   2091:                 foreach my $match (@matches) {
                   2092:                     my ($key,$value) = split(/=/,$match);
                   2093:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2094:                 }
1.899     raeburn  2095:             }
                   2096:         }
                   2097:     }
1.909     raeburn  2098:     return ($outcome,%results);
1.899     raeburn  2099: }
                   2100: 
                   2101: sub usersearch {
                   2102:     my ($srch) = @_;
                   2103:     my $dom = $srch->{'srchdomain'};
                   2104:     my %results;
                   2105:     my %libserv = &all_library();
                   2106:     my $query = 'usersearch';
                   2107:     foreach my $tryserver (keys(%libserv)) {
                   2108:         if (&host_domain($tryserver) eq $dom) {
1.1172.2.116  raeburn  2109:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2110:                 if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2111:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.119  raeburn  2112:                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116  raeburn  2113:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2114:                              (($major == 2) && ($minor < 11)) ||
                   2115:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
                   2116:                 }
                   2117:             }
1.899     raeburn  2118:             my $host=&hostname($tryserver);
                   2119:             my $queryid=
1.911     raeburn  2120:                 &reply("querysend:".&escape($query).':'.
                   2121:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2122:                        &escape($srch->{'srchtype'}).':'.
                   2123:                        &escape($srch->{'srchterm'}),$tryserver);
                   2124:             if ($queryid !~/^\Q$host\E\_/) {
                   2125:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2126:                 next;
1.899     raeburn  2127:             }
                   2128:             my $reply = &get_query_reply($queryid);
                   2129:             my $maxtries = 1;
                   2130:             my $tries = 1;
                   2131:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2132:                 $reply = &get_query_reply($queryid);
                   2133:                 $tries ++;
                   2134:             }
                   2135:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2136:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2137:             } else {
1.911     raeburn  2138:                 my @matches;
                   2139:                 if ($reply =~ /\n/) {
                   2140:                     @matches = split(/\n/,$reply);
                   2141:                 } else {
                   2142:                     @matches = split(/\&/,$reply);
                   2143:                 }
1.899     raeburn  2144:                 foreach my $match (@matches) {
                   2145:                     my ($uname,$udom,%userhash);
1.911     raeburn  2146:                     foreach my $entry (split(/:/,$match)) {
                   2147:                         my ($key,$value) =
                   2148:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2149:                         $userhash{$key} = $value;
                   2150:                         if ($key eq 'username') {
                   2151:                             $uname = $value;
                   2152:                         } elsif ($key eq 'domain') {
                   2153:                             $udom = $value;
1.911     raeburn  2154:                         }
1.899     raeburn  2155:                     }
                   2156:                     $results{$uname.':'.$udom} = \%userhash;
                   2157:                 }
                   2158:             }
                   2159:         }
                   2160:     }
                   2161:     return %results;
                   2162: }
                   2163: 
1.912     raeburn  2164: sub get_instuser {
                   2165:     my ($udom,$uname,$id) = @_;
                   2166:     my $homeserver = &domain($udom,'primary');
                   2167:     my ($outcome,%results);
                   2168:     if ($homeserver ne '') {
                   2169:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2170:                            &escape($id).':'.&escape($udom),$homeserver);
                   2171:         my $host=&hostname($homeserver);
                   2172:         if ($queryid !~/^\Q$host\E\_/) {
                   2173:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2174:             return;
                   2175:         }
                   2176:         my $response = &get_query_reply($queryid);
                   2177:         my $maxtries = 5;
                   2178:         my $tries = 1;
                   2179:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2180:             $response = &get_query_reply($queryid);
                   2181:             $tries ++;
                   2182:         }
                   2183:         if (!&error($response) && $response ne 'refused') {
                   2184:             if ($response eq 'unavailable') {
                   2185:                 $outcome = $response;
                   2186:             } else {
                   2187:                 $outcome = 'ok';
                   2188:                 my @matches = split(/\n/,$response);
                   2189:                 foreach my $match (@matches) {
                   2190:                     my ($key,$value) = split(/=/,$match);
                   2191:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2192:                 }
                   2193:             }
                   2194:         }
                   2195:     }
                   2196:     my %userinfo;
                   2197:     if (ref($results{$uname}) eq 'HASH') {
                   2198:         %userinfo = %{$results{$uname}};
                   2199:     } 
                   2200:     return ($outcome,%userinfo);
                   2201: }
                   2202: 
1.1172.2.69  raeburn  2203: sub get_multiple_instusers {
                   2204:     my ($udom,$users,$caller) = @_;
                   2205:     my ($outcome,$results);
                   2206:     if (ref($users) eq 'HASH') {
                   2207:         my $count = keys(%{$users});
                   2208:         my $requested = &freeze_escape($users);
                   2209:         my $homeserver = &domain($udom,'primary');
                   2210:         if ($homeserver ne '') {
                   2211:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2212:             my $host=&hostname($homeserver);
                   2213:             if ($queryid !~/^\Q$host\E\_/) {
                   2214:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2215:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2216:                 return ($outcome,$results);
                   2217:             }
                   2218:             my $response = &get_query_reply($queryid);
                   2219:             my $maxtries = 5;
                   2220:             if ($count > 100) {
                   2221:                 $maxtries = 1+int($count/20);
                   2222:             }
                   2223:             my $tries = 1;
                   2224:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2225:                 $response = &get_query_reply($queryid);
                   2226:                 $tries ++;
                   2227:             }
                   2228:             if ($response eq '') {
                   2229:                 $results = {};
                   2230:                 foreach my $key (keys(%{$users})) {
                   2231:                     my ($uname,$id);
                   2232:                     if ($caller eq 'id') {
                   2233:                         $id = $key;
                   2234:                     } else {
                   2235:                         $uname = $key;
                   2236:                     }
                   2237:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2238:                     $outcome = $resp;
                   2239:                     if ($resp eq 'ok') {
                   2240:                         %{$results} = (%{$results}, %info);
                   2241:                     } else {
                   2242:                         last;
                   2243:                     }
                   2244:                 }
                   2245:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2246:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2247:                     $outcome = $response;
                   2248:                 } else {
                   2249:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2250:                     if ($outcome eq 'ok') {
                   2251:                         $results = &thaw_unescape($userdata);
                   2252:                     }
                   2253:                 }
                   2254:             }
                   2255:         }
                   2256:     }
                   2257:     return ($outcome,$results);
                   2258: }
                   2259: 
1.912     raeburn  2260: sub inst_rulecheck {
1.923     raeburn  2261:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2262:     my %returnhash;
                   2263:     if ($udom ne '') {
                   2264:         if (ref($rules) eq 'ARRAY') {
                   2265:             @{$rules} = map {&escape($_);} (@{$rules});
                   2266:             my $rulestr = join(':',@{$rules});
                   2267:             my $homeserver=&domain($udom,'primary');
                   2268:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2269:                 my $response;
                   2270:                 if ($item eq 'username') {                
                   2271:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2272:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2273:                                               $homeserver));
1.923     raeburn  2274:                 } elsif ($item eq 'id') {
                   2275:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2276:                                               ':'.&escape($id).':'.$rulestr,
                   2277:                                               $homeserver));
1.945     raeburn  2278:                 } elsif ($item eq 'selfcreate') {
                   2279:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2280:                                                &escape($udom).':'.&escape($uname).
                   2281:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2282:                 }
1.912     raeburn  2283:                 if ($response ne 'refused') {
                   2284:                     my @pairs=split(/\&/,$response);
                   2285:                     foreach my $item (@pairs) {
                   2286:                         my ($key,$value)=split(/=/,$item,2);
                   2287:                         $key = &unescape($key);
                   2288:                         next if ($key =~ /^error: 2 /);
                   2289:                         $returnhash{$key}=&thaw_unescape($value);
                   2290:                     }
                   2291:                 }
                   2292:             }
                   2293:         }
                   2294:     }
                   2295:     return %returnhash;
                   2296: }
                   2297: 
                   2298: sub inst_userrules {
1.923     raeburn  2299:     my ($udom,$check) = @_;
1.912     raeburn  2300:     my (%ruleshash,@ruleorder);
                   2301:     if ($udom ne '') {
                   2302:         my $homeserver=&domain($udom,'primary');
                   2303:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2304:             my $response;
                   2305:             if ($check eq 'id') {
                   2306:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2307:                                  $homeserver);
1.943     raeburn  2308:             } elsif ($check eq 'email') {
                   2309:                 $response=&reply('instemailrules:'.&escape($udom),
                   2310:                                  $homeserver);
1.923     raeburn  2311:             } else {
                   2312:                 $response=&reply('instuserrules:'.&escape($udom),
                   2313:                                  $homeserver);
                   2314:             }
1.912     raeburn  2315:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2316:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2317:                 ($response ne 'no_such_host')) {
                   2318:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2319:                 my @pairs=split(/\&/,$hashitems);
                   2320:                 foreach my $item (@pairs) {
                   2321:                     my ($key,$value)=split(/=/,$item,2);
                   2322:                     $key = &unescape($key);
                   2323:                     next if ($key =~ /^error: 2 /);
                   2324:                     $ruleshash{$key}=&thaw_unescape($value);
                   2325:                 }
                   2326:                 my @esc_order = split(/\&/,$orderitems);
                   2327:                 foreach my $item (@esc_order) {
                   2328:                     push(@ruleorder,&unescape($item));
                   2329:                 }
                   2330:             }
                   2331:         }
                   2332:     }
                   2333:     return (\%ruleshash,\@ruleorder);
                   2334: }
                   2335: 
1.976     raeburn  2336: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2337: 
                   2338: sub get_domain_defaults {
1.1172.2.35  raeburn  2339:     my ($domain,$ignore_cache) = @_;
                   2340:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2341:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2342:     unless ($ignore_cache) {
                   2343:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2344:         if (defined($cached)) {
                   2345:             if (ref($result) eq 'HASH') {
                   2346:                 return %{$result};
                   2347:             }
1.943     raeburn  2348:         }
                   2349:     }
                   2350:     my %domdefaults;
                   2351:     my %domconfig =
1.989     raeburn  2352:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2353:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2354:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2355:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2356:                                   'coursecategories','autoenroll',
1.1172.2.146  raeburn  2357:                                   'helpsettings','wafproxy'],$domain);
1.1172.2.41  raeburn  2358:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2359:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2360:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2361:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2362:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2363:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2364:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2365:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2366:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2367:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2368:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2369:     } else {
                   2370:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2371:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2372:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2373:     }
1.976     raeburn  2374:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2375:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2376:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2377:         } else {
                   2378:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2379:         }
1.1172.2.6  raeburn  2380:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2381:         foreach my $item (@usertools) {
                   2382:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2383:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2384:             }
                   2385:         }
1.1172.2.29  raeburn  2386:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2387:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2388:         }
1.976     raeburn  2389:     }
1.985     raeburn  2390:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2391:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2392:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2393:         }
                   2394:     }
1.1172.2.9  raeburn  2395:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2396:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2397:     }
1.989     raeburn  2398:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2399:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2400:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2401:         }
                   2402:     }
1.1047    raeburn  2403:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2404:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
1.1172.2.144  raeburn  2405:         $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
1.1172.2.60  raeburn  2406:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2407:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2408:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2409:         }
1.1172.2.41  raeburn  2410:         foreach my $type (@coursetypes) {
                   2411:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2412:                 unless ($type eq 'community') {
                   2413:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2414:                 }
                   2415:             }
                   2416:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2417:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2418:             }
1.1172.2.60  raeburn  2419:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2420:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2421:                     $domdefaults{$type.'postsubtimeout'} =
                   2422:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2423:                 }
                   2424:             }
1.1172.2.30  raeburn  2425:         }
1.1172.2.67  raeburn  2426:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2427:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2428:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2429:                 if (@clonecodes) {
                   2430:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2431:                 }
                   2432:             }
                   2433:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2434:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2435:         }
1.1172.2.103  raeburn  2436:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2437:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2438:         }
1.1172.2.146.  .3(raebu 2439:22):         if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
                   2440:22):             $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
                   2441:22):         }
1.1047    raeburn  2442:     }
1.1073    raeburn  2443:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2444:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2445:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2446:         }
                   2447:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2448:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2449:         }
1.1172.2.62  raeburn  2450:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2451:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2452:         }
1.1172.2.137  raeburn  2453:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1172.2.136  raeburn  2454:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
                   2455:         }
1.1073    raeburn  2456:     }
1.1172.2.41  raeburn  2457:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2458:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2459:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2460:                             'approval','limit');
                   2461:             foreach my $type (@coursetypes) {
                   2462:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2463:                     my @mgrdc = ();
                   2464:                     foreach my $item (@settings) {
                   2465:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2466:                             push(@mgrdc,$item);
                   2467:                         }
                   2468:                     }
                   2469:                     if (@mgrdc) {
                   2470:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2471:                     }
                   2472:                 }
                   2473:             }
                   2474:         }
                   2475:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2476:             foreach my $type (@coursetypes) {
                   2477:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2478:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2479:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2480:                     }
                   2481:                 }
                   2482:             }
                   2483:         }
                   2484:     }
1.1172.2.46  raeburn  2485:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2486:         $domdefaults{'catauth'} = 'std';
                   2487:         $domdefaults{'catunauth'} = 'std';
                   2488:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2489:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2490:         }
                   2491:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2492:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2493:         }
                   2494:     }
1.1172.2.76  raeburn  2495:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2496:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
1.1172.2.146  raeburn  2497:         $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
1.1172.2.76  raeburn  2498:     }
1.1172.2.89  raeburn  2499:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2500:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2501:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2502:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2503:         }
                   2504:     }
1.1172.2.142  raeburn  2505:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   2506:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
                   2507:             if ($domconfig{'wafproxy'}{$item}) {
                   2508:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
                   2509:             }
                   2510:         }
                   2511:     }
1.1172.2.23  raeburn  2512:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2513:     return %domdefaults;
                   2514: }
                   2515: 
1.1172.2.106  raeburn  2516: sub get_dom_cats {
                   2517:     my ($dom) = @_;
                   2518:     return unless (&domain($dom));
                   2519:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2520:     unless (defined($cached)) {
                   2521:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2522:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2523:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2524:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2525:             } else {
                   2526:                 $cats = {};
                   2527:             }
                   2528:         } else {
                   2529:             $cats = {};
                   2530:         }
                   2531:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2532:     }
                   2533:     return $cats;
                   2534: }
                   2535: 
                   2536: sub get_dom_instcats {
                   2537:     my ($dom) = @_;
                   2538:     return unless (&domain($dom));
                   2539:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2540:     unless (defined($cached)) {
                   2541:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2542:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2543:         if ($totcodes > 0) {
                   2544:             my $caller = 'global';
                   2545:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2546:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2547:                 $instcats = {
                   2548:                                 codes => \%codes,
                   2549:                                 codetitles => \@codetitles,
                   2550:                                 cat_titles => \%cat_titles,
                   2551:                                 cat_order => \%cat_order,
                   2552:                             };
                   2553:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2554:             }
                   2555:         }
                   2556:     }
                   2557:     return $instcats;
                   2558: }
                   2559: 
                   2560: sub retrieve_instcodes {
                   2561:     my ($coursecodes,$dom) = @_;
                   2562:     my $totcodes;
                   2563:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2564:     foreach my $course (keys(%courses)) {
                   2565:         if (ref($courses{$course}) eq 'HASH') {
                   2566:             if ($courses{$course}{'inst_code'} ne '') {
                   2567:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2568:                 $totcodes ++;
                   2569:             }
                   2570:         }
                   2571:     }
                   2572:     return $totcodes;
                   2573: }
                   2574: 
1.1172.2.113  raeburn  2575: # --------------------------------------------- Get domain config for passwords
                   2576: 
                   2577: sub get_passwdconf {
                   2578:     my ($dom) = @_;
                   2579:     my (%passwdconf,$gotconf,$lookup);
                   2580:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2581:     if (defined($cached)) {
                   2582:         if (ref($result) eq 'HASH') {
                   2583:             %passwdconf = %{$result};
                   2584:             $gotconf = 1;
                   2585:         }
                   2586:     }
                   2587:     unless ($gotconf) {
                   2588:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2589:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2590:             %passwdconf = %{$domconfig{'passwords'}};
                   2591:         }
                   2592:         my $cachetime = 24*60*60;
                   2593:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2594:     }
                   2595:     return %passwdconf;
                   2596: }
                   2597: 
1.1172.2.146.  .1(raebu 2598:22): sub course_portal_url {
                   2599:22):     my ($cnum,$cdom,$r) = @_;
                   2600:22):     my $chome = &homeserver($cnum,$cdom);
                   2601:22):     my $hostname = &hostname($chome);
                   2602:22):     my $protocol = $protocol{$chome};
                   2603:22):     $protocol = 'http' if ($protocol ne 'https');
                   2604:22):     my %domdefaults = &get_domain_defaults($cdom);
                   2605:22):     my $firsturl;
                   2606:22):     if ($domdefaults{'portal_def'}) {
                   2607:22):         $firsturl = $domdefaults{'portal_def'};
                   2608:22):     } else {
                   2609:22):         my $alias = &Apache::lonnet::use_proxy_alias($r,$chome);
                   2610:22):         $hostname = $alias if ($alias ne '');
                   2611:22):         $firsturl = $protocol.'://'.$hostname;
                   2612:22):     }
                   2613:22):     return $firsturl;
                   2614:22): }
                   2615:22): 
1.344     www      2616: # --------------------------------------------------- Assign a key to a student
                   2617: 
                   2618: sub assign_access_key {
1.364     www      2619: #
                   2620: # a valid key looks like uname:udom#comments
                   2621: # comments are being appended
                   2622: #
1.498     www      2623:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2624:     $kdom=
1.620     albertel 2625:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2626:     $knum=
1.620     albertel 2627:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2628:     $cdom=
1.620     albertel 2629:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2630:     $cnum=
1.620     albertel 2631:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2632:     $udom=$env{'user.name'} unless (defined($udom));
                   2633:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2634:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2635:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2636:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2637:                                                   # assigned to this person
                   2638:                                                   # - this should not happen,
1.345     www      2639:                                                   # unless something went wrong
                   2640:                                                   # the first time around
                   2641: # ready to assign
1.364     www      2642:         $logentry=$1.'; '.$logentry;
1.496     www      2643:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2644:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2645: # key now belongs to user
1.346     www      2646: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2647:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2648:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2649:                 return 'ok';
                   2650:             } else {
                   2651:                 return 
                   2652:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2653: 	    }
                   2654:         } else {
                   2655:             return 'error: Could not assign key, try again later.';
                   2656:         }
1.364     www      2657:     } elsif (!$existing{$ckey}) {
1.345     www      2658: # the key does not exist
                   2659: 	return 'error: The key does not exist';
                   2660:     } else {
                   2661: # the key is somebody else's
                   2662: 	return 'error: The key is already in use';
                   2663:     }
1.344     www      2664: }
                   2665: 
1.364     www      2666: # ------------------------------------------ put an additional comment on a key
                   2667: 
                   2668: sub comment_access_key {
                   2669: #
                   2670: # a valid key looks like uname:udom#comments
                   2671: # comments are being appended
                   2672: #
                   2673:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2674:     $cdom=
1.620     albertel 2675:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2676:     $cnum=
1.620     albertel 2677:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2678:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2679:     if ($existing{$ckey}) {
                   2680:         $existing{$ckey}.='; '.$logentry;
                   2681: # ready to assign
1.367     www      2682:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2683:                                                  $cdom,$cnum) eq 'ok') {
                   2684: 	    return 'ok';
                   2685:         } else {
                   2686: 	    return 'error: Count not store comment.';
                   2687:         }
                   2688:     } else {
                   2689: # the key does not exist
                   2690: 	return 'error: The key does not exist';
                   2691:     }
                   2692: }
                   2693: 
1.344     www      2694: # ------------------------------------------------------ Generate a set of keys
                   2695: 
                   2696: sub generate_access_keys {
1.364     www      2697:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2698:     $cdom=
1.620     albertel 2699:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2700:     $cnum=
1.620     albertel 2701:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2702:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2703:     unless (($cdom) && ($cnum)) { return 0; }
                   2704:     if ($number>10000) { return 0; }
                   2705:     sleep(2); # make sure don't get same seed twice
                   2706:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2707:     my $total=0;
                   2708:     for (my $i=1;$i<=$number;$i++) {
                   2709:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2710:                   sprintf("%lx",int(100000*rand)).'-'.
                   2711:                   sprintf("%lx",int(100000*rand));
                   2712:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2713:        $newkey=~s/0/h/g; # and also 0 and O
                   2714:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2715:        if ($existing{$newkey}) {
                   2716:            $i--;
                   2717:        } else {
1.364     www      2718: 	  if (&put('accesskeys',
                   2719:               { $newkey => '# generated '.localtime().
1.620     albertel 2720:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2721:                            '; '.$logentry },
                   2722: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2723:               $total++;
                   2724: 	  }
                   2725:        }
                   2726:     }
1.620     albertel 2727:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2728:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2729:     return $total;
                   2730: }
                   2731: 
                   2732: # ------------------------------------------------------- Validate an accesskey
                   2733: 
                   2734: sub validate_access_key {
                   2735:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2736:     $cdom=
1.620     albertel 2737:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2738:     $cnum=
1.620     albertel 2739:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2740:     $udom=$env{'user.domain'} unless (defined($udom));
                   2741:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2742:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2743:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2744: }
                   2745: 
                   2746: # ------------------------------------- Find the section of student in a course
1.652     albertel 2747: sub devalidate_getsection_cache {
                   2748:     my ($udom,$unam,$courseid)=@_;
                   2749:     my $hashid="$udom:$unam:$courseid";
                   2750:     &devalidate_cache_new('getsection',$hashid);
                   2751: }
1.298     matthew  2752: 
1.815     albertel 2753: sub courseid_to_courseurl {
                   2754:     my ($courseid) = @_;
                   2755:     #already url style courseid
                   2756:     return $courseid if ($courseid =~ m{^/});
                   2757: 
                   2758:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2759: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2760: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2761: 	return "/$cdom/$cnum";
                   2762:     }
                   2763: 
                   2764:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2765:     if (exists($courseinfo{'num'})) {
                   2766: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2767:     }
                   2768: 
                   2769:     return undef;
                   2770: }
                   2771: 
1.298     matthew  2772: sub getsection {
                   2773:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2774:     my $cachetime=1800;
1.551     albertel 2775: 
                   2776:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2777:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2778:     if (defined($cached)) { return $result; }
                   2779: 
1.298     matthew  2780:     my %Pending; 
                   2781:     my %Expired;
                   2782:     #
                   2783:     # Each role can either have not started yet (pending), be active, 
                   2784:     #    or have expired.
                   2785:     #
                   2786:     # If there is an active role, we are done.
                   2787:     #
                   2788:     # If there is more than one role which has not started yet, 
                   2789:     #     choose the one which will start sooner
                   2790:     # If there is one role which has not started yet, return it.
                   2791:     #
                   2792:     # If there is more than one expired role, choose the one which ended last.
                   2793:     # If there is a role which has expired, return it.
                   2794:     #
1.815     albertel 2795:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2796:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2797:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2798:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2799:         my $section=$1;
                   2800:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2801:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2802:         my $now=time;
1.548     albertel 2803:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2804:             $Expired{$end}=$section;
                   2805:             next;
                   2806:         }
1.548     albertel 2807:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2808:             $Pending{$start}=$section;
                   2809:             next;
                   2810:         }
1.599     albertel 2811:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2812:     }
                   2813:     #
                   2814:     # Presumedly there will be few matching roles from the above
                   2815:     # loop and the sorting time will be negligible.
                   2816:     if (scalar(keys(%Pending))) {
                   2817:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2818:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2819:     } 
                   2820:     if (scalar(keys(%Expired))) {
                   2821:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2822:         my $time = pop(@sorted);
1.599     albertel 2823:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2824:     }
1.599     albertel 2825:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2826: }
1.70      www      2827: 
1.599     albertel 2828: sub save_cache {
                   2829:     &purge_remembered();
1.722     albertel 2830:     #&Apache::loncommon::validate_page();
1.620     albertel 2831:     undef(%env);
1.780     albertel 2832:     undef($env_loaded);
1.599     albertel 2833: }
1.452     albertel 2834: 
1.599     albertel 2835: my $to_remember=-1;
                   2836: my %remembered;
                   2837: my %accessed;
                   2838: my $kicks=0;
                   2839: my $hits=0;
1.849     albertel 2840: sub make_key {
                   2841:     my ($name,$id) = @_;
1.872     albertel 2842:     if (length($id) > 65 
                   2843: 	&& length(&escape($id)) > 200) {
                   2844: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2845:     }
1.849     albertel 2846:     return &escape($name.':'.$id);
                   2847: }
                   2848: 
1.599     albertel 2849: sub devalidate_cache_new {
                   2850:     my ($name,$id,$debug) = @_;
                   2851:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2852:     my $remembered_id=$name.':'.$id;
1.849     albertel 2853:     $id=&make_key($name,$id);
1.599     albertel 2854:     $memcache->delete($id);
1.1172.2.81  raeburn  2855:     delete($remembered{$remembered_id});
                   2856:     delete($accessed{$remembered_id});
1.599     albertel 2857: }
                   2858: 
                   2859: sub is_cached_new {
                   2860:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2861:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2862:                                      # keys in %remembered hash, which persists for
                   2863:                                      # duration of request (no restriction on key length).
                   2864:     if (exists($remembered{$remembered_id})) {
                   2865: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2866: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2867: 	$hits++;
1.1172.2.81  raeburn  2868: 	return ($remembered{$remembered_id},1);
1.599     albertel 2869:     }
1.1172.2.81  raeburn  2870:     $id=&make_key($name,$id);
1.599     albertel 2871:     my $value = $memcache->get($id);
                   2872:     if (!(defined($value))) {
                   2873: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2874: 	return (undef,undef);
1.416     albertel 2875:     }
1.599     albertel 2876:     if ($value eq '__undef__') {
                   2877: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2878: 	$value=undef;
                   2879:     }
1.1172.2.81  raeburn  2880:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2881:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2882:     return ($value,1);
                   2883: }
                   2884: 
                   2885: sub do_cache_new {
                   2886:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2887:     my $remembered_id=$name.':'.$id;
1.849     albertel 2888:     $id=&make_key($name,$id);
1.599     albertel 2889:     my $setvalue=$value;
                   2890:     if (!defined($setvalue)) {
                   2891: 	$setvalue='__undef__';
                   2892:     }
1.623     albertel 2893:     if (!defined($time) ) {
                   2894: 	$time=600;
                   2895:     }
1.599     albertel 2896:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2897:     my $result = $memcache->set($id,$setvalue,$time);
                   2898:     if (! $result) {
1.872     albertel 2899: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2900: 	$memcache->disconnect_all();
1.872     albertel 2901:     }
1.600     albertel 2902:     # need to make a copy of $value
1.1172.2.81  raeburn  2903:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2904:     return $value;
                   2905: }
                   2906: 
                   2907: sub make_room {
1.1172.2.81  raeburn  2908:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2909: 
1.1172.2.81  raeburn  2910:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2911:                                     : $value;
1.599     albertel 2912:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2913:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2914:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2915:     my $to_kick;
                   2916:     my $max_time=0;
                   2917:     foreach my $other (keys(%accessed)) {
                   2918: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2919: 	    $to_kick=$other;
                   2920: 	    $max_time=&tv_interval($accessed{$other});
                   2921: 	}
                   2922:     }
                   2923:     delete($remembered{$to_kick});
                   2924:     delete($accessed{$to_kick});
                   2925:     $kicks++;
                   2926:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2927:     return;
                   2928: }
                   2929: 
1.599     albertel 2930: sub purge_remembered {
1.604     albertel 2931:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2932:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2933:     undef(%remembered);
                   2934:     undef(%accessed);
1.428     albertel 2935: }
1.70      www      2936: # ------------------------------------- Read an entry from a user's environment
                   2937: 
                   2938: sub userenvironment {
                   2939:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2940:     my $items;
                   2941:     foreach my $item (@what) {
                   2942:         $items.=&escape($item).'&';
                   2943:     }
                   2944:     $items=~s/\&$//;
1.70      www      2945:     my %returnhash=();
1.1009    raeburn  2946:     my $uhome = &homeserver($unam,$udom);
                   2947:     unless ($uhome eq 'no_host') {
                   2948:         my @answer=split(/\&/, 
                   2949:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2950:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2951:             return %returnhash;
                   2952:         }
1.1009    raeburn  2953:         my $i;
                   2954:         for ($i=0;$i<=$#what;$i++) {
                   2955: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2956:         }
1.70      www      2957:     }
                   2958:     return %returnhash;
1.1       albertel 2959: }
                   2960: 
1.617     albertel 2961: # ---------------------------------------------------------- Get a studentphoto
                   2962: sub studentphoto {
                   2963:     my ($udom,$unam,$ext) = @_;
                   2964:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2965:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2966:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2967:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2968:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2969:             } else {
                   2970:                 my ($result,$perm_reqd)=
1.707     albertel 2971: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2972:                 if ($result eq 'ok') {
                   2973:                     if (!($perm_reqd eq 'yes')) {
                   2974:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2975:                     }
                   2976:                 }
                   2977:             }
                   2978:         }
                   2979:     } else {
                   2980:         my ($result,$perm_reqd) = 
1.707     albertel 2981: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2982:         if ($result eq 'ok') {
                   2983:             if (!($perm_reqd eq 'yes')) {
                   2984:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2985:             }
                   2986:         }
                   2987:     }
                   2988:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2989: }
                   2990: 
                   2991: sub retrievestudentphoto {
                   2992:     my ($udom,$unam,$ext,$type) = @_;
                   2993:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2994:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2995:     if ($ret eq 'ok') {
                   2996:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2997:         if ($type eq 'thumbnail') {
                   2998:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2999:         }
                   3000:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   3001:         return $tokenurl;
                   3002:     } else {
                   3003:         if ($type eq 'thumbnail') {
                   3004:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3005:         } else { 
                   3006:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3007:         }
1.617     albertel 3008:     }
                   3009: }
                   3010: 
1.263     www      3011: # -------------------------------------------------------------------- New chat
                   3012: 
                   3013: sub chatsend {
1.724     raeburn  3014:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3015:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3016:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3017:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3018:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3019: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3020: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3021: }
                   3022: 
                   3023: # ------------------------------------------ Find current version of a resource
                   3024: 
                   3025: sub getversion {
                   3026:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  3027:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3028:     return &currentversion(&filelocation('',$fname));
                   3029: }
                   3030: 
                   3031: sub currentversion {
                   3032:     my $fname=shift;
                   3033:     my $author=$fname;
                   3034:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3035:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3036:     my $home=&homeserver($uname,$udom);
1.292     www      3037:     if ($home eq 'no_host') { 
                   3038:         return -1; 
                   3039:     }
1.1112    www      3040:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3041:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3042: 	return -1;
                   3043:     }
1.1112    www      3044:     return $answer;
1.263     www      3045: }
                   3046: 
1.1111    www      3047: #
                   3048: # Return special version number of resource if set by override, empty otherwise
                   3049: #
                   3050: sub usedversion {
                   3051:     my $fname=shift;
                   3052:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3053:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3054:     if ($urlversion) { return $urlversion; }
                   3055:     return '';
                   3056: }
                   3057: 
1.1       albertel 3058: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3059: 
1.1       albertel 3060: sub subscribe {
                   3061:     my $fname=shift;
1.761     raeburn  3062:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3063:     $fname=~s/[\n\r]//g;
1.1       albertel 3064:     my $author=$fname;
                   3065:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3066:     my ($udom,$uname)=split(/\//,$author);
                   3067:     my $home=homeserver($uname,$udom);
1.335     albertel 3068:     if ($home eq 'no_host') {
                   3069:         return 'not_found';
1.1       albertel 3070:     }
                   3071:     my $answer=reply("sub:$fname",$home);
1.64      www      3072:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3073: 	$answer.=' by '.$home;
                   3074:     }
1.1       albertel 3075:     return $answer;
                   3076: }
                   3077:     
1.8       www      3078: # -------------------------------------------------------------- Replicate file
                   3079: 
                   3080: sub repcopy {
                   3081:     my $filename=shift;
1.23      www      3082:     $filename=~s/\/+/\//g;
1.1142    raeburn  3083:     my $londocroot = $perlvar{'lonDocRoot'};
                   3084:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3085:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3086:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3087: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3088: 	return &repcopy_userfile($filename);
                   3089:     }
1.532     albertel 3090:     $filename=~s/[\n\r]//g;
1.8       www      3091:     my $transname="$filename.in.transfer";
1.828     www      3092: # FIXME: this should flock
1.607     raeburn  3093:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3094:     my $remoteurl=subscribe($filename);
1.64      www      3095:     if ($remoteurl =~ /^con_lost by/) {
                   3096: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3097:            return 'unavailable';
1.8       www      3098:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3099: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3100: 	   return 'not_found';
1.64      www      3101:     } elsif ($remoteurl =~ /^rejected by/) {
                   3102: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3103:            return 'forbidden';
1.20      www      3104:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3105:            return 'ok';
1.8       www      3106:     } else {
1.290     www      3107:         my $author=$filename;
                   3108:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3109:         my ($udom,$uname)=split(/\//,$author);
                   3110:         my $home=homeserver($uname,$udom);
                   3111:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3112:            my @parts=split(/\//,$filename);
                   3113:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3114:            if ($path ne "$londocroot/res") {
1.8       www      3115:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3116: 	       return 'bad_request';
1.8       www      3117:            }
                   3118:            my $count;
                   3119:            for ($count=5;$count<$#parts;$count++) {
                   3120:                $path.="/$parts[$count]";
                   3121:                if ((-e $path)!=1) {
                   3122: 		   mkdir($path,0777);
                   3123:                }
                   3124:            }
                   3125:            my $ua=new LWP::UserAgent;
                   3126:            my $request=new HTTP::Request('GET',"$remoteurl");
                   3127:            my $response=$ua->request($request,$transname);
                   3128:            if ($response->is_error()) {
                   3129: 	       unlink($transname);
                   3130:                my $message=$response->status_line;
1.672     albertel 3131:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3132:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3133:                return 'unavailable';
1.8       www      3134:            } else {
1.16      www      3135: 	       if ($remoteurl!~/\.meta$/) {
                   3136:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   3137:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   3138:                   if ($mresponse->is_error()) {
                   3139: 		      unlink($filename.'.meta');
                   3140:                       &logthis(
1.672     albertel 3141:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3142:                   }
                   3143: 	       }
1.8       www      3144:                rename($transname,$filename);
1.607     raeburn  3145:                return 'ok';
1.8       www      3146:            }
1.290     www      3147:        }
1.8       www      3148:     }
1.330     www      3149: }
                   3150: 
1.1172.2.124  raeburn  3151: # ------------------------------------------------- Unsubscribe from a resource
                   3152: 
                   3153: sub unsubscribe {
                   3154:     my ($fname) = @_;
                   3155:     my $answer;
                   3156:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3157:     $fname=~s/[\n\r]//g;
                   3158:     my $author=$fname;
                   3159:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3160:     my ($udom,$uname)=split(/\//,$author);
                   3161:     my $home=homeserver($uname,$udom);
                   3162:     if ($home eq 'no_host') {
                   3163:         $answer = 'no_host';
                   3164:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3165:         $answer = 'home';
                   3166:     } else {
1.1172.2.125  raeburn  3167:         $answer = reply("unsub:$fname",$home);
1.1172.2.124  raeburn  3168:     }
                   3169:     return $answer;
                   3170: }
                   3171: 
1.330     www      3172: # ------------------------------------------------ Get server side include body
                   3173: sub ssi_body {
1.381     albertel 3174:     my ($filelink,%form)=@_;
1.606     matthew  3175:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3176:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3177:     }
1.953     www      3178:     my $output='';
                   3179:     my $response;
1.980     raeburn  3180:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3181:        ($output,$response)=&externalssi($filelink);
1.953     www      3182:     } else {
1.1004    droeschl 3183:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3184:        $filelink .= 'inhibitmenu=yes';
1.953     www      3185:        ($output,$response)=&ssi($filelink,%form);
                   3186:     }
1.778     albertel 3187:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3188:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3189:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3190:     if (wantarray) {
                   3191:         return ($output, $response);
                   3192:     } else {
                   3193:         return $output;
                   3194:     }
1.8       www      3195: }
                   3196: 
1.15      www      3197: # --------------------------------------------------------- Server Side Include
                   3198: 
1.782     albertel 3199: sub absolute_url {
1.1172.2.145  raeburn  3200:     my ($host_name,$unalias,$keep_proto) = @_;
1.782     albertel 3201:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3202:     if ($host_name eq '') {
                   3203: 	$host_name = $ENV{'SERVER_NAME'};
                   3204:     }
1.1172.2.145  raeburn  3205:     if ($unalias) {
                   3206:         my $alias = &get_proxy_alias();
                   3207:         if ($alias eq $host_name) {
                   3208:             my $lonhost = $perlvar{'lonHostID'};
                   3209:             my $hostname = &hostname($lonhost);
                   3210:             my $lcproto;
                   3211:             if (($keep_proto) || ($hostname eq '')) {
                   3212:                 $lcproto = $protocol;
                   3213:             } else {
                   3214:                 $lcproto = $protocol{$lonhost};
                   3215:                 $lcproto = 'http' if ($lcproto ne 'https');
                   3216:                 $lcproto .= '://';
                   3217:             }
                   3218:             unless ($hostname eq '') {
                   3219:                 return $lcproto.$hostname;
                   3220:             }
                   3221:         }
                   3222:     } 
1.782     albertel 3223:     return $protocol.$host_name;
                   3224: }
                   3225: 
1.942     foxr     3226: #
                   3227: #   Server side include.
                   3228: # Parameters:
                   3229: #  fn     Possibly encrypted resource name/id.
                   3230: #  form   Hash that describes how the rendering should be done
                   3231: #         and other things.
1.944     foxr     3232: # Returns:
1.950     raeburn  3233: #   Scalar context: The content of the response.
                   3234: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3235: #     
1.15      www      3236: sub ssi {
                   3237: 
1.944     foxr     3238:     my ($fn,%form)=@_;
1.1172.2.145  raeburn  3239:     my ($host,$request,$response);
                   3240:     $host = &absolute_url('',1);
1.711     albertel 3241: 
                   3242:     $form{'no_update_last_known'}=1;
1.895     albertel 3243:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3244:     if (%form) {
1.1172.2.145  raeburn  3245:       $request=new HTTP::Request('POST',$host.$fn);
1.1172.2.58  raeburn  3246:       $request->content(join('&',map {
                   3247:             my $name = escape($_);
                   3248:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3249:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3250:             : &escape($form{$_}) );
                   3251:         } keys(%form)));
1.23      www      3252:     } else {
1.1172.2.145  raeburn  3253:       $request=new HTTP::Request('GET',$host.$fn);
1.23      www      3254:     }
                   3255: 
1.15      www      3256:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3257: 
1.1172.2.101  raeburn  3258:     if (($env{'request.course.id'}) &&
                   3259:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3260:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3261:         ($form{'grade_symb'} ne '') &&
                   3262:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3263:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3264:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3265:             my $ua=new LWP::UserAgent;
                   3266:             $ua->local_address('127.0.0.1');
                   3267:             $response = $ua->request($request);
                   3268:         } else {
                   3269:             {
                   3270:                 require LWP::Protocol::http;
                   3271:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3272:                 my $ua=new LWP::UserAgent;
                   3273:                 $response = $ua->request($request);
                   3274:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3275:             }
                   3276:         }
                   3277:     } else {
                   3278:         my $ua=new LWP::UserAgent;
                   3279:         $response = $ua->request($request);
                   3280:     }
1.944     foxr     3281:     if (wantarray) {
1.1172.2.3  raeburn  3282: 	return ($response->content, $response);
1.944     foxr     3283:     } else {
1.1172.2.3  raeburn  3284: 	return $response->content;
1.942     foxr     3285:     }
1.324     www      3286: }
                   3287: 
                   3288: sub externalssi {
                   3289:     my ($url)=@_;
                   3290:     my $ua=new LWP::UserAgent;
                   3291:     my $request=new HTTP::Request('GET',$url);
                   3292:     my $response=$ua->request($request);
1.954     raeburn  3293:     if (wantarray) {
                   3294:         return ($response->content, $response);
                   3295:     } else {
                   3296:         return $response->content;
                   3297:     }
1.15      www      3298: }
1.254     www      3299: 
1.1172.2.98  raeburn  3300: # If the local copy of a replicated resource is outdated, trigger a
                   3301: # connection from the homeserver to flush the delayed queue. If no update
                   3302: # happens, remove local copies of outdated resource (and corresponding
                   3303: # metadata file).
                   3304: 
                   3305: sub remove_stale_resfile {
                   3306:     my ($url) = @_;
                   3307:     my $removed;
                   3308:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3309:         my $audom = $1;
                   3310:         my $auname = $2;
                   3311:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3312:             my $homeserver = &homeserver($auname,$audom);
                   3313:             unless (($homeserver eq 'no_host') ||
                   3314:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3315:                 my $fname = &filelocation('',$url);
                   3316:                 if (-e $fname) {
                   3317:                     my $hostname = &hostname($homeserver);
                   3318:                     if ($hostname) {
1.1172.2.120  raeburn  3319:                         my $protocol = $protocol{$homeserver};
                   3320:                         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98  raeburn  3321:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.120  raeburn  3322:                         my $ua=new LWP::UserAgent;
                   3323:                         $ua->timeout(5);
1.1172.2.98  raeburn  3324:                         my $request=new HTTP::Request('HEAD',$uri);
                   3325:                         my $response=$ua->request($request);
                   3326:                         if ($response->is_success()) {
                   3327:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3328:                             my $locmodtime = (stat($fname))[9];
                   3329:                             if ($locmodtime < $remmodtime) {
                   3330:                                 my $stale;
                   3331:                                 my $answer = &reply('pong',$homeserver);
                   3332:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3333:                                     sleep(0.2);
                   3334:                                     $locmodtime = (stat($fname))[9];
                   3335:                                     if ($locmodtime < $remmodtime) {
                   3336:                                         my $posstransfer = $fname.'.in.transfer';
                   3337:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3338:                                             $removed = 1;
                   3339:                                         } else {
                   3340:                                             $stale = 1;
                   3341:                                         }
                   3342:                                     } else {
                   3343:                                         $removed = 1;
                   3344:                                     }
                   3345:                                 } else {
                   3346:                                     $stale = 1;
                   3347:                                 }
                   3348:                                 if ($stale) {
1.1172.2.124  raeburn  3349:                                     if (unlink($fname)) {
                   3350:                                         if ($uri!~/\.meta$/) {
                   3351:                                             if (-e $fname.'.meta') {
                   3352:                                                 unlink($fname.'.meta');
                   3353:                                             }
                   3354:                                         }
                   3355:                                         my $unsubresult = &unsubscribe($fname);
                   3356:                                         unless ($unsubresult eq 'ok') {
                   3357:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3358:                                         }
                   3359:                                         $removed = 1;
1.1172.2.98  raeburn  3360:                                     }
                   3361:                                 }
                   3362:                             }
                   3363:                         }
                   3364:                     }
                   3365:                 }
                   3366:             }
                   3367:         }
                   3368:     }
                   3369:     return $removed;
                   3370: }
                   3371: 
1.492     albertel 3372: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3373: 
                   3374: sub allowuploaded {
                   3375:     my ($srcurl,$url)=@_;
                   3376:     $url=&clutter(&declutter($url));
                   3377:     my $dir=$url;
                   3378:     $dir=~s/\/[^\/]+$//;
                   3379:     my %httpref=();
                   3380:     my $httpurl=&hreflocation('',$url);
                   3381:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3382:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3383: }
1.477     raeburn  3384: 
1.1172.2.13  raeburn  3385: #
                   3386: # Determine if the current user should be able to edit a particular resource,
                   3387: # when viewing in course context.
                   3388: # (a) When viewing resource used to determine if "Edit" item is included in
                   3389: #     Functions.
                   3390: # (b) When displaying folder contents in course editor, used to determine if
                   3391: #     "Edit" link will be displayed alongside resource.
                   3392: #
                   3393: #  input: six args -- filename (decluttered), course number, course domain,
                   3394: #                   url, symb (if registered) and group (if this is a group
                   3395: #                   item -- e.g., bulletin board, group page etc.).
                   3396: #  output: array of five scalars --
                   3397: #          $cfile -- url for file editing if editable on current server
                   3398: #          $home -- homeserver of resource (i.e., for author if published,
                   3399: #                                           or course if uploaded.).
                   3400: #          $switchserver --  1 if server switch will be needed.
                   3401: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3402: #          $forceview -- 1 if icon/link should be to go to view mode
                   3403: #
                   3404: 
                   3405: sub can_edit_resource {
                   3406:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3407:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3408: #
                   3409: # For aboutme pages user can only edit his/her own.
                   3410: #
                   3411:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3412:         my ($sdom,$sname) = ($1,$2);
                   3413:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3414:             $home = $env{'user.home'};
                   3415:             $cfile = $resurl;
                   3416:             if ($env{'form.forceedit'}) {
                   3417:                 $forceview = 1;
                   3418:             } else {
                   3419:                 $forceedit = 1;
                   3420:             }
                   3421:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3422:         } else {
                   3423:             return;
                   3424:         }
                   3425:     }
                   3426: 
                   3427:     if ($env{'request.course.id'}) {
                   3428:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3429:         if ($group ne '') {
                   3430: # if this is a group homepage or group bulletin board, check group privs
                   3431:             my $allowed = 0;
                   3432:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3433:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3434:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3435:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3436:                     $allowed = 1;
                   3437:                 }
                   3438:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3439:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3440:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3441:                     $allowed = 1;
                   3442:                 }
                   3443:             }
                   3444:             if ($allowed) {
                   3445:                 $home=&homeserver($cnum,$cdom);
                   3446:                 if ($env{'form.forceedit'}) {
                   3447:                     $forceview = 1;
                   3448:                 } else {
                   3449:                     $forceedit = 1;
                   3450:                 }
                   3451:                 $cfile = $resurl;
                   3452:             } else {
                   3453:                 return;
                   3454:             }
                   3455:         } else {
1.1172.2.15  raeburn  3456:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3457:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3458:                     return;
                   3459:                 }
                   3460:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3461: #
                   3462: # No edit allowed where CC has switched to student role.
                   3463: #
                   3464:                 return;
                   3465:             }
                   3466:         }
                   3467:     }
                   3468: 
                   3469:     if ($file ne '') {
                   3470:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3471:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3472:                 $uploaded = 1;
                   3473:                 $incourse = 1;
                   3474:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3475:                     $cfile = &hreflocation('',$file);
                   3476:                     if ($env{'form.forceedit'}) {
                   3477:                         $forceview = 1;
                   3478:                     } else {
                   3479:                         $forceedit = 1;
                   3480:                     }
                   3481:                 }
                   3482:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3483:                 $incourse = 1;
                   3484:                 if ($env{'form.forceedit'}) {
                   3485:                     $forceview = 1;
                   3486:                 } else {
                   3487:                     $forceedit = 1;
                   3488:                 }
                   3489:                 $cfile = $resurl;
                   3490:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3491:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3492:                     $incourse = 1;
                   3493:                     if ($env{'form.forceedit'}) {
                   3494:                         $forceview = 1;
                   3495:                     } else {
                   3496:                         $forceedit = 1;
                   3497:                     }
                   3498:                     $cfile = $resurl;
                   3499:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3500:                     $incourse = 1;
                   3501:                     $cfile = $resurl.'/smpedit';
                   3502:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3503:                     $incourse = 1;
                   3504:                     if ($env{'form.forceedit'}) {
                   3505:                         $forceview = 1;
                   3506:                     } else {
                   3507:                         $forceedit = 1;
                   3508:                     }
                   3509:                     $cfile = $resurl;
1.1172.2.122  raeburn  3510:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3511:                     my ($map,$id,$res) = &decode_symb($symb);
                   3512:                     if ($map =~ /\.page$/) {
                   3513:                         $incourse = 1;
                   3514:                         if ($env{'form.forceedit'}) {
                   3515:                             $forceview = 1;
                   3516:                             $cfile = $map;
                   3517:                         } else {
                   3518:                             $forceedit = 1;
                   3519:                             $cfile =  '/adm/wrapper'.$resurl;
                   3520:                         }
                   3521:                     }
1.1172.2.146.  .1(raebu 3522:22):                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3523:22):                     $incourse = 1;
                   3524:22):                     if ($env{'form.forceedit'}) {
                   3525:22):                         $forceview = 1;
                   3526:22):                     } else {
                   3527:22):                         $forceedit = 1;
                   3528:22):                     }
                   3529:22):                     $cfile = $resurl;
1.1172.2.15  raeburn  3530:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3531:                     $incourse = 1;
                   3532:                     if ($env{'form.forceedit'}) {
                   3533:                         $forceview = 1;
                   3534:                     } else {
                   3535:                         $forceedit = 1;
                   3536:                     }
                   3537:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3538:                 }
                   3539:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3540:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3541:                 if (&is_on_map($template)) {
                   3542:                     $incourse = 1;
                   3543:                     $forceview = 1;
                   3544:                     $cfile = $template;
                   3545:                 }
                   3546:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118  raeburn  3547:                 $incourse = 1;
                   3548:                 if ($env{'form.forceedit'}) {
                   3549:                     $forceview = 1;
                   3550:                 } else {
                   3551:                     $forceedit = 1;
                   3552:                 }
                   3553:                 $cfile = $resurl;
1.1172.2.146.  .1(raebu 3554:22):             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3555:22):                 $incourse = 1;
                   3556:22):                 if ($env{'form.forceedit'}) {
                   3557:22):                     $forceview = 1;
                   3558:22):                 } else {
                   3559:22):                     $forceedit = 1;
                   3560:22):                 }
                   3561:22):                 $cfile = $resurl;
1.1172.2.13  raeburn  3562:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3563:                 $incourse = 1;
                   3564:                 $forceview = 1;
                   3565:                 if ($symb) {
                   3566:                     my ($map,$id,$res)=&decode_symb($symb);
                   3567:                     $env{'request.symb'} = $symb;
                   3568:                     $cfile = &clutter($res);
                   3569:                 } else {
                   3570:                     $cfile = $env{'form.suppurl'};
1.1172.2.146.  .1(raebu 3571:22):                     my $escfile = &unescape($cfile);
                   3572:22):                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3573:22):                         $cfile = '/adm/wrapper'.$escfile;
                   3574:22):                     } else {
                   3575:22):                         $escfile =~ s{^http://}{};
                   3576:22):                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3577:22):                     }
1.1172.2.13  raeburn  3578:                 }
1.1172.2.31  raeburn  3579:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3580:                 if ($env{'form.forceedit'}) {
                   3581:                     $forceview = 1;
                   3582:                 } else {
                   3583:                     $forceedit = 1;
                   3584:                 }
                   3585:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3586:             }
                   3587:         }
                   3588:         if ($uploaded || $incourse) {
                   3589:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3590:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3591:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3592:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3593:             # Check that the user has permission to edit this resource
                   3594:             my $setpriv = 1;
                   3595:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3596:             if (defined($cfudom)) {
                   3597:                 $home=&homeserver($cfuname,$cfudom);
                   3598:                 $cfile=$file;
                   3599:             }
                   3600:         }
                   3601:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3602:             (($home ne '') && ($home ne 'no_host'))) {
                   3603:             my @ids=&current_machine_ids();
                   3604:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3605:                 $switchserver=1;
                   3606:             }
                   3607:         }
                   3608:     }
                   3609:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3610: }
                   3611: 
                   3612: sub is_course_upload {
                   3613:     my ($file,$cnum,$cdom) = @_;
                   3614:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3615:     $uploadpath =~ s{^\/}{};
                   3616:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3617:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3618:         return 1;
                   3619:     }
                   3620:     return;
                   3621: }
                   3622: 
                   3623: sub in_course {
                   3624:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3625:     if ($hideprivileged) {
                   3626:         my $skipuser;
1.1172.2.23  raeburn  3627:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3628:         my @possdoms = ($cdom);
                   3629:         if ($coursehash{'checkforpriv'}) {
                   3630:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3631:         }
                   3632:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3633:             $skipuser = 1;
                   3634:             if ($coursehash{'nothideprivileged'}) {
                   3635:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3636:                     my $user;
                   3637:                     if ($item =~ /:/) {
                   3638:                         $user = $item;
                   3639:                     } else {
                   3640:                         $user = join(':',split(/[\@]/,$item));
                   3641:                     }
                   3642:                     if ($user eq $uname.':'.$udom) {
                   3643:                         undef($skipuser);
                   3644:                         last;
                   3645:                     }
                   3646:                 }
                   3647:             }
                   3648:             if ($skipuser) {
                   3649:                 return 0;
                   3650:             }
                   3651:         }
                   3652:     }
                   3653:     $type ||= 'any';
                   3654:     if (!defined($cdom) || !defined($cnum)) {
                   3655:         my $cid  = $env{'request.course.id'};
                   3656:         $cdom = $env{'course.'.$cid.'.domain'};
                   3657:         $cnum = $env{'course.'.$cid.'.num'};
                   3658:     }
                   3659:     my $typesref;
                   3660:     if (($type eq 'any') || ($type eq 'all')) {
                   3661:         $typesref = ['active','previous','future'];
                   3662:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3663:         $typesref = [$type];
                   3664:     }
                   3665:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3666:                               $typesref,undef,[$cdom]);
                   3667:     my ($tmp) = keys(%roles);
                   3668:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3669:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3670:     if (@course_roles > 0) {
                   3671:         return 1;
                   3672:     }
                   3673:     return 0;
                   3674: }
                   3675: 
1.478     albertel 3676: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3677: # input: action, courseID, current domain, intended
1.637     raeburn  3678: #        path to file, source of file, instruction to parse file for objects,
                   3679: #        ref to hash for embedded objects,
                   3680: #        ref to hash for codebase of java objects.
1.1095    raeburn  3681: #        reference to scalar to accommodate mime type determined
                   3682: #          from File::MMagic if $parser = parse.
1.637     raeburn  3683: #
1.485     raeburn  3684: # output: url to file (if action was uploaddoc), 
                   3685: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3686: #
1.478     albertel 3687: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3688: # course.
1.477     raeburn  3689: #
1.478     albertel 3690: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3691: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3692: #          course's home server.
1.477     raeburn  3693: #
1.478     albertel 3694: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3695: #          be copied from $source (current location) to 
                   3696: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3697: #         and will then be copied to
                   3698: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3699: #         course's home server.
1.485     raeburn  3700: #
1.481     raeburn  3701: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3702: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3703: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3704: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3705: #         in course's home server.
1.637     raeburn  3706: #
1.477     raeburn  3707: 
                   3708: sub process_coursefile {
1.1095    raeburn  3709:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3710:         $mimetype)=@_;
1.477     raeburn  3711:     my $fetchresult;
1.638     albertel 3712:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3713:     if ($action eq 'propagate') {
1.638     albertel 3714:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3715: 			     $home);
1.481     raeburn  3716:     } else {
1.477     raeburn  3717:         my $fpath = '';
                   3718:         my $fname = $file;
1.478     albertel 3719:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3720:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3721:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3722:         if ($action eq 'copy') {
                   3723:             if ($source eq '') {
                   3724:                 $fetchresult = 'no source file';
                   3725:                 return $fetchresult;
                   3726:             } else {
                   3727:                 my $destination = $filepath.'/'.$fname;
                   3728:                 rename($source,$destination);
                   3729:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3730:                                  $home);
1.481     raeburn  3731:             }
                   3732:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3733:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3734:             print $fh $env{'form.'.$source};
1.481     raeburn  3735:             close($fh);
1.637     raeburn  3736:             if ($parser eq 'parse') {
1.1024    raeburn  3737:                 my $mm = new File::MMagic;
1.1095    raeburn  3738:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3739:                 if ($type eq 'text/html') {
1.1024    raeburn  3740:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3741:                     unless ($parse_result eq 'ok') {
                   3742:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3743:                     }
1.637     raeburn  3744:                 }
1.1095    raeburn  3745:                 if (ref($mimetype)) {
                   3746:                     $$mimetype = $type;
                   3747:                 } 
1.637     raeburn  3748:             }
1.477     raeburn  3749:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3750:                                  $home);
1.481     raeburn  3751:             if ($fetchresult eq 'ok') {
                   3752:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3753:             } else {
                   3754:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3755:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3756:                 return '/adm/notfound.html';
                   3757:             }
1.477     raeburn  3758:         }
                   3759:     }
1.485     raeburn  3760:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3761:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3762:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3763:     }
                   3764:     return $fetchresult;
                   3765: }
                   3766: 
1.637     raeburn  3767: sub build_filepath {
                   3768:     my ($fpath) = @_;
                   3769:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3770:     unless ($fpath eq '') {
                   3771:         my @parts=split('/',$fpath);
                   3772:         foreach my $part (@parts) {
                   3773:             $filepath.= '/'.$part;
                   3774:             if ((-e $filepath)!=1) {
                   3775:                 mkdir($filepath,0777);
                   3776:             }
                   3777:         }
                   3778:     }
                   3779:     return $filepath;
                   3780: }
                   3781: 
                   3782: sub store_edited_file {
1.638     albertel 3783:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3784:     my $file = $primary_url;
                   3785:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3786:     my $fpath = '';
                   3787:     my $fname = $file;
                   3788:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3789:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3790:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3791:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3792:     print $fh $content;
                   3793:     close($fh);
1.638     albertel 3794:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3795:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3796: 			  $home);
1.637     raeburn  3797:     if ($$fetchresult eq 'ok') {
                   3798:         return '/uploaded/'.$fpath.'/'.$fname;
                   3799:     } else {
1.638     albertel 3800:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3801: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3802:         return '/adm/notfound.html';
                   3803:     }
                   3804: }
                   3805: 
1.531     albertel 3806: sub clean_filename {
1.831     albertel 3807:     my ($fname,$args)=@_;
1.315     www      3808: # Replace Windows backslashes by forward slashes
1.257     www      3809:     $fname=~s/\\/\//g;
1.831     albertel 3810:     if (!$args->{'keep_path'}) {
                   3811:         # Get rid of everything but the actual filename
                   3812: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3813:     }
1.315     www      3814: # Replace spaces by underscores
                   3815:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  3816: # Transliterate non-ascii text to ascii
                   3817:     my $lang = &Apache::lonlocal::current_language();
                   3818:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3819: # Replace all other weird characters by nothing
1.831     albertel 3820:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3821: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3822: # numbers
                   3823:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1172.2.140  raeburn  3824: # Replace three or more adjacent underscores with one for consistency
                   3825: # with loncfile::filename_check() so complete url can be extracted by
                   3826: # lonnet::decode_symb()
                   3827:     $fname=~s/_{3,}/_/g;
1.531     albertel 3828:     return $fname;
                   3829: }
1.1172.2.110  raeburn  3830: 
1.1051    raeburn  3831: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3832: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3833: # image with the same aspect ratio as the original, but with dimensions which do 
                   3834: # not exceed $resizewidth and $resizeheight.
                   3835:  
1.984     neumanie 3836: sub resizeImage {
1.1051    raeburn  3837:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3838:     my $ima = Image::Magick->new;
                   3839:     my $resized;
                   3840:     if (-e $img_path) {
                   3841:         $ima->Read($img_path);
                   3842:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3843:             my $width = $ima->Get('width');
                   3844:             my $height = $ima->Get('height');
                   3845:             if ($width > $resizewidth) {
                   3846: 	        my $factor = $width/$resizewidth;
                   3847:                 my $newheight = $height/$factor;
                   3848:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3849:                 $resized = 1;
                   3850:             }
                   3851:         }
                   3852:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3853:             my $width = $ima->Get('width');
                   3854:             my $height = $ima->Get('height');
                   3855:             if ($height > $resizeheight) {
                   3856:                 my $factor = $height/$resizeheight;
                   3857:                 my $newwidth = $width/$factor;
                   3858:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3859:                 $resized = 1;
                   3860:             }
                   3861:         }
                   3862:         if ($resized) {
                   3863:             $ima->Write($img_path);
                   3864:         }
                   3865:     }
                   3866:     return;
1.977     amueller 3867: }
                   3868: 
1.608     albertel 3869: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3870: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3871: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3872: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.109  raeburn  3873: #                                    canceloverwrite, scantron or ''. 
1.1090    raeburn  3874: #                   if 'coursedoc': upload to the current course
                   3875: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3876: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3877: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3878: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  3879: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3880: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3881: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   3882: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3883: #        $allfiles - reference to hash for embedded objects
                   3884: #        $codebase - reference to hash for codebase of java objects
                   3885: #        $desuname - username for permanent storage of uploaded file
                   3886: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3887: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3888: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3889: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3890: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3891: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3892: #                    from File::MMagic.
1.858     raeburn  3893: # 
1.686     albertel 3894: # output: url of file in userspace, or error: <message> 
                   3895: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3896: 
1.531     albertel 3897: sub userfileupload {
1.1090    raeburn  3898:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3899:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3900:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3901:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3902:     $fname=&clean_filename($fname);
1.1090    raeburn  3903:     # See if there is anything left
1.257     www      3904:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  3905:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   3906:     if ($fname =~ /^\./) {
                   3907:         my ($s,$usec) = &gettimeofday();
                   3908:         while (length($usec) < 6) {
                   3909:             $usec = '0'.$usec;
                   3910:         }
                   3911:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   3912:     }
1.1090    raeburn  3913:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3914:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3915:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3916:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3917:         my $now = time;
1.1090    raeburn  3918:         my $filepath;
1.1095    raeburn  3919:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3920:              $filepath = 'tmp/helprequests/'.$now;
                   3921:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3922:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3923:                          '_'.$env{'user.domain'}.'/pending';
                   3924:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3925:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3926:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3927:                 $docudom = $destudom;
                   3928:             } else {
                   3929:                 $docudom = $env{'user.domain'};
                   3930:             }
1.1172.2.96  raeburn  3931:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3932:                 $docuname = $destuname;
                   3933:             } else {
                   3934:                 $docuname = $env{'user.name'};
                   3935:             }
                   3936:             if (exists($env{'form.group'})) {
                   3937:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3938:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3939:             }
                   3940:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3941:             if ($context eq 'canceloverwrite') {
                   3942:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3943:                 if (-e  $tempfile) {
                   3944:                     my @info = stat($tempfile);
                   3945:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3946:                         unlink($tempfile);
                   3947:                     }
                   3948:                 }
                   3949:                 return;
1.523     raeburn  3950:             }
                   3951:         }
1.1090    raeburn  3952:         # Create the directory if not present
1.741     raeburn  3953:         my @parts=split(/\//,$filepath);
                   3954:         my $fullpath = $perlvar{'lonDaemons'};
                   3955:         for (my $i=0;$i<@parts;$i++) {
                   3956:             $fullpath .= '/'.$parts[$i];
                   3957:             if ((-e $fullpath)!=1) {
                   3958:                 mkdir($fullpath,0777);
                   3959:             }
                   3960:         }
1.1172.2.96  raeburn  3961:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3962:         print $fh $env{'form.'.$formname};
                   3963:         close($fh);
1.1090    raeburn  3964:         if ($context eq 'existingfile') {
                   3965:             my @info = stat($fullpath.'/'.$fname);
                   3966:             return ($fullpath.'/'.$fname,$info[9]);
                   3967:         } else {
                   3968:             return $fullpath.'/'.$fname;
                   3969:         }
1.523     raeburn  3970:     }
1.995     raeburn  3971:     if ($subdir eq 'scantron') {
                   3972:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3973:     } else {
1.995     raeburn  3974:         $fname="$subdir/$fname";
                   3975:     }
1.1090    raeburn  3976:     if ($context eq 'coursedoc') {
1.638     albertel 3977: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3978: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3979:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3980:             return &finishuserfileupload($docuname,$docudom,
                   3981: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3982: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3983:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3984:         } else {
1.1172.2.21  raeburn  3985:             if ($env{'form.folder'}) {
                   3986:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3987:             }
1.638     albertel 3988:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3989: 				       $fname,$formname,$parser,
1.1095    raeburn  3990: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3991:         }
1.719     banghart 3992:     } elsif (defined($destuname)) {
                   3993:         my $docuname=$destuname;
                   3994:         my $docudom=$destudom;
1.860     raeburn  3995: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3996: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3997:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3998:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3999:     } else {
1.638     albertel 4000:         my $docuname=$env{'user.name'};
                   4001:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  4002:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  4003:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4004:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4005:         }
1.860     raeburn  4006: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4007: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4008:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4009:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4010:     }
1.271     www      4011: }
                   4012: 
                   4013: sub finishuserfileupload {
1.860     raeburn  4014:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  4015:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  4016:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      4017:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 4018:   
1.860     raeburn  4019:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 4020:     $file=$fname;
                   4021:     if ($fname=~m|/|) {
                   4022:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   4023: 	$path.=$fnamepath.'/';
                   4024:     }
1.259     www      4025:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      4026:     my $count;
                   4027:     for ($count=4;$count<=$#parts;$count++) {
                   4028:         $filepath.="/$parts[$count]";
                   4029:         if ((-e $filepath)!=1) {
                   4030: 	    mkdir($filepath,0777);
                   4031:         }
                   4032:     }
1.984     neumanie 4033: 
1.258     www      4034: # Save the file
                   4035:     {
1.1172.2.96  raeburn  4036: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4037: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4038: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4039: 	    return '/adm/notfound.html';
                   4040: 	}
1.1090    raeburn  4041:         if ($context eq 'overwrite') {
1.1117    foxr     4042:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4043:             my $target = $filepath.'/'.$file;
                   4044:             if (-e $source) {
                   4045:                 my @info = stat($source);
                   4046:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4047:                     unless (&File::Copy::move($source,$target)) {
                   4048:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4049:                         return "Moving from $source failed";
                   4050:                     }
                   4051:                 } else {
                   4052:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4053:                 }
                   4054:             } else {
                   4055:                 return "Temporary file: $source missing";
                   4056:             }
                   4057:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4058: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4059: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4060: 	    return '/adm/notfound.html';
                   4061: 	}
1.570     albertel 4062: 	close(FH);
1.1051    raeburn  4063:         if ($resizewidth && $resizeheight) {
                   4064:             my $mm = new File::MMagic;
                   4065:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4066:             if ($mime_type =~ m{^image/}) {
                   4067: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4068:             }  
1.977     amueller 4069: 	}
1.258     www      4070:     }
1.1152    raeburn  4071:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4072:         if (ref($mimetype)) {
                   4073:             if ($$mimetype eq '') {
                   4074:                 my $mm = new File::MMagic;
                   4075:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4076:                 $$mimetype = $type;
                   4077:             }
                   4078:         }
                   4079:     }
1.1172.2.109  raeburn  4080:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4081:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4082:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4083:                                                        $allfiles,$codebase);
                   4084:             unless ($parse_result eq 'ok') {
                   4085:                 &logthis('Failed to parse '.$filepath.$file.
                   4086: 	   	         ' for embedded media: '.$parse_result); 
                   4087:             }
1.637     raeburn  4088:         }
1.1172.2.109  raeburn  4089:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4090:         my $format = $env{'form.scantron_format'};
                   4091:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4092:     }
1.860     raeburn  4093:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4094:         my $input = $filepath.'/'.$file;
                   4095:         my $output = $filepath.'/'.'tn-'.$file;
                   4096:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  4097:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4098:         system({$args[0]} @args);
1.860     raeburn  4099:         if (-e $filepath.'/'.'tn-'.$file) {
                   4100:             $fetchthumb  = 1; 
                   4101:         }
                   4102:     }
1.858     raeburn  4103:  
1.259     www      4104: # Notify homeserver to grep it
                   4105: #
1.984     neumanie 4106:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4107:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4108:     if ($fetchresult eq 'ok') {
1.860     raeburn  4109:         if ($fetchthumb) {
                   4110:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4111:             if ($thumbresult ne 'ok') {
                   4112:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4113:                          $docuhome.': '.$thumbresult);
                   4114:             }
                   4115:         }
1.259     www      4116: #
1.258     www      4117: # Return the URL to it
1.494     albertel 4118:         return '/uploaded/'.$path.$file;
1.263     www      4119:     } else {
1.494     albertel 4120:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4121: 		 ': '.$fetchresult);
1.263     www      4122:         return '/adm/notfound.html';
1.858     raeburn  4123:     }
1.493     albertel 4124: }
                   4125: 
1.637     raeburn  4126: sub extract_embedded_items {
1.961     raeburn  4127:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4128:     my @state = ();
1.1164    raeburn  4129:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4130:     my %javafiles = (
                   4131:                       codebase => '',
                   4132:                       code => '',
                   4133:                       archive => ''
                   4134:                     );
                   4135:     my %mediafiles = (
                   4136:                       src => '',
                   4137:                       movie => '',
                   4138:                      );
1.648     raeburn  4139:     my $p;
                   4140:     if ($content) {
                   4141:         $p = HTML::LCParser->new($content);
                   4142:     } else {
1.961     raeburn  4143:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4144:     }
1.641     albertel 4145:     while (my $t=$p->get_token()) {
1.640     albertel 4146: 	if ($t->[0] eq 'S') {
                   4147: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4148: 	    push(@state, $tagname);
1.648     raeburn  4149:             if (lc($tagname) eq 'allow') {
                   4150:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4151:             }
1.640     albertel 4152: 	    if (lc($tagname) eq 'img') {
                   4153: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4154: 	    }
1.886     albertel 4155: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  4156:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   4157: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   4158:                 }
1.886     albertel 4159: 	    }
1.645     raeburn  4160:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4161:                 my $src;
1.645     raeburn  4162:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4163:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4164:                 } else {
1.1164    raeburn  4165:                     if ($attr->{'src'} ne '') {
                   4166:                         $src = $attr->{'src'};
                   4167:                         &add_filetype($allfiles,$src,'src');
                   4168:                     }
                   4169:                 }
                   4170:                 my $text = $p->get_trimmed_text();
                   4171:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4172:                     my @swfargs = split(/,/,$1);
                   4173:                     foreach my $item (@swfargs) {
                   4174:                         $item =~ s/["']//g;
                   4175:                         $item =~ s/^\s+//;
                   4176:                         $item =~ s/\s+$//;
                   4177:                     }
                   4178:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4179:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4180:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4181:                         } else {
                   4182:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4183:                         }
                   4184:                     }
1.645     raeburn  4185:                 }
                   4186:             }
                   4187:             if (lc($tagname) eq 'link') {
                   4188:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4189:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4190:                 }
                   4191:             }
1.640     albertel 4192: 	    if (lc($tagname) eq 'object' ||
                   4193: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4194: 		foreach my $item (keys(%javafiles)) {
                   4195: 		    $javafiles{$item} = '';
                   4196: 		}
1.1164    raeburn  4197:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4198:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4199:                 }
1.640     albertel 4200: 	    }
                   4201: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4202: 		my $name = lc($attr->{'name'});
                   4203: 		foreach my $item (keys(%javafiles)) {
                   4204: 		    if ($name eq $item) {
                   4205: 			$javafiles{$item} = $attr->{'value'};
                   4206: 			last;
                   4207: 		    }
                   4208: 		}
1.1164    raeburn  4209:                 my $pathfrom;
1.640     albertel 4210: 		foreach my $item (keys(%mediafiles)) {
                   4211: 		    if ($name eq $item) {
1.1164    raeburn  4212:                         $pathfrom = $attr->{'value'};
                   4213:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4214: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4215: 			last;
                   4216: 		    }
                   4217: 		}
1.1164    raeburn  4218:                 if ($name eq 'flashvars') {
                   4219:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4220:                 }
                   4221:                 if ($pathfrom ne '') {
                   4222:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4223:                                          $pathfrom);
                   4224:                 }
1.640     albertel 4225: 	    }
                   4226: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4227: 		foreach my $item (keys(%javafiles)) {
                   4228: 		    if ($attr->{$item}) {
                   4229: 			$javafiles{$item} = $attr->{$item};
                   4230: 			last;
                   4231: 		    }
                   4232: 		}
                   4233: 		foreach my $item (keys(%mediafiles)) {
                   4234: 		    if ($attr->{$item}) {
                   4235: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4236: 			last;
                   4237: 		    }
                   4238: 		}
1.1164    raeburn  4239:                 if (lc($tagname) eq 'embed') {
                   4240:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4241:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4242:                                              $attr->{'src'});
                   4243:                     }
                   4244:                 }
1.640     albertel 4245: 	    }
1.1172.2.35  raeburn  4246:             if (lc($tagname) eq 'iframe') {
                   4247:                 my $src = $attr->{'src'} ;
                   4248:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4249:                     &add_filetype($allfiles,$src,'src');
                   4250:                 } elsif ($src =~ m{^/}) {
                   4251:                     if ($env{'request.course.id'}) {
                   4252:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4253:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4254:                         my $url = &hreflocation('',$fullpath);
                   4255:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4256:                             my $relpath = $1;
                   4257:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4258:                                 &add_filetype($allfiles,$1,'src');
                   4259:                             }
                   4260:                         }
                   4261:                     }
                   4262:                 }
                   4263:             }
1.1164    raeburn  4264:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4265:                 pop(@state);
1.1164    raeburn  4266:             }
1.640     albertel 4267: 	} elsif ($t->[0] eq 'E') {
                   4268: 	    my ($tagname) = ($t->[1]);
                   4269: 	    if ($javafiles{'codebase'} ne '') {
                   4270: 		$javafiles{'codebase'} .= '/';
                   4271: 	    }  
                   4272: 	    if (lc($tagname) eq 'applet' ||
                   4273: 		lc($tagname) eq 'object' ||
                   4274: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4275: 		) {
                   4276: 		foreach my $item (keys(%javafiles)) {
                   4277: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4278: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4279: 			&add_filetype($allfiles,$file,$item);
                   4280: 		    }
                   4281: 		}
                   4282: 	    } 
                   4283: 	    pop @state;
                   4284: 	}
                   4285:     }
1.1164    raeburn  4286:     foreach my $id (sort(keys(%flashvars))) {
                   4287:         if ($shockwave{$id} ne '') {
                   4288:             my @pairs = split(/\&/,$flashvars{$id});
                   4289:             foreach my $pair (@pairs) {
                   4290:                 my ($key,$value) = split(/\=/,$pair);
                   4291:                 if ($key eq 'thumb') {
                   4292:                     &add_filetype($allfiles,$value,$key);
                   4293:                 } elsif ($key eq 'content') {
                   4294:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4295:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4296:                     if ($ext ne '') {
                   4297:                         &add_filetype($allfiles,$path.$value,$ext);
                   4298:                     }
                   4299:                 }
                   4300:             }
                   4301:         }
                   4302:     }
1.637     raeburn  4303:     return 'ok';
                   4304: }
                   4305: 
1.639     albertel 4306: sub add_filetype {
                   4307:     my ($allfiles,$file,$type)=@_;
                   4308:     if (exists($allfiles->{$file})) {
                   4309: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4310: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4311: 	}
                   4312:     } else {
                   4313: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4314:     }
                   4315: }
                   4316: 
1.1164    raeburn  4317: sub embedded_dependency {
                   4318:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4319:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4320:         if (($identifier ne '') &&
                   4321:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4322:             ($pathfrom ne '')) {
                   4323:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4324:             foreach my $dep (@{$related->{$identifier}}) {
                   4325:                 &add_filetype($allfiles,$path.$dep,'object');
                   4326:             }
                   4327:         }
                   4328:     }
                   4329:     return;
                   4330: }
                   4331: 
1.1172.2.109  raeburn  4332: sub bubblesheet_converter {
                   4333:     my ($cdom,$fullpath,$config,$format) = @_;
                   4334:     if ((&domain($cdom) ne '') &&
                   4335:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4336:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4337:         my (%csvcols,%csvoptions);
                   4338:         if (ref($config->{'fields'}) eq 'HASH') {
                   4339:             %csvcols = %{$config->{'fields'}};
                   4340:         }
                   4341:         if (ref($config->{'options'}) eq 'HASH') {
                   4342:             %csvoptions = %{$config->{'options'}};
                   4343:         }
                   4344:         my %csvbynum = reverse(%csvcols);
                   4345:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4346:         if (keys(%scantronconf)) {
                   4347:             my %bynum = (
                   4348:                           $scantronconf{CODEstart} => 'CODEstart',
                   4349:                           $scantronconf{IDstart}   => 'IDstart',
                   4350:                           $scantronconf{PaperID}   => 'PaperID',
                   4351:                           $scantronconf{FirstName} => 'FirstName',
                   4352:                           $scantronconf{LastName}  => 'LastName',
                   4353:                           $scantronconf{Qstart}    => 'Qstart',
                   4354:                         );
                   4355:             my @ordered;
                   4356:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4357:                 push(@ordered,$bynum{$item});
                   4358:             }
                   4359:             my %mapstart = (
                   4360:                               CODEstart => 'CODE',
                   4361:                               IDstart   => 'ID',
                   4362:                               PaperID   => 'PaperID',
                   4363:                               FirstName => 'FirstName',
                   4364:                               LastName  => 'LastName',
                   4365:                               Qstart    => 'FirstQuestion',
                   4366:                            );
                   4367:             my %maplength = (
                   4368:                               CODEstart => 'CODElength',
                   4369:                               IDstart   => 'IDlength',
                   4370:                               PaperID   => 'PaperIDlength',
                   4371:                               FirstName => 'FirstNamelength',
                   4372:                               LastName  => 'LastNamelength',
                   4373:             );
                   4374:             if (open(my $fh,'<',$fullpath)) {
                   4375:                 my $output;
                   4376:                 my %lettdig = &letter_to_digits();
                   4377:                 my %diglett = reverse(%lettdig);
                   4378:                 my $numletts = scalar(keys(%lettdig));
                   4379:                 my $num = 0;
                   4380:                 while (my $line=<$fh>) {
                   4381:                     $num ++;
                   4382:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4383:                     $line =~ s{[\r\n]+$}{};
                   4384:                     my %found;
1.1172.2.143  raeburn  4385:                     my @values = split(/,/,$line,-1);
1.1172.2.109  raeburn  4386:                     my ($qstart,$record);
                   4387:                     for (my $i=0; $i<@values; $i++) {
                   4388:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4389:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4390:                             if ($values[$i] eq '') {
                   4391:                                 $values[$i] = $scantronconf{'Qoff'};
                   4392:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4393:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4394:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4395:                                 }
                   4396:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4397:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4398:                                     $values[$i] = $diglett{$values[$i]};
                   4399:                                 }
                   4400:                             } else {
                   4401:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4402:                                     my $digit;
                   4403:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4404:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4405:                                         if ($values[$i] eq 'J') {
                   4406:                                             $digit += $numletts;
                   4407:                                         }
                   4408:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4409:                                         $digit = $values[$i]-1;
                   4410:                                         if ($values[$i] eq '0') {
                   4411:                                             $digit += $numletts;
                   4412:                                         }
                   4413:                                     }
                   4414:                                     my $qval='';
                   4415:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4416:                                         if ($j == $digit) {
                   4417:                                             $qval .= $scantronconf{'Qon'};
                   4418:                                         } else {
                   4419:                                             $qval .= $scantronconf{'Qoff'};
                   4420:                                         }
                   4421:                                     }
                   4422:                                     $values[$i] = $qval;
                   4423:                                 }
                   4424:                             }
                   4425:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4426:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4427:                             }
                   4428:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4429:                             if ($numblank > 0) {
                   4430:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4431:                             }
                   4432:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4433:                                 $qstart = $i;
                   4434:                                 $found{$csvbynum{$i}} = $values[$i];
                   4435:                             } else {
                   4436:                                 $found{'FirstQuestion'} .= $values[$i];
                   4437:                             }
                   4438:                         } elsif (exists($csvbynum{$i})) {
                   4439:                             if ($csvoptions{'rem'}) {
                   4440:                                 $values[$i] =~ s/^\s+//;
                   4441:                             }
                   4442:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4443:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4444:                                     $values[$i] = '0'.$values[$i];
                   4445:                                 }
                   4446:                             }
                   4447:                             $found{$csvbynum{$i}} = $values[$i];
                   4448:                         }
                   4449:                     }
                   4450:                     foreach my $item (@ordered) {
                   4451:                         my $currlength = 1+length($record);
                   4452:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4453:                         if ($numspaces > 0) {
                   4454:                             $record .= (' ' x $numspaces);
                   4455:                         }
                   4456:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4457:                             unless ($item eq 'Qstart') {
                   4458:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4459:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4460:                                 }
                   4461:                             }
                   4462:                             $record .= $found{$mapstart{$item}};
                   4463:                         }
                   4464:                     }
                   4465:                     $output .= "$record\n";
                   4466:                 }
                   4467:                 close($fh);
                   4468:                 if ($output) {
                   4469:                     if (open(my $fh,'>',$fullpath)) {
                   4470:                         print $fh $output;
                   4471:                         close($fh);
                   4472:                     }
                   4473:                 }
                   4474:             }
                   4475:         }
                   4476:         return;
                   4477:     }
                   4478: }
                   4479: 
                   4480: sub letter_to_digits {
                   4481:     my %lettdig = (
                   4482:                     A => 1,
                   4483:                     B => 2,
                   4484:                     C => 3,
                   4485:                     D => 4,
                   4486:                     E => 5,
                   4487:                     F => 6,
                   4488:                     G => 7,
                   4489:                     H => 8,
                   4490:                     I => 9,
                   4491:                     J => 0,
                   4492:                   );
                   4493:     return %lettdig;
                   4494: }
                   4495: 
                   4496: sub get_scantron_config {
                   4497:     my ($which,$cdom) = @_;
                   4498:     my @lines = &get_scantronformat_file($cdom);
                   4499:     my %config;
                   4500:     #FIXME probably should move to XML it has already gotten a bit much now
                   4501:     foreach my $line (@lines) {
                   4502:         my ($name,$descrip)=split(/:/,$line);
                   4503:         if ($name ne $which ) { next; }
                   4504:         chomp($line);
                   4505:         my @config=split(/:/,$line);
                   4506:         $config{'name'}=$config[0];
                   4507:         $config{'description'}=$config[1];
                   4508:         $config{'CODElocation'}=$config[2];
                   4509:         $config{'CODEstart'}=$config[3];
                   4510:         $config{'CODElength'}=$config[4];
                   4511:         $config{'IDstart'}=$config[5];
                   4512:         $config{'IDlength'}=$config[6];
                   4513:         $config{'Qstart'}=$config[7];
                   4514:         $config{'Qlength'}=$config[8];
                   4515:         $config{'Qoff'}=$config[9];
                   4516:         $config{'Qon'}=$config[10];
                   4517:         $config{'PaperID'}=$config[11];
                   4518:         $config{'PaperIDlength'}=$config[12];
                   4519:         $config{'FirstName'}=$config[13];
                   4520:         $config{'FirstNamelength'}=$config[14];
                   4521:         $config{'LastName'}=$config[15];
                   4522:         $config{'LastNamelength'}=$config[16];
                   4523:         $config{'BubblesPerRow'}=$config[17];
                   4524:         last;
                   4525:     }
                   4526:     return %config;
                   4527: }
                   4528: 
                   4529: sub get_scantronformat_file {
                   4530:     my ($cdom) = @_;
                   4531:     if ($cdom eq '') {
                   4532:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4533:     }
                   4534:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4535:     my $gottab = 0;
                   4536:     my @lines;
                   4537:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4538:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4539:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4540:             if ($formatfile ne '-1') {
                   4541:                 @lines = split("\n",$formatfile,-1);
                   4542:                 $gottab = 1;
                   4543:             }
                   4544:         }
                   4545:     }
                   4546:     if (!$gottab) {
                   4547:         my $confname = $cdom.'-domainconfig';
                   4548:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4549:         my $formatfile = &getfile($default);
                   4550:         if ($formatfile ne '-1') {
                   4551:             @lines = split("\n",$formatfile,-1);
                   4552:             $gottab = 1;
                   4553:         }
                   4554:     }
                   4555:     if (!$gottab) {
                   4556:         my @domains = &current_machine_domains();
                   4557:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4558:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4559:                 @lines = <$fh>;
                   4560:                 close($fh);
                   4561:             }
                   4562:         } else {
                   4563:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4564:                 @lines = <$fh>;
                   4565:                 close($fh);
                   4566:             }
                   4567:         }
                   4568:     }
                   4569:     return @lines;
                   4570: }
                   4571: 
1.493     albertel 4572: sub removeuploadedurl {
1.984     neumanie 4573:     my ($url)=@_;	
                   4574:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4575:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4576: }
                   4577: 
                   4578: sub removeuserfile {
                   4579:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4580:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4581:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4582:     if ($result eq 'ok') {	
1.798     raeburn  4583:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4584:             my $metafile = $fname.'.meta';
                   4585:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4586: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4587:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4588:             my $sqlresult = 
1.823     albertel 4589:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4590:                                         'portfolio_metadata',$group,
                   4591:                                         'delete');
1.798     raeburn  4592:         }
                   4593:     }
                   4594:     return $result;
1.257     www      4595: }
1.15      www      4596: 
1.530     albertel 4597: sub mkdiruserfile {
                   4598:     my ($docuname,$docudom,$dir)=@_;
                   4599:     my $home=&homeserver($docuname,$docudom);
                   4600:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4601: }
                   4602: 
1.531     albertel 4603: sub renameuserfile {
                   4604:     my ($docuname,$docudom,$old,$new)=@_;
                   4605:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4606:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4607:                         &escape("$old").':'.&escape("$new"),$home);
                   4608:     if ($result eq 'ok') {
                   4609:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4610:             my $oldmeta = $old.'.meta';
                   4611:             my $newmeta = $new.'.meta';
                   4612:             my $metaresult = 
                   4613:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4614: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4615:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4616:             my $sqlresult = 
1.823     albertel 4617:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4618:                                         'portfolio_metadata',$group,
                   4619:                                         'delete');
1.798     raeburn  4620:         }
                   4621:     }
                   4622:     return $result;
1.531     albertel 4623: }
                   4624: 
1.14      www      4625: # ------------------------------------------------------------------------- Log
                   4626: 
                   4627: sub log {
                   4628:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4629:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4630: }
                   4631: 
                   4632: # ------------------------------------------------------------------ Course Log
1.352     www      4633: #
                   4634: # This routine flushes several buffers of non-mission-critical nature
                   4635: #
1.157     www      4636: 
                   4637: sub flushcourselogs {
1.352     www      4638:     &logthis('Flushing log buffers');
                   4639: #
                   4640: # course logs
                   4641: # This is a log of all transactions in a course, which can be used
                   4642: # for data mining purposes
                   4643: #
                   4644: # It also collects the courseid database, which lists last transaction
                   4645: # times and course titles for all courseids
                   4646: #
                   4647:     my %courseidbuffer=();
1.921     raeburn  4648:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4649:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4650: 		          &escape($courselogs{$crsid}),
                   4651: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4652: 	    delete $courselogs{$crsid};
                   4653:         } else {
                   4654:             &logthis('Failed to flush log buffer for '.$crsid);
                   4655:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4656:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4657:                         " exceeded maximum size, deleting.</font>");
                   4658:                delete $courselogs{$crsid};
                   4659:             }
1.352     www      4660:         }
1.920     raeburn  4661:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4662:             'description' => $coursedescrbuf{$crsid},
                   4663:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4664:             'type'        => $coursetypebuf{$crsid},
                   4665:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4666:         };
1.191     harris41 4667:     }
1.352     www      4668: #
                   4669: # Write course id database (reverse lookup) to homeserver of courses 
                   4670: # Is used in pickcourse
                   4671: #
1.840     albertel 4672:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4673:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4674:                                     $courseidbuffer{$crs_home},
                   4675:                                     $crs_home,'timeonly');
1.352     www      4676:     }
                   4677: #
                   4678: # File accesses
                   4679: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4680: #
1.449     matthew  4681:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4682:         if ($entry =~ /___count$/) {
                   4683:             my ($dom,$name);
1.807     albertel 4684:             ($dom,$name,undef)=
1.811     albertel 4685: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4686:             if (! defined($dom) || $dom eq '' || 
                   4687:                 ! defined($name) || $name eq '') {
1.620     albertel 4688:                 my $cid = $env{'request.course.id'};
1.1172.2.142  raeburn  4689: #
                   4690: # FIXME 11/29/2021
                   4691: # Typo in rev. 1.458 (2003/12/09)??
                   4692: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
                   4693: #
                   4694: # While these ramain as  $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
                   4695: # $dom and $name will always be null, so the &inc() call will default to storing this data
                   4696: # in a nohist_accesscount.db file for the user rather than the course.
                   4697: #
                   4698: # That said there is a lot of noise in the data being stored.
                   4699: # So counts for prtspool/  and adm/ etc. are recorded.
                   4700: #
                   4701: # A review of which items ending '___count' are written to %accesshash should likely be
                   4702: # made before deciding whether to set these to 'course.' instead of 'request.'
                   4703: #
                   4704: # Under the current scheme each user receives a nohist_accesscount.db file listing
                   4705: # accesses for things which are not published resources, regardless of course, and
                   4706: # there is not a nohist_accesscount.db file in a course, which might log accesses from
                   4707: # anyone in the course for things which are not published resources.
                   4708: #
                   4709: # For an author, nohist_accesscount.db ends up having records for other items
                   4710: # mixed up with the legitimate access counts for the author's published resources.
                   4711: #
1.620     albertel 4712:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4713:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4714:             }
1.450     matthew  4715:             my $value = $accesshash{$entry};
                   4716:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4717:             my %temphash=($url => $value);
1.449     matthew  4718:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4719:             if ($result eq 'ok') {
                   4720:                 delete $accesshash{$entry};
                   4721:             }
                   4722:         } else {
1.811     albertel 4723:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4724:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4725:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4726:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4727:                 delete $accesshash{$entry};
                   4728:             }
1.185     www      4729:         }
1.191     harris41 4730:     }
1.352     www      4731: #
                   4732: # Roles
                   4733: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4734: #
1.800     albertel 4735:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4736:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4737: 	    split(/\:/,$entry);
                   4738:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4739:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4740:                 $rudom,$runame) eq 'ok') {
                   4741: 	    delete $userrolehash{$entry};
                   4742:         }
                   4743:     }
1.662     raeburn  4744: #
1.1172.2.90  raeburn  4745: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4746: #
                   4747:     my %domrolebuffer = ();
1.1000    raeburn  4748:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4749:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4750:         if ($domrolebuffer{$rudom}) {
                   4751:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4752:                       '='.&escape($domainrolehash{$entry});
                   4753:         } else {
                   4754:             $domrolebuffer{$rudom}.=&escape($entry).
                   4755:                       '='.&escape($domainrolehash{$entry});
                   4756:         }
                   4757:         delete $domainrolehash{$entry};
                   4758:     }
                   4759:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4760:         my %servers;
                   4761:         if (defined(&domain($dom,'primary'))) {
                   4762:             my $primary=&domain($dom,'primary');
                   4763:             my $hostname=&hostname($primary);
                   4764:             $servers{$primary} = $hostname;
                   4765:         } else {
                   4766:             %servers = &get_servers($dom,'library');
                   4767:         }
1.841     albertel 4768: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4769: 	    if (&reply('domroleput:'.$dom.':'.
                   4770: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4771: 	        last;
                   4772: 	    } else {
1.841     albertel 4773: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4774: 	    }
1.662     raeburn  4775:         }
                   4776:     }
1.186     www      4777:     $dumpcount++;
1.157     www      4778: }
                   4779: 
                   4780: sub courselog {
                   4781:     my $what=shift;
1.158     www      4782:     $what=time.':'.$what;
1.620     albertel 4783:     unless ($env{'request.course.id'}) { return ''; }
                   4784:     $coursedombuf{$env{'request.course.id'}}=
                   4785:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4786:     $coursenumbuf{$env{'request.course.id'}}=
                   4787:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4788:     $coursehombuf{$env{'request.course.id'}}=
                   4789:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4790:     $coursedescrbuf{$env{'request.course.id'}}=
                   4791:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4792:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4793:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4794:     $courseownerbuf{$env{'request.course.id'}}=
                   4795:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4796:     $coursetypebuf{$env{'request.course.id'}}=
                   4797:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4798:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4799: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4800:     } else {
1.620     albertel 4801: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4802:     }
1.620     albertel 4803:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4804: 	&flushcourselogs();
                   4805:     }
1.158     www      4806: }
                   4807: 
                   4808: sub courseacclog {
                   4809:     my $fnsymb=shift;
1.620     albertel 4810:     unless ($env{'request.course.id'}) { return ''; }
                   4811:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4812:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4813:         $what.=':POST';
1.583     matthew  4814:         # FIXME: Probably ought to escape things....
1.800     albertel 4815: 	foreach my $key (keys(%env)) {
                   4816:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4817:                 my $formitem = $1;
                   4818:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4819:                     $what.=':'.$formitem.'='.$env{$key};
                   4820:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.131  raeburn  4821:                     if ($formitem eq 'proctorpassword') {
1.1172.2.132  raeburn  4822:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1172.2.131  raeburn  4823:                     } else {
                   4824:                         $what.=':'.$formitem.'='.$env{$key};
                   4825:                     }
1.975     raeburn  4826:                 }
1.158     www      4827:             }
1.191     harris41 4828:         }
1.583     matthew  4829:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4830:         # FIXME: We should not be depending on a form parameter that someone
                   4831:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4832:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4833:             $what.= ':POST';
                   4834:             # FIXME: Probably ought to escape things....
                   4835:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4836:                                  'crsdiscuss') {
1.620     albertel 4837:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4838:             }
                   4839:         }
1.158     www      4840:     }
                   4841:     &courselog($what);
1.149     www      4842: }
                   4843: 
1.185     www      4844: sub countacc {
                   4845:     my $url=&declutter(shift);
1.458     matthew  4846:     return if (! defined($url) || $url eq '');
1.620     albertel 4847:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4848: #
                   4849: # Mark that this url was used in this course
                   4850: #
1.620     albertel 4851:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4852: #
                   4853: # Increase the access count for this resource in this child process
                   4854: #
1.281     www      4855:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4856:     $accesshash{$key}++;
1.185     www      4857: }
1.349     www      4858: 
1.361     www      4859: sub linklog {
                   4860:     my ($from,$to)=@_;
                   4861:     $from=&declutter($from);
                   4862:     $to=&declutter($to);
                   4863:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4864:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4865: }
1.1160    www      4866: 
                   4867: sub statslog {
                   4868:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4869:     if ($users<2) { return; }
                   4870:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4871:             'course'       => $env{'request.course.id'},
                   4872:             'sections'     => '"all"',
                   4873:             'num_students' => $users,
                   4874:             'part'         => $part,
                   4875:             'symb'         => $symb,
                   4876:             'mean_tries'   => $av_attempts,
                   4877:             'deg_of_diff'  => $degdiff});
                   4878:     foreach my $key (keys(%dynstore)) {
                   4879:         $accesshash{$key}=$dynstore{$key};
                   4880:     }
                   4881: }
1.361     www      4882:   
1.349     www      4883: sub userrolelog {
                   4884:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4885:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4886:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4887:        $userrolehash
                   4888:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4889:                     =$tend.':'.$tstart;
1.662     raeburn  4890:     }
1.1169    droeschl 4891:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4892:        $userrolehash
                   4893:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4894:                     =$tend.':'.$tstart;
                   4895:     }
1.1172.2.90  raeburn  4896:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4897:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4898:        $domainrolehash
                   4899:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4900:                     = $tend.':'.$tstart;
                   4901:     }
1.351     www      4902: }
                   4903: 
1.957     raeburn  4904: sub courserolelog {
                   4905:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4906:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4907:         my $cdom = $1;
                   4908:         my $cnum = $2;
                   4909:         my $sec = $3;
                   4910:         my $namespace = 'rolelog';
                   4911:         my %storehash = (
                   4912:                            role    => $trole,
                   4913:                            start   => $tstart,
                   4914:                            end     => $tend,
                   4915:                            selfenroll => $selfenroll,
                   4916:                            context    => $context,
                   4917:                         );
                   4918:         if ($trole eq 'gr') {
                   4919:             $namespace = 'groupslog';
                   4920:             $storehash{'group'} = $sec;
                   4921:         } else {
                   4922:             $storehash{'section'} = $sec;
                   4923:         }
                   4924:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4925:                    $domain,$cnum,$cdom);
                   4926:         if (($trole ne 'st') || ($sec ne '')) {
                   4927:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4928:         }
                   4929:     }
                   4930:     return;
                   4931: }
                   4932: 
1.1172.2.9  raeburn  4933: sub domainrolelog {
                   4934:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4935:     if ($area =~ m{^/($match_domain)/$}) {
                   4936:         my $cdom = $1;
                   4937:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4938:         my $namespace = 'rolelog';
                   4939:         my %storehash = (
                   4940:                            role    => $trole,
                   4941:                            start   => $tstart,
                   4942:                            end     => $tend,
                   4943:                            context => $context,
                   4944:                         );
                   4945:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4946:                    $domain,$domconfiguser,$cdom);
                   4947:     }
                   4948:     return;
                   4949: 
                   4950: }
                   4951: 
                   4952: sub coauthorrolelog {
                   4953:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4954:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4955:         my $audom = $1;
                   4956:         my $auname = $2;
                   4957:         my $namespace = 'rolelog';
                   4958:         my %storehash = (
                   4959:                            role    => $trole,
                   4960:                            start   => $tstart,
                   4961:                            end     => $tend,
                   4962:                            context => $context,
                   4963:                         );
                   4964:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4965:                    $domain,$auname,$audom);
                   4966:     }
                   4967:     return;
                   4968: }
                   4969: 
1.351     www      4970: sub get_course_adv_roles {
1.948     raeburn  4971:     my ($cid,$codes) = @_;
1.620     albertel 4972:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4973:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4974:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4975:     my %nothide=();
1.800     albertel 4976:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4977:         if ($user !~ /:/) {
                   4978: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4979:         } else {
                   4980:             $nothide{$user}=1;
                   4981:         }
1.470     www      4982:     }
1.1172.2.23  raeburn  4983:     my @possdoms = ($coursehash{'domain'});
                   4984:     if ($coursehash{'checkforpriv'}) {
                   4985:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4986:     }
1.351     www      4987:     my %returnhash=();
                   4988:     my %dumphash=
                   4989:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4990:     my $now=time;
1.997     raeburn  4991:     my %privileged;
1.1000    raeburn  4992:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4993: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4994:         if (($tstart) && ($tstart<0)) { next; }
                   4995:         if (($tend) && ($tend<$now)) { next; }
                   4996:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4997:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4998: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  4999:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  5000:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 5001: 	if ($role eq 'cr') { next; }
1.948     raeburn  5002:         if ($codes) {
                   5003:             if ($section) { $role .= ':'.$section; }
                   5004:             if ($returnhash{$role}) {
                   5005:                 $returnhash{$role}.=','.$username.':'.$domain;
                   5006:             } else {
                   5007:                 $returnhash{$role}=$username.':'.$domain;
                   5008:             }
1.351     www      5009:         } else {
1.988     raeburn  5010:             my $key=&plaintext($role,$crstype);
1.973     bisitz   5011:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  5012:             if ($returnhash{$key}) {
                   5013: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   5014:             } else {
                   5015:                 $returnhash{$key}=$username.':'.$domain;
                   5016:             }
1.351     www      5017:         }
1.948     raeburn  5018:     }
1.400     www      5019:     return %returnhash;
                   5020: }
                   5021: 
                   5022: sub get_my_roles {
1.937     raeburn  5023:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 5024:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   5025:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  5026:     my (%dumphash,%nothide);
1.1086    raeburn  5027:     if ($context eq 'userroles') {
1.1166    raeburn  5028:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  5029:     } else {
1.1172.2.23  raeburn  5030:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  5031:         if ($hidepriv) {
                   5032:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   5033:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   5034:                 if ($user !~ /:/) {
                   5035:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   5036:                 } else {
                   5037:                     $nothide{$user} = 1;
                   5038:                 }
                   5039:             }
                   5040:         }
1.858     raeburn  5041:     }
1.400     www      5042:     my %returnhash=();
                   5043:     my $now=time;
1.999     raeburn  5044:     my %privileged;
1.800     albertel 5045:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  5046:         my ($role,$tend,$tstart);
                   5047:         if ($context eq 'userroles') {
1.1149    raeburn  5048:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  5049: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   5050:         } else {
                   5051:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   5052:         }
1.400     www      5053:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  5054:         my $status = 'active';
1.939     raeburn  5055:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  5056:             $status = 'previous';
                   5057:         } 
                   5058:         if (($tstart) && ($now<$tstart)) {
                   5059:             $status = 'future';
                   5060:         }
                   5061:         if (ref($types) eq 'ARRAY') {
                   5062:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   5063:                 next;
                   5064:             } 
                   5065:         } else {
                   5066:             if ($status ne 'active') {
                   5067:                 next;
                   5068:             }
                   5069:         }
1.867     raeburn  5070:         my ($rolecode,$username,$domain,$section,$area);
                   5071:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  5072:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5073:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5074:         } else {
                   5075:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5076:         }
1.832     raeburn  5077:         if (ref($roledoms) eq 'ARRAY') {
                   5078:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5079:                 next;
                   5080:             }
                   5081:         }
                   5082:         if (ref($roles) eq 'ARRAY') {
                   5083:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5084:                 if ($role =~ /^cr\//) {
                   5085:                     if (!grep(/^cr$/,@{$roles})) {
                   5086:                         next;
                   5087:                     }
1.1104    raeburn  5088:                 } elsif ($role =~ /^gr\//) {
                   5089:                     if (!grep(/^gr$/,@{$roles})) {
                   5090:                         next;
                   5091:                     }
1.922     raeburn  5092:                 } else {
                   5093:                     next;
                   5094:                 }
1.832     raeburn  5095:             }
1.867     raeburn  5096:         }
1.937     raeburn  5097:         if ($hidepriv) {
1.1172.2.23  raeburn  5098:             my @privroles = ('dc','su');
1.999     raeburn  5099:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  5100:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5101:             } else {
1.1172.2.23  raeburn  5102:                 my $possdoms = [$domain];
                   5103:                 if (ref($roledoms) eq 'ARRAY') {
                   5104:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  5105:                 }
1.1172.2.23  raeburn  5106:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5107:                     if (!$nothide{$username.':'.$domain}) {
                   5108:                         next;
                   5109:                     }
                   5110:                 }
1.937     raeburn  5111:             }
                   5112:         }
1.933     raeburn  5113:         if ($withsec) {
                   5114:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5115:                 $tstart.':'.$tend;
                   5116:         } else {
                   5117:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5118:         }
1.832     raeburn  5119:     }
1.373     www      5120:     return %returnhash;
1.399     www      5121: }
                   5122: 
1.1172.2.89  raeburn  5123: sub get_all_adhocroles {
                   5124:     my ($dom) = @_;
                   5125:     my @roles_by_num = ();
                   5126:     my %domdefaults = &get_domain_defaults($dom);
                   5127:     my (%description,%access_in_dom,%access_info);
                   5128:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5129:         my $count = 0;
                   5130:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5131:         my %ordered;
                   5132:         foreach my $role (sort(keys(%domcurrent))) {
                   5133:             my ($order,$desc,$access_in_dom);
                   5134:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5135:                 $order = $domcurrent{$role}{'order'};
                   5136:                 $desc = $domcurrent{$role}{'desc'};
                   5137:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5138:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5139:             }
                   5140:             if ($order eq '') {
                   5141:                 $order = $count;
                   5142:             }
                   5143:             $ordered{$order} = $role;
                   5144:             if ($desc ne '') {
                   5145:                 $description{$role} = $desc;
                   5146:             } else {
                   5147:                 $description{$role}= $role;
                   5148:             }
                   5149:             $count++;
                   5150:         }
                   5151:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5152:             push(@roles_by_num,$ordered{$item});
                   5153:         }
                   5154:     }
                   5155:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5156: }
                   5157: 
                   5158: sub get_my_adhocroles {
                   5159:     my ($cid,$checkreg) = @_;
                   5160:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5161:     if ($env{'request.course.id'} eq $cid) {
                   5162:         $cdom = $env{'course.'.$cid.'.domain'};
                   5163:         $cnum = $env{'course.'.$cid.'.num'};
                   5164:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5165:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5166:         $cdom = $1;
                   5167:         $cnum = $2;
                   5168:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5169:                                      $cdom,$cnum);
                   5170:     }
                   5171:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5172:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5173:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5174:         if ($rosterhash{$user} ne '') {
                   5175:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5176:             return ([],{}) if ($type eq 'auto');
                   5177:         }
                   5178:     }
                   5179:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5180:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5181:             my $then=$env{'user.login.time'};
                   5182:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5183:             if (!$update) {
                   5184:                 $update = $then;
                   5185:             }
                   5186:             my @liveroles;
                   5187:             foreach my $role ('dh','da') {
                   5188:                 if ($env{"user.role.$role./$cdom/"}) {
                   5189:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5190:                     my $limit = $update;
                   5191:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5192:                         $limit = $then;
                   5193:                     }
                   5194:                     my $activerole = 1;
                   5195:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5196:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5197:                     if ($activerole) {
                   5198:                         push(@liveroles,$role);
                   5199:                     }
                   5200:                 }
                   5201:             }
                   5202:             if (@liveroles) {
1.1172.2.89  raeburn  5203:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5204:                     my ($accessref,$accessinfo,%access_in_dom);
                   5205:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5206:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5207:                         if (@{$roles_by_num}) {
                   5208:                             my %settings;
                   5209:                             if ($env{'request.course.id'} eq $cid) {
                   5210:                                 foreach my $envkey (keys(%env)) {
                   5211:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5212:                                         $settings{$1} = $env{$envkey};
                   5213:                                     }
                   5214:                                 }
                   5215:                             } else {
                   5216:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5217:                             }
                   5218:                             my %setincrs;
                   5219:                             if ($settings{'internal.adhocaccess'}) {
                   5220:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5221:                             }
                   5222:                             my @statuses;
                   5223:                             if ($env{'environment.inststatus'}) {
                   5224:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5225:                             }
                   5226:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5227:                             if (ref($accessref) eq 'HASH') {
                   5228:                                 %access_in_dom = %{$accessref};
                   5229:                             }
                   5230:                             foreach my $role (@{$roles_by_num}) {
                   5231:                                 my ($curraccess,@okstatus,@personnel);
                   5232:                                 if ($setincrs{$role}) {
                   5233:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5234:                                     if ($curraccess eq 'status') {
                   5235:                                         @okstatus = split(/\&/,$rest);
                   5236:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5237:                                         @personnel = split(/\&/,$rest);
                   5238:                                     }
                   5239:                                 } else {
                   5240:                                     $curraccess = $access_in_dom{$role};
                   5241:                                     if (ref($accessinfo) eq 'HASH') {
                   5242:                                         if ($curraccess eq 'status') {
                   5243:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5244:                                                 @okstatus = @{$accessinfo->{$role}};
                   5245:                                             }
                   5246:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5247:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5248:                                                 @personnel = @{$accessinfo->{$role}};
                   5249:                                             }
                   5250:                                         }
                   5251:                                     }
                   5252:                                 }
                   5253:                                 if ($curraccess eq 'none') {
                   5254:                                     next;
                   5255:                                 } elsif ($curraccess eq 'all') {
                   5256:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5257:                                 } elsif ($curraccess eq 'dh') {
                   5258:                                     if (grep(/^dh$/,@liveroles)) {
                   5259:                                         push(@possroles,$role);
                   5260:                                     } else {
                   5261:                                         next;
                   5262:                                     }
                   5263:                                 } elsif ($curraccess eq 'da') {
                   5264:                                     if (grep(/^da$/,@liveroles)) {
                   5265:                                         push(@possroles,$role);
                   5266:                                     } else {
                   5267:                                         next;
                   5268:                                     }
1.1172.2.89  raeburn  5269:                                 } elsif ($curraccess eq 'status') {
                   5270:                                     if (@okstatus) {
                   5271:                                         if (!@statuses) {
                   5272:                                             if (grep(/^default$/,@okstatus)) {
                   5273:                                                 push(@possroles,$role);
                   5274:                                             }
                   5275:                                         } else {
                   5276:                                             foreach my $status (@okstatus) {
                   5277:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5278:                                                     push(@possroles,$role);
                   5279:                                                     last;
                   5280:                                                 }
                   5281:                                             }
                   5282:                                         }
                   5283:                                     }
                   5284:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5285:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5286:                                         if ($curraccess eq 'exc') {
                   5287:                                             push(@possroles,$role);
                   5288:                                         }
                   5289:                                     } elsif ($curraccess eq 'inc') {
                   5290:                                         push(@possroles,$role);
                   5291:                                     }
                   5292:                                 }
                   5293:                             }
                   5294:                         }
                   5295:                     }
                   5296:                 }
                   5297:             }
                   5298:         }
                   5299:     }
                   5300:     unless (ref($description) eq 'HASH') {
                   5301:         if (ref($roles_by_num) eq 'ARRAY') {
                   5302:             my %desc;
                   5303:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5304:             $description = \%desc;
                   5305:         } else {
                   5306:             $description = {};
                   5307:         }
                   5308:     }
                   5309:     return (\@possroles,$description);
                   5310: }
                   5311: 
1.399     www      5312: # ----------------------------------------------------- Frontpage Announcements
                   5313: #
                   5314: #
                   5315: 
                   5316: sub postannounce {
                   5317:     my ($server,$text)=@_;
1.844     albertel 5318:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5319:     unless ($text=~/\w/) { $text=''; }
                   5320:     return &reply('setannounce:'.&escape($text),$server);
                   5321: }
                   5322: 
                   5323: sub getannounce {
1.448     albertel 5324: 
1.1172.2.96  raeburn  5325:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5326: 	my $announcement='';
1.800     albertel 5327: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5328: 	close($fh);
1.399     www      5329: 	if ($announcement=~/\w/) { 
                   5330: 	    return 
                   5331:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5332:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5333: 	} else {
                   5334: 	    return '';
                   5335: 	}
                   5336:     } else {
                   5337: 	return '';
                   5338:     }
1.351     www      5339: }
1.353     www      5340: 
                   5341: # ---------------------------------------------------------- Course ID routines
                   5342: # Deal with domain's nohist_courseid.db files
                   5343: #
                   5344: 
                   5345: sub courseidput {
1.921     raeburn  5346:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5347:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5348:     my $outcome;
                   5349:     if ($caller eq 'timeonly') {
                   5350:         my $cids = '';
                   5351:         foreach my $item (keys(%$storehash)) {
                   5352:             $cids.=&escape($item).'&';
                   5353:         }
                   5354:         $cids=~s/\&$//;
                   5355:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5356:                           $coursehome);       
                   5357:     } else {
                   5358:         my $items = '';
                   5359:         foreach my $item (keys(%$storehash)) {
                   5360:             $items.= &escape($item).'='.
                   5361:                      &freeze_escape($$storehash{$item}).'&';
                   5362:         }
                   5363:         $items=~s/\&$//;
                   5364:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5365:                           $coursehome);
1.918     raeburn  5366:     }
                   5367:     if ($outcome eq 'unknown_cmd') {
                   5368:         my $what;
                   5369:         foreach my $cid (keys(%$storehash)) {
                   5370:             $what .= &escape($cid).'=';
1.921     raeburn  5371:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5372:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5373:             }
                   5374:             $what =~ s/\:$/&/;
                   5375:         }
                   5376:         $what =~ s/\&$//;  
                   5377:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5378:     } else {
                   5379:         return $outcome;
                   5380:     }
1.353     www      5381: }
                   5382: 
                   5383: sub courseiddump {
1.921     raeburn  5384:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5385:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5386:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5387:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5388:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5389:     my $as_hash = 1;
                   5390:     my %returnhash;
                   5391:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5392:     my %libserv = &all_library();
                   5393:     foreach my $tryserver (keys(%libserv)) {
                   5394:         if ( (  $hostidflag == 1 
                   5395: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5396: 	     || (!defined($hostidflag)) ) {
                   5397: 
1.918     raeburn  5398: 	    if (($domfilter eq '') ||
                   5399: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5400:                 my $rep;
                   5401:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5402:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5403:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5404:                                 &escape($descfilter), &escape($instcodefilter),
                   5405:                                 &escape($ownerfilter), &escape($coursefilter),
                   5406:                                 &escape($typefilter), &escape($regexp_ok),
                   5407:                                 $as_hash, &escape($selfenrollonly),
                   5408:                                 &escape($catfilter), $showhidden, $caller,
                   5409:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5410:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5411:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5412:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5413:                 } else {
                   5414:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5415:                              $sincefilter.':'.&escape($descfilter).':'.
                   5416:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5417:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5418:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5419:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5420:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5421:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5422:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5423:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5424:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5425:                 }
                   5426: 
1.918     raeburn  5427:                 my @pairs=split(/\&/,$rep);
                   5428:                 foreach my $item (@pairs) {
                   5429:                     my ($key,$value)=split(/\=/,$item,2);
                   5430:                     $key = &unescape($key);
                   5431:                     next if ($key =~ /^error: 2 /);
                   5432:                     my $result = &thaw_unescape($value);
                   5433:                     if (ref($result) eq 'HASH') {
                   5434:                         $returnhash{$key}=$result;
                   5435:                     } else {
1.921     raeburn  5436:                         my @responses = split(/:/,$value);
                   5437:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5438:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5439:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5440:                         }
1.1008    raeburn  5441:                     }
1.353     www      5442:                 }
                   5443:             }
                   5444:         }
                   5445:     }
                   5446:     return %returnhash;
                   5447: }
                   5448: 
1.1055    raeburn  5449: sub courselastaccess {
                   5450:     my ($cdom,$cnum,$hostidref) = @_;
                   5451:     my %returnhash;
                   5452:     if ($cdom && $cnum) {
                   5453:         my $chome = &homeserver($cnum,$cdom);
                   5454:         if ($chome ne 'no_host') {
                   5455:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5456:             &extract_lastaccess(\%returnhash,$rep);
                   5457:         }
                   5458:     } else {
                   5459:         if (!$cdom) { $cdom=''; }
                   5460:         my %libserv = &all_library();
                   5461:         foreach my $tryserver (keys(%libserv)) {
                   5462:             if (ref($hostidref) eq 'ARRAY') {
                   5463:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5464:             } 
                   5465:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5466:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5467:                 &extract_lastaccess(\%returnhash,$rep);
                   5468:             }
                   5469:         }
                   5470:     }
                   5471:     return %returnhash;
                   5472: }
                   5473: 
                   5474: sub extract_lastaccess {
                   5475:     my ($returnhash,$rep) = @_;
                   5476:     if (ref($returnhash) eq 'HASH') {
                   5477:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5478:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5479:                  $rep eq '') {
                   5480:             my @pairs=split(/\&/,$rep);
                   5481:             foreach my $item (@pairs) {
                   5482:                 my ($key,$value)=split(/\=/,$item,2);
                   5483:                 $key = &unescape($key);
                   5484:                 next if ($key =~ /^error: 2 /);
                   5485:                 $returnhash->{$key} = &thaw_unescape($value);
                   5486:             }
                   5487:         }
                   5488:     }
                   5489:     return;
                   5490: }
                   5491: 
1.658     raeburn  5492: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5493: 
                   5494: sub dcmailput {
1.685     raeburn  5495:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5496:     my $status = &Apache::lonnet::critical(
1.740     www      5497:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5498:        &escape($message),$server);
1.662     raeburn  5499:     return $status;
                   5500: }
                   5501: 
1.658     raeburn  5502: sub dcmaildump {
                   5503:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5504:     my %returnhash=();
1.846     albertel 5505: 
                   5506:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5507:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5508:                                                          &escape($enddate).':';
                   5509: 	my @esc_senders=map { &escape($_)} @$senders;
                   5510: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5511: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5512:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5513:             if (($key) && ($value)) {
                   5514:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5515:             }
                   5516:         }
                   5517:     }
                   5518:     return %returnhash;
                   5519: }
1.662     raeburn  5520: # ---------------------------------------------------------- Domain roles
                   5521: 
                   5522: sub get_domain_roles {
                   5523:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5524:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5525:         $startdate = '.';
                   5526:     }
1.1018    raeburn  5527:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5528:         $enddate = '.';
                   5529:     }
1.922     raeburn  5530:     my $rolelist;
                   5531:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5532:         $rolelist = join('&',@{$roles});
1.922     raeburn  5533:     }
1.662     raeburn  5534:     my %personnel = ();
1.841     albertel 5535: 
                   5536:     my %servers = &get_servers($dom,'library');
                   5537:     foreach my $tryserver (keys(%servers)) {
                   5538: 	%{$personnel{$tryserver}}=();
                   5539: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5540: 					    &escape($startdate).':'.
                   5541: 					    &escape($enddate).':'.
                   5542: 					    &escape($rolelist), $tryserver))) {
                   5543: 	    my ($key,$value) = split(/\=/,$line,2);
                   5544: 	    if (($key) && ($value)) {
                   5545: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5546: 	    }
                   5547: 	}
1.662     raeburn  5548:     }
                   5549:     return %personnel;
                   5550: }
1.658     raeburn  5551: 
1.1172.2.89  raeburn  5552: sub get_active_domroles {
                   5553:     my ($dom,$roles) = @_;
                   5554:     return () unless (ref($roles) eq 'ARRAY');
                   5555:     my $now = time;
                   5556:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5557:     my %domroles;
                   5558:     foreach my $server (keys(%dompersonnel)) {
                   5559:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5560:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5561:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5562:         }
                   5563:     }
                   5564:     return %domroles;
                   5565: }
                   5566: 
1.1057    www      5567: # ----------------------------------------------------------- Interval timing 
1.149     www      5568: 
1.1153    www      5569: {
                   5570: # Caches needed for speedup of navmaps
                   5571: # We don't want to cache this for very long at all (5 seconds at most)
                   5572: # 
                   5573: # The user for whom we cache
                   5574: my $cachedkey='';
                   5575: # The cached times for this user
                   5576: my %cachedtimes=();
                   5577: # When this was last done
1.1172.2.66  raeburn  5578: my $cachedtime='';
1.1153    www      5579: 
                   5580: sub load_all_first_access {
1.1172.2.146.  .1(raebu 5581:22):     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5582:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.146.  .1(raebu 5583:22):         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5584:22):         (!$ignorecache)) {
1.1154    raeburn  5585:         return;
                   5586:     }
                   5587:     $cachedtime=time;
                   5588:     $cachedkey=$uname.':'.$udom;
                   5589:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5590: }
                   5591: 
1.504     albertel 5592: sub get_first_access {
1.1172.2.146.  .1(raebu 5593:22):     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5594:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5595:     if ($argsymb) { $symb=$argsymb; }
                   5596:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5597:     if ($argmap) { $map = $argmap; }
1.926     albertel 5598:     if ($type eq 'course') {
                   5599: 	$res='course';
                   5600:     } elsif ($type eq 'map') {
1.588     albertel 5601: 	$res=&symbread($map);
                   5602:     } else {
                   5603: 	$res=$symb;
                   5604:     }
1.1172.2.146.  .1(raebu 5605:22):     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5606:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5607: }
                   5608: 
                   5609: sub set_first_access {
1.1162    raeburn  5610:     my ($type,$interval)=@_;
1.790     albertel 5611:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5612:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5613:     if ($type eq 'course') {
                   5614: 	$res='course';
                   5615:     } elsif ($type eq 'map') {
1.588     albertel 5616: 	$res=&symbread($map);
                   5617:     } else {
                   5618: 	$res=$symb;
                   5619:     }
1.1153    www      5620:     $cachedkey='';
1.1162    raeburn  5621:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5622:     if ($firstaccess) {
                   5623:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5624:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5625:                  "in $courseid");
                   5626:         return 'already_set';
                   5627:     } else {
1.1162    raeburn  5628:         my $start = time;
                   5629: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5630:                           $udom,$uname);
                   5631:         if ($putres eq 'ok') {
                   5632:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5633:                  $udom,$uname); 
                   5634:             &appenv(
                   5635:                      {
                   5636:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5637:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5638:                      }
                   5639:                   );
1.1172.2.97  raeburn  5640:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5641:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5642:             }
1.1172.2.102  raeburn  5643:         } elsif ($putres ne 'refused') {
                   5644:             &logthis("Result: $putres when attempting to set first access time ".
                   5645:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5646:         }
                   5647:         return $putres;
1.505     albertel 5648:     }
                   5649:     return 'already_set';
1.504     albertel 5650: }
1.1153    www      5651: }
1.1172.2.32  raeburn  5652: 
                   5653: sub checkout {
                   5654:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5655:     my $now=time;
                   5656:     my $lonhost=$perlvar{'lonHostID'};
1.1172.2.134  raeburn  5657:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5658:     my $infostr=&escape(
                   5659:                  'CHECKOUTTOKEN&'.
                   5660:                  $tuname.'&'.
                   5661:                  $tudom.'&'.
                   5662:                  $tcrsid.'&'.
                   5663:                  $symb.'&'.
1.1172.2.134  raeburn  5664:                  $now.'&'.$ip);
1.1172.2.32  raeburn  5665:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5666:     if ($token=~/^error\:/) {
                   5667:         &logthis("<font color=\"blue\">WARNING: ".
                   5668:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5669:                  "</font>");
                   5670:         return '';
                   5671:     }
                   5672: 
                   5673:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5674:     $token=~tr/a-z/A-Z/;
                   5675: 
                   5676:     my %infohash=('resource.0.outtoken' => $token,
                   5677:                   'resource.0.checkouttime' => $now,
1.1172.2.134  raeburn  5678:                   'resource.0.outremote' => $ip);
1.1172.2.32  raeburn  5679: 
                   5680:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5681:        return '';
                   5682:     } else {
                   5683:         &logthis("<font color=\"blue\">WARNING: ".
                   5684:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5685:                  "</font>");
                   5686:     }
                   5687: 
                   5688:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5689:                          &escape('Checkout '.$infostr.' - '.
                   5690:                                                  $token)) ne 'ok') {
                   5691:         return '';
                   5692:     } else {
                   5693:         &logthis("<font color=\"blue\">WARNING: ".
                   5694:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5695:                  "</font>");
                   5696:     }
                   5697:     return $token;
                   5698: }
                   5699: 
                   5700: # ------------------------------------------------------------ Check in an item
                   5701: 
                   5702: sub checkin {
                   5703:     my $token=shift;
                   5704:     my $now=time;
                   5705:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5706:     $lonhost=~tr/A-Z/a-z/;
                   5707:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5708:     $dtoken=~s/\W/\_/g;
1.1172.2.134  raeburn  5709:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5710:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5711:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5712: 
                   5713:     unless (($tuname) && ($tudom)) {
                   5714:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5715:         return '';
                   5716:     }
                   5717: 
                   5718:     unless (&allowed('mgr',$tcrsid)) {
                   5719:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5720:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5721:         return '';
                   5722:     }
                   5723: 
                   5724:     my %infohash=('resource.0.intoken' => $token,
                   5725:                   'resource.0.checkintime' => $now,
1.1172.2.134  raeburn  5726:                   'resource.0.inremote' => $ip);
1.1172.2.32  raeburn  5727: 
                   5728:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5729:        return '';
                   5730:     }
                   5731: 
                   5732:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5733:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5734:         return '';
                   5735:     }
                   5736: 
                   5737:     return ($symb,$tuname,$tudom,$tcrsid);
                   5738: }
                   5739: 
1.110     www      5740: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5741: 
                   5742: sub expirespread {
                   5743:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5744:     my $cid=$env{'request.course.id'}; 
1.110     www      5745:     if ($cid) {
                   5746:        my $now=time;
                   5747:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5748:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5749:                             $env{'course.'.$cid.'.num'}.
1.110     www      5750: 	        	    ':nohist_expirationdates:'.
                   5751:                             &escape($key).'='.$now,
1.620     albertel 5752:                             $env{'course.'.$cid.'.home'})
1.110     www      5753:     }
                   5754:     return 'ok';
1.14      www      5755: }
                   5756: 
1.109     www      5757: # ----------------------------------------------------- Devalidate Spreadsheets
                   5758: 
                   5759: sub devalidate {
1.325     www      5760:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5761:     my $cid=$env{'request.course.id'}; 
1.109     www      5762:     if ($cid) {
1.391     matthew  5763:         # delete the stored spreadsheets for
                   5764:         # - the student level sheet of this user in course's homespace
                   5765:         # - the assessment level sheet for this resource 
                   5766:         #   for this user in user's homespace
1.553     albertel 5767: 	# - current conditional state info
1.325     www      5768: 	my $key=$uname.':'.$udom.':';
1.109     www      5769:         my $status=
1.299     matthew  5770: 	    &del('nohist_calculatedsheets',
1.391     matthew  5771: 		 [$key.'studentcalc:'],
1.620     albertel 5772: 		 $env{'course.'.$cid.'.domain'},
                   5773: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5774: 		.' '.
                   5775: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5776: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5777:         unless ($status eq 'ok ok') {
                   5778:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5779:                     $uname.' at '.$udom.' for '.
1.109     www      5780: 		    $symb.': '.$status);
1.133     albertel 5781:         }
1.553     albertel 5782: 	&delenv('user.state.'.$cid);
1.109     www      5783:     }
                   5784: }
                   5785: 
1.265     albertel 5786: sub get_scalar {
                   5787:     my ($string,$end) = @_;
                   5788:     my $value;
                   5789:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5790: 	$value = $1;
                   5791:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5792: 	$value = $1;
                   5793:     }
                   5794:     return &unescape($value);
                   5795: }
                   5796: 
                   5797: sub array2str {
                   5798:   my (@array) = @_;
                   5799:   my $result=&arrayref2str(\@array);
                   5800:   $result=~s/^__ARRAY_REF__//;
                   5801:   $result=~s/__END_ARRAY_REF__$//;
                   5802:   return $result;
                   5803: }
                   5804: 
1.204     albertel 5805: sub arrayref2str {
                   5806:   my ($arrayref) = @_;
1.265     albertel 5807:   my $result='__ARRAY_REF__';
1.204     albertel 5808:   foreach my $elem (@$arrayref) {
1.265     albertel 5809:     if(ref($elem) eq 'ARRAY') {
                   5810:       $result.=&arrayref2str($elem).'&';
                   5811:     } elsif(ref($elem) eq 'HASH') {
                   5812:       $result.=&hashref2str($elem).'&';
                   5813:     } elsif(ref($elem)) {
                   5814:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5815:     } else {
                   5816:       $result.=&escape($elem).'&';
                   5817:     }
                   5818:   }
                   5819:   $result=~s/\&$//;
1.265     albertel 5820:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5821:   return $result;
                   5822: }
                   5823: 
1.168     albertel 5824: sub hash2str {
1.204     albertel 5825:   my (%hash) = @_;
                   5826:   my $result=&hashref2str(\%hash);
1.265     albertel 5827:   $result=~s/^__HASH_REF__//;
                   5828:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5829:   return $result;
                   5830: }
                   5831: 
                   5832: sub hashref2str {
                   5833:   my ($hashref)=@_;
1.265     albertel 5834:   my $result='__HASH_REF__';
1.800     albertel 5835:   foreach my $key (sort(keys(%$hashref))) {
                   5836:     if (ref($key) eq 'ARRAY') {
                   5837:       $result.=&arrayref2str($key).'=';
                   5838:     } elsif (ref($key) eq 'HASH') {
                   5839:       $result.=&hashref2str($key).'=';
                   5840:     } elsif (ref($key)) {
1.265     albertel 5841:       $result.='=';
1.800     albertel 5842:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5843:     } else {
1.1132    raeburn  5844: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5845:     }
                   5846: 
1.800     albertel 5847:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5848:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5849:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5850:       $result.=&hashref2str($hashref->{$key}).'&';
                   5851:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5852:        $result.='&';
1.800     albertel 5853:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5854:     } else {
1.800     albertel 5855:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5856:     }
                   5857:   }
1.168     albertel 5858:   $result=~s/\&$//;
1.265     albertel 5859:   $result .= '__END_HASH_REF__';
1.168     albertel 5860:   return $result;
                   5861: }
                   5862: 
                   5863: sub str2hash {
1.265     albertel 5864:     my ($string)=@_;
                   5865:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5866:     return %$hash;
                   5867: }
                   5868: 
                   5869: sub str2hashref {
1.168     albertel 5870:   my ($string) = @_;
1.265     albertel 5871: 
                   5872:   my %hash;
                   5873: 
                   5874:   if($string !~ /^__HASH_REF__/) {
                   5875:       if (! ($string eq '' || !defined($string))) {
                   5876: 	  $hash{'error'}='Not hash reference';
                   5877:       }
                   5878:       return (\%hash, $string);
                   5879:   }
                   5880: 
                   5881:   $string =~ s/^__HASH_REF__//;
                   5882: 
                   5883:   while($string !~ /^__END_HASH_REF__/) {
                   5884:       #key
                   5885:       my $key='';
                   5886:       if($string =~ /^__HASH_REF__/) {
                   5887:           ($key, $string)=&str2hashref($string);
                   5888:           if(defined($key->{'error'})) {
                   5889:               $hash{'error'}='Bad data';
                   5890:               return (\%hash, $string);
                   5891:           }
                   5892:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5893:           ($key, $string)=&str2arrayref($string);
                   5894:           if($key->[0] eq 'Array reference error') {
                   5895:               $hash{'error'}='Bad data';
                   5896:               return (\%hash, $string);
                   5897:           }
                   5898:       } else {
                   5899:           $string =~ s/^(.*?)=//;
1.267     albertel 5900: 	  $key=&unescape($1);
1.265     albertel 5901:       }
                   5902:       $string =~ s/^=//;
                   5903: 
                   5904:       #value
                   5905:       my $value='';
                   5906:       if($string =~ /^__HASH_REF__/) {
                   5907:           ($value, $string)=&str2hashref($string);
                   5908:           if(defined($value->{'error'})) {
                   5909:               $hash{'error'}='Bad data';
                   5910:               return (\%hash, $string);
                   5911:           }
                   5912:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5913:           ($value, $string)=&str2arrayref($string);
                   5914:           if($value->[0] eq 'Array reference error') {
                   5915:               $hash{'error'}='Bad data';
                   5916:               return (\%hash, $string);
                   5917:           }
                   5918:       } else {
                   5919: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5920:       }
                   5921:       $string =~ s/^&//;
                   5922: 
                   5923:       $hash{$key}=$value;
1.204     albertel 5924:   }
1.265     albertel 5925: 
                   5926:   $string =~ s/^__END_HASH_REF__//;
                   5927: 
                   5928:   return (\%hash, $string);
1.204     albertel 5929: }
                   5930: 
                   5931: sub str2array {
1.265     albertel 5932:     my ($string)=@_;
                   5933:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5934:     return @$array;
                   5935: }
                   5936: 
                   5937: sub str2arrayref {
1.204     albertel 5938:   my ($string) = @_;
1.265     albertel 5939:   my @array;
                   5940: 
                   5941:   if($string !~ /^__ARRAY_REF__/) {
                   5942:       if (! ($string eq '' || !defined($string))) {
                   5943: 	  $array[0]='Array reference error';
                   5944:       }
                   5945:       return (\@array, $string);
                   5946:   }
                   5947: 
                   5948:   $string =~ s/^__ARRAY_REF__//;
                   5949: 
                   5950:   while($string !~ /^__END_ARRAY_REF__/) {
                   5951:       my $value='';
                   5952:       if($string =~ /^__HASH_REF__/) {
                   5953:           ($value, $string)=&str2hashref($string);
                   5954:           if(defined($value->{'error'})) {
                   5955:               $array[0] ='Array reference error';
                   5956:               return (\@array, $string);
                   5957:           }
                   5958:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5959:           ($value, $string)=&str2arrayref($string);
                   5960:           if($value->[0] eq 'Array reference error') {
                   5961:               $array[0] ='Array reference error';
                   5962:               return (\@array, $string);
                   5963:           }
                   5964:       } else {
                   5965: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5966:       }
                   5967:       $string =~ s/^&//;
                   5968: 
                   5969:       push(@array, $value);
1.191     harris41 5970:   }
1.265     albertel 5971: 
                   5972:   $string =~ s/^__END_ARRAY_REF__//;
                   5973: 
                   5974:   return (\@array, $string);
1.168     albertel 5975: }
                   5976: 
1.167     albertel 5977: # -------------------------------------------------------------------Temp Store
                   5978: 
1.168     albertel 5979: sub tmpreset {
                   5980:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5981:   if (!$symb) {
                   5982:     $symb=&symbread();
1.620     albertel 5983:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5984:   }
                   5985:   $symb=escape($symb);
                   5986: 
1.620     albertel 5987:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5988:   $namespace=~s/\//\_/g;
                   5989:   $namespace=~s/\W//g;
                   5990: 
1.620     albertel 5991:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5992:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5993:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  5994:       $stuname=&get_requestor_ip();
1.591     albertel 5995:   }
1.1117    foxr     5996:   my $path=LONCAPA::tempdir();
1.168     albertel 5997:   my %hash;
                   5998:   if (tie(%hash,'GDBM_File',
                   5999: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6000: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  6001:     foreach my $key (keys(%hash)) {
1.180     albertel 6002:       if ($key=~ /:$symb/) {
1.168     albertel 6003: 	delete($hash{$key});
                   6004:       }
                   6005:     }
                   6006:   }
                   6007: }
                   6008: 
1.167     albertel 6009: sub tmpstore {
1.168     albertel 6010:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   6011: 
                   6012:   if (!$symb) {
                   6013:     $symb=&symbread();
1.620     albertel 6014:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6015:   }
                   6016:   $symb=escape($symb);
                   6017: 
                   6018:   if (!$namespace) {
                   6019:     # I don't think we would ever want to store this for a course.
                   6020:     # it seems this will only be used if we don't have a course.
1.620     albertel 6021:     #$namespace=$env{'request.course.id'};
1.168     albertel 6022:     #if (!$namespace) {
1.620     albertel 6023:       $namespace=$env{'request.state'};
1.168     albertel 6024:     #}
                   6025:   }
                   6026:   $namespace=~s/\//\_/g;
                   6027:   $namespace=~s/\W//g;
1.620     albertel 6028:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6029:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6030:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6031:       $stuname=&get_requestor_ip();
1.591     albertel 6032:   }
1.168     albertel 6033:   my $now=time;
                   6034:   my %hash;
1.1117    foxr     6035:   my $path=LONCAPA::tempdir();
1.168     albertel 6036:   if (tie(%hash,'GDBM_File',
                   6037: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6038: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 6039:     $hash{"version:$symb"}++;
                   6040:     my $version=$hash{"version:$symb"};
                   6041:     my $allkeys=''; 
                   6042:     foreach my $key (keys(%$storehash)) {
                   6043:       $allkeys.=$key.':';
1.591     albertel 6044:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 6045:     }
                   6046:     $hash{"$version:$symb:timestamp"}=$now;
                   6047:     $allkeys.='timestamp';
                   6048:     $hash{"$version:keys:$symb"}=$allkeys;
                   6049:     if (untie(%hash)) {
                   6050:       return 'ok';
                   6051:     } else {
                   6052:       return "error:$!";
                   6053:     }
                   6054:   } else {
                   6055:     return "error:$!";
                   6056:   }
                   6057: }
1.167     albertel 6058: 
1.168     albertel 6059: # -----------------------------------------------------------------Temp Restore
1.167     albertel 6060: 
1.168     albertel 6061: sub tmprestore {
                   6062:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 6063: 
1.168     albertel 6064:   if (!$symb) {
                   6065:     $symb=&symbread();
1.620     albertel 6066:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6067:   }
                   6068:   $symb=escape($symb);
                   6069: 
1.620     albertel 6070:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 6071: 
1.620     albertel 6072:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6073:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6074:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6075:       $stuname=&get_requestor_ip();
1.591     albertel 6076:   }
1.168     albertel 6077:   my %returnhash;
                   6078:   $namespace=~s/\//\_/g;
                   6079:   $namespace=~s/\W//g;
                   6080:   my %hash;
1.1117    foxr     6081:   my $path=LONCAPA::tempdir();
1.168     albertel 6082:   if (tie(%hash,'GDBM_File',
                   6083: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6084: 	  &GDBM_READER(),0640)) {
1.168     albertel 6085:     my $version=$hash{"version:$symb"};
                   6086:     $returnhash{'version'}=$version;
                   6087:     my $scope;
                   6088:     for ($scope=1;$scope<=$version;$scope++) {
                   6089:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6090:       my @keys=split(/:/,$vkeys);
                   6091:       my $key;
                   6092:       $returnhash{"$scope:keys"}=$vkeys;
                   6093:       foreach $key (@keys) {
1.591     albertel 6094: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6095: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6096:       }
                   6097:     }
1.168     albertel 6098:     if (!(untie(%hash))) {
                   6099:       return "error:$!";
                   6100:     }
                   6101:   } else {
                   6102:     return "error:$!";
                   6103:   }
                   6104:   return %returnhash;
1.167     albertel 6105: }
                   6106: 
1.9       www      6107: # ----------------------------------------------------------------------- Store
                   6108: 
                   6109: sub store {
1.1172.2.64  raeburn  6110:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6111:     my $home='';
                   6112: 
1.168     albertel 6113:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6114: 
1.213     www      6115:     $symb=&symbclean($symb);
1.122     albertel 6116:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6117: 
1.620     albertel 6118:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6119:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6120: 
                   6121:     &devalidate($symb,$stuname,$domain);
1.109     www      6122: 
                   6123:     $symb=escape($symb);
1.187     www      6124:     if (!$namespace) { 
1.620     albertel 6125:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6126:           return ''; 
                   6127:        } 
                   6128:     }
1.620     albertel 6129:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6130: 
1.1172.2.138  raeburn  6131:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6132:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6133: 
1.12      www      6134:     my $namevalue='';
1.800     albertel 6135:     foreach my $key (keys(%$storehash)) {
                   6136:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6137:     }
1.12      www      6138:     $namevalue=~s/\&$//;
1.187     www      6139:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  6140:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6141: }
                   6142: 
1.47      www      6143: # -------------------------------------------------------------- Critical Store
                   6144: 
                   6145: sub cstore {
1.1172.2.64  raeburn  6146:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6147:     my $home='';
                   6148: 
1.168     albertel 6149:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6150: 
1.213     www      6151:     $symb=&symbclean($symb);
1.122     albertel 6152:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6153: 
1.620     albertel 6154:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6155:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6156: 
                   6157:     &devalidate($symb,$stuname,$domain);
1.109     www      6158: 
                   6159:     $symb=escape($symb);
1.187     www      6160:     if (!$namespace) { 
1.620     albertel 6161:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6162:           return ''; 
                   6163:        } 
                   6164:     }
1.620     albertel 6165:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6166: 
1.1172.2.138  raeburn  6167:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6168:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6169: 
1.47      www      6170:     my $namevalue='';
1.800     albertel 6171:     foreach my $key (keys(%$storehash)) {
                   6172:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6173:     }
1.47      www      6174:     $namevalue=~s/\&$//;
1.187     www      6175:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6176:     return critical
1.1172.2.64  raeburn  6177:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6178: }
                   6179: 
1.9       www      6180: # --------------------------------------------------------------------- Restore
                   6181: 
                   6182: sub restore {
1.124     www      6183:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6184:     my $home='';
                   6185: 
1.168     albertel 6186:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6187: 
1.122     albertel 6188:     if (!$symb) {
1.1172.2.26  raeburn  6189:         return if ($namespace eq 'courserequests');
                   6190:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6191:     } else {
1.1172.2.26  raeburn  6192:         unless ($namespace eq 'courserequests') {
                   6193:             $symb=&escape(&symbclean($symb));
                   6194:         }
1.122     albertel 6195:     }
1.188     www      6196:     if (!$namespace) { 
1.620     albertel 6197:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6198:           return ''; 
                   6199:        } 
                   6200:     }
1.620     albertel 6201:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6202:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6203:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6204:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6205: 
1.12      www      6206:     my %returnhash=();
1.800     albertel 6207:     foreach my $line (split(/\&/,$answer)) {
                   6208: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6209:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6210:     }
1.75      www      6211:     my $version;
                   6212:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6213:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6214:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6215:        }
1.75      www      6216:     }
1.13      www      6217:     return %returnhash;
1.34      www      6218: }
                   6219: 
                   6220: # ---------------------------------------------------------- Course Description
1.1118    foxr     6221: #
                   6222: #  
1.34      www      6223: 
                   6224: sub coursedescription {
1.731     albertel 6225:     my ($courseid,$args)=@_;
1.34      www      6226:     $courseid=~s/^\///;
1.49      www      6227:     $courseid=~s/\_/\//g;
1.34      www      6228:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6229:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6230:     my $normalid=$cdomain.'_'.$cnum;
                   6231:     # need to always cache even if we get errors otherwise we keep 
                   6232:     # trying and trying and trying to get the course description.
                   6233:     my %envhash=();
                   6234:     my %returnhash=();
1.731     albertel 6235:     
                   6236:     my $expiretime=600;
                   6237:     if ($env{'request.course.id'} eq $normalid) {
                   6238: 	$expiretime=120;
                   6239:     }
                   6240: 
                   6241:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6242:     if (!$args->{'freshen_cache'}
                   6243: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6244: 	foreach my $key (keys(%env)) {
                   6245: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6246: 	    my ($setting) = $1;
                   6247: 	    $returnhash{$setting} = $env{$key};
                   6248: 	}
                   6249: 	return %returnhash;
                   6250:     }
                   6251: 
1.1118    foxr     6252:     # get the data again
                   6253: 
1.731     albertel 6254:     if (!$args->{'one_time'}) {
                   6255: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6256:     }
1.811     albertel 6257: 
1.34      www      6258:     if ($chome ne 'no_host') {
1.302     albertel 6259:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6260:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6261: 	   my $username = $env{'user.name'}; # Defult username
                   6262: 	   if(defined $args->{'user'}) {
                   6263: 	       $username = $args->{'user'};
                   6264: 	   }
1.129     albertel 6265:            $returnhash{'home'}= $chome;
                   6266: 	   $returnhash{'domain'} = $cdomain;
                   6267: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6268:            if (!defined($returnhash{'type'})) {
                   6269:                $returnhash{'type'} = 'Course';
                   6270:            }
1.130     albertel 6271:            while (my ($name,$value) = each %returnhash) {
1.53      www      6272:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6273:            }
1.270     www      6274:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6275:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6276: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6277:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6278:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6279:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6280:        }
                   6281:     }
1.731     albertel 6282:     if (!$args->{'one_time'}) {
1.949     raeburn  6283: 	&appenv(\%envhash);
1.731     albertel 6284:     }
1.302     albertel 6285:     return %returnhash;
1.461     www      6286: }
                   6287: 
1.1080    raeburn  6288: sub update_released_required {
                   6289:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6290:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6291:         $cid = $env{'request.course.id'};
                   6292:         $cdom = $env{'course.'.$cid.'.domain'};
                   6293:         $cnum = $env{'course.'.$cid.'.num'};
                   6294:         $chome = $env{'course.'.$cid.'.home'};
                   6295:     }
                   6296:     if ($needsrelease) {
                   6297:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6298:         my $needsupdate;
                   6299:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6300:             $needsupdate = 1;
                   6301:         } else {
                   6302:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6303:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6304:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6305:                 $needsupdate = 1;
                   6306:             }
                   6307:         }
                   6308:         if ($needsupdate) {
                   6309:             my %needshash = (
                   6310:                              'internal.releaserequired' => $needsrelease,
                   6311:                             );
                   6312:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6313:             if ($putresult eq 'ok') {
                   6314:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6315:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6316:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6317:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6318:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6319:                 }
                   6320:             }
                   6321:         }
                   6322:     }
                   6323:     return;
                   6324: }
                   6325: 
1.461     www      6326: # -------------------------------------------------See if a user is privileged
                   6327: 
                   6328: sub privileged {
1.1172.2.23  raeburn  6329:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6330:     my $now = time;
1.1172.2.23  raeburn  6331:     my $roles;
                   6332:     if (ref($possroles) eq 'ARRAY') {
                   6333:         $roles = $possroles;
                   6334:     } else {
                   6335:         $roles = ['dc','su'];
                   6336:     }
                   6337:     if (ref($possdomains) eq 'ARRAY') {
                   6338:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6339:         foreach my $dom (@{$possdomains}) {
                   6340:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6341:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6342:                 foreach my $role (@{$roles}) {
                   6343:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6344:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6345:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6346:                             return 1 unless (($end && $end < $now) ||
                   6347:                                              ($start && $start > $now));
                   6348:                         }
                   6349:                     }
                   6350:                 }
                   6351:             }
                   6352:         }
                   6353:     } else {
                   6354:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6355:         my $now = time;
1.1170    droeschl 6356: 
1.1172.2.58  raeburn  6357:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6358:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6359:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6360:                 return 1 unless ($tend && $tend < $now)
                   6361:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6362:             }
1.1172.2.23  raeburn  6363:         }
                   6364:     }
1.461     www      6365:     return 0;
1.9       www      6366: }
1.1       albertel 6367: 
1.1172.2.23  raeburn  6368: sub privileged_by_domain {
                   6369:     my ($domains,$roles) = @_;
                   6370:     my %privileged = ();
                   6371:     my $cachetime = 60*60*24;
                   6372:     my $now = time;
                   6373:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6374:         return %privileged;
                   6375:     }
                   6376:     foreach my $dom (@{$domains}) {
                   6377:         next if (ref($privileged{$dom}) eq 'HASH');
                   6378:         my $needroles;
                   6379:         foreach my $role (@{$roles}) {
                   6380:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6381:             if (defined($cached)) {
                   6382:                 if (ref($result) eq 'HASH') {
                   6383:                     $privileged{$dom}{$role} = $result;
                   6384:                 }
                   6385:             } else {
                   6386:                 $needroles = 1;
                   6387:             }
                   6388:         }
                   6389:         if ($needroles) {
                   6390:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6391:             $privileged{$dom} = {};
                   6392:             foreach my $server (keys(%dompersonnel)) {
                   6393:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6394:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6395:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6396:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6397:                         next if ($end && $end < $now);
                   6398:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6399:                             $dompersonnel{$server}{$item};
                   6400:                     }
                   6401:                 }
                   6402:             }
                   6403:             if (ref($privileged{$dom}) eq 'HASH') {
                   6404:                 foreach my $role (@{$roles}) {
                   6405:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6406:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6407:                     } else {
                   6408:                         my %hash = ();
                   6409:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6410:                     }
                   6411:                 }
                   6412:             }
                   6413:         }
                   6414:     }
                   6415:     return %privileged;
                   6416: }
                   6417: 
1.103     harris41 6418: # -------------------------------------------------------- Get user privileges
1.11      www      6419: 
                   6420: sub rolesinit {
1.1169    droeschl 6421:     my ($domain, $username) = @_;
                   6422:     my %userroles = ('user.login.time' => time);
                   6423:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6424: 
                   6425:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6426:     # also, blocking can be triggered by an activating timer
                   6427:     # it's saved in the user's %env.
                   6428:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6429:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6430:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6431:         %timerintchk, %timerintenv);
                   6432: 
1.1162    raeburn  6433:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6434:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6435:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6436:     }
1.1169    droeschl 6437: 
1.1162    raeburn  6438:     foreach my $key (keys(%timerinterval)) {
                   6439:         my ($cid,$rest) = split(/\0/,$key);
                   6440:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6441:     }
1.1169    droeschl 6442: 
1.11      www      6443:     my %allroles=();
1.1162    raeburn  6444:     my %allgroups=();
1.11      www      6445: 
1.1172.2.58  raeburn  6446:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6447:         my $role = $rolesdump{$area};
                   6448:         $area =~ s/\_\w\w$//;
                   6449: 
                   6450:         my ($trole, $tend, $tstart, $group_privs);
                   6451: 
                   6452:         if ($role =~ /^cr/) {
                   6453:         # Custom role, defined by a user 
                   6454:         # e.g., user.role.cr/msu/smith/mynewrole
                   6455:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6456:                 $trole = $1;
                   6457:                 ($tend, $tstart) = split('_', $2);
                   6458:             } else {
                   6459:                 $trole = $role;
                   6460:             }
                   6461:         } elsif ($role =~ m|^gr/|) {
                   6462:         # Role of member in a group, defined within a course/community
                   6463:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6464:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6465:             next if $tstart eq '-1';
                   6466:             ($trole, $group_privs) = split(/\//, $trole);
                   6467:             $group_privs = &unescape($group_privs);
                   6468:         } else {
                   6469:         # Just a normal role, defined in roles.tab
                   6470:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6471:         }
                   6472: 
                   6473:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6474:                  $username);
                   6475:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6476: 
                   6477:         # role expired or not available yet?
                   6478:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6479:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6480: 
                   6481:         next if $area eq '' or $trole eq '';
                   6482: 
                   6483:         my $spec = "$trole.$area";
                   6484:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6485: 
                   6486:         if ($trole =~ /^cr\//) {
                   6487:         # Custom role, defined by a user
                   6488:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6489:         } elsif ($trole eq 'gr') {
                   6490:         # Role of a member in a group, defined within a course/community
                   6491:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6492:             next;
                   6493:         } else {
                   6494:         # Normal role, defined in roles.tab
                   6495:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6496:         }
                   6497: 
                   6498:         my $cid = $tdomain.'_'.$trest;
                   6499:         unless ($firstaccchk{$cid}) {
                   6500:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6501:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6502:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6503:                         $coursetimerstarts{$cid}{$item}; 
                   6504:                 }
                   6505:             }
                   6506:             $firstaccchk{$cid} = 1;
                   6507:         }
                   6508:         unless ($timerintchk{$cid}) {
                   6509:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6510:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6511:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6512:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6513:                 }
1.12      www      6514:             }
1.1169    droeschl 6515:             $timerintchk{$cid} = 1;
1.191     harris41 6516:         }
1.11      www      6517:     }
1.1169    droeschl 6518: 
1.1172.2.91  raeburn  6519:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6520:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6521:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6522:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6523: 
1.1162    raeburn  6524:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6525: }
                   6526: 
1.567     raeburn  6527: sub set_arearole {
1.1172.2.19  raeburn  6528:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6529:     unless ($nolog) {
1.567     raeburn  6530: # log the associated role with the area
1.1172.2.19  raeburn  6531:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6532:     }
1.743     albertel 6533:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6534: }
                   6535: 
                   6536: sub custom_roleprivs {
                   6537:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6538:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6539:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6540:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6541:         my ($rdummy,$roledef)=
                   6542:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6543:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6544:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6545:             if (defined($syspriv)) {
1.1043    raeburn  6546:                 if ($trest =~ /^$match_community$/) {
                   6547:                     $syspriv =~ s/bre\&S//; 
                   6548:                 }
1.567     raeburn  6549:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6550:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6551:             }
                   6552:             if ($tdomain ne '') {
                   6553:                 if (defined($dompriv)) {
                   6554:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6555:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6556:                 }
                   6557:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6558:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6559:                         my $rolename = $1;
                   6560:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6561:                     }
1.567     raeburn  6562:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6563:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6564:                 }
                   6565:             }
                   6566:         }
                   6567:     }
                   6568: }
                   6569: 
1.1172.2.89  raeburn  6570: sub course_adhocrole_privs {
                   6571:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6572:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6573:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6574:         my (%currprivs,%storeprivs);
                   6575:         foreach my $item (split(/:/,$coursepriv)) {
                   6576:             my ($priv,$restrict) = split(/\&/,$item);
                   6577:             $currprivs{$priv} = $restrict;
                   6578:         }
                   6579:         my (%possadd,%possremove,%full);
                   6580:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6581:             my ($priv,$restrict)=split(/\&/,$item);
                   6582:             $full{$priv} = $restrict;
                   6583:         }
                   6584:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6585:              next if ($item eq '');
                   6586:              my ($rule,$rest) = split(/=/,$item);
                   6587:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6588:              foreach my $priv (split(/:/,$rest)) {
                   6589:                  if ($priv ne '') {
                   6590:                      if ($rule eq 'off') {
                   6591:                          $possremove{$priv} = 1;
                   6592:                      } else {
                   6593:                          $possadd{$priv} = 1;
                   6594:                      }
                   6595:                  }
                   6596:              }
                   6597:          }
                   6598:          foreach my $priv (sort(keys(%full))) {
                   6599:              if (exists($currprivs{$priv})) {
                   6600:                  unless (exists($possremove{$priv})) {
                   6601:                      $storeprivs{$priv} = $currprivs{$priv};
                   6602:                  }
                   6603:              } elsif (exists($possadd{$priv})) {
                   6604:                  $storeprivs{$priv} = $full{$priv};
                   6605:              }
                   6606:          }
                   6607:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6608:      }
                   6609:      return $coursepriv;
                   6610: }
                   6611: 
1.678     raeburn  6612: sub group_roleprivs {
                   6613:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6614:     my $access = 1;
                   6615:     my $now = time;
                   6616:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6617:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6618:     if ($access) {
1.811     albertel 6619:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6620:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6621:     }
                   6622: }
1.567     raeburn  6623: 
                   6624: sub standard_roleprivs {
                   6625:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6626:     if (defined($pr{$trole.':s'})) {
                   6627:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6628:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6629:     }
                   6630:     if ($tdomain ne '') {
                   6631:         if (defined($pr{$trole.':d'})) {
                   6632:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6633:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6634:         }
                   6635:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6636:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6637:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6638:         }
                   6639:     }
                   6640: }
                   6641: 
                   6642: sub set_userprivs {
1.1064    raeburn  6643:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6644:     my $author=0;
                   6645:     my $adv=0;
1.1172.2.91  raeburn  6646:     my $rar=0;
1.678     raeburn  6647:     my %grouproles = ();
                   6648:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6649:         my @groupkeys; 
1.1000    raeburn  6650:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6651:             push(@groupkeys,$role);
                   6652:         }
                   6653:         if (ref($groups_roles) eq 'HASH') {
                   6654:             foreach my $key (keys(%{$groups_roles})) {
                   6655:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6656:                     push(@groupkeys,$key);
                   6657:                 }
                   6658:             }
                   6659:         }
                   6660:         if (@groupkeys > 0) {
                   6661:             foreach my $role (@groupkeys) {
                   6662:                 my ($trole,$area,$sec,$extendedarea);
                   6663:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6664:                     $trole = $1;
                   6665:                     $area = $2;
                   6666:                     $sec = $3;
                   6667:                     $extendedarea = $area.$sec;
                   6668:                     if (exists($$allgroups{$area})) {
                   6669:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6670:                             my $spec = $trole.'.'.$extendedarea;
                   6671:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6672:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6673:                         }
1.678     raeburn  6674:                     }
                   6675:                 }
                   6676:             }
                   6677:         }
                   6678:     }
1.800     albertel 6679:     foreach my $group (keys(%grouproles)) {
                   6680:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6681:     }
1.800     albertel 6682:     foreach my $role (keys(%{$allroles})) {
                   6683:         my %thesepriv;
1.941     raeburn  6684:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6685:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6686:             if ($item ne '') {
                   6687:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6688:                 if ($restrictions eq '') {
                   6689:                     $thesepriv{$privilege}='F';
                   6690:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6691:                     $thesepriv{$privilege}.=$restrictions;
                   6692:                 }
                   6693:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6694:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6695:             }
                   6696:         }
                   6697:         my $thesestr='';
1.1104    raeburn  6698:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6699: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6700: 	}
                   6701:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6702:     }
1.1172.2.91  raeburn  6703:     return ($author,$adv,$rar);
1.567     raeburn  6704: }
                   6705: 
1.994     raeburn  6706: sub role_status {
1.1104    raeburn  6707:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6708:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6709:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6710:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6711:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6712:             $$where = '/'.$two;
1.994     raeburn  6713:             $$trolecode=$$role.'.'.$$where;
                   6714:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6715:             $$tstatus='is';
1.1104    raeburn  6716:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6717:                 $$tstatus='future';
1.1034    raeburn  6718:                 if ($$tstart<$now) {
                   6719:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6720:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6721:                             my (%allroles,%allgroups,$group_privs,
                   6722:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6723:                             my %userroles = (
                   6724:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6725:                             );
1.1064    raeburn  6726:                             @rolecodes = ('cm'); 
1.1002    raeburn  6727:                             my $spec=$$role.'.'.$$where;
                   6728:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6729:                             if ($$role =~ /^cr\//) {
                   6730:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6731:                                 push(@rolecodes,'cr');
1.1002    raeburn  6732:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6733:                                 push(@rolecodes,$$role);
1.1002    raeburn  6734:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6735:                                                     $env{'user.name'});
1.1064    raeburn  6736:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6737:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6738:                                 $group_privs = &unescape($group_privs);
                   6739:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6740:                                 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  6741:                                 &get_groups_roles($tdomain,$trest,
                   6742:                                                   \%course_roles,\@rolecodes,
                   6743:                                                   \%groups_roles);
1.1002    raeburn  6744:                             } else {
1.1064    raeburn  6745:                                 push(@rolecodes,$$role);
1.1002    raeburn  6746:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6747:                             }
1.1172.2.91  raeburn  6748:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6749:                                                                    \%groups_roles);
1.1064    raeburn  6750:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6751:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6752:                         }
                   6753:                     }
1.1034    raeburn  6754:                     $$tstatus = 'is';
1.1002    raeburn  6755:                 }
1.994     raeburn  6756:             }
                   6757:             if ($$tend) {
1.1104    raeburn  6758:                 if ($$tend<$update) {
1.994     raeburn  6759:                     $$tstatus='expired';
                   6760:                 } elsif ($$tend<$now) {
                   6761:                     $$tstatus='will_not';
                   6762:                 }
                   6763:             }
                   6764:         }
                   6765:     }
                   6766: }
                   6767: 
1.1104    raeburn  6768: sub get_groups_roles {
                   6769:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6770:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6771:                   (ref($rolecodes) eq 'ARRAY') && 
                   6772:                   (ref($groups_roles) eq 'HASH')); 
                   6773:     if (keys(%{$cdom_courseroles}) > 0) {
                   6774:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6775:         if ($cdom ne '' && $cnum ne '') {
                   6776:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6777:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6778:                     my $crsrole = $1;
                   6779:                     my $crssec = $2;
                   6780:                     if ($crsrole =~ /^cr/) {
                   6781:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6782:                             push(@{$rolecodes},'cr');
                   6783:                         }
                   6784:                     } else {
                   6785:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6786:                             push(@{$rolecodes},$crsrole);
                   6787:                         }
                   6788:                     }
                   6789:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6790:                     if ($crssec ne '') {
                   6791:                         $rolekey .= "/$crssec";
                   6792:                     }
                   6793:                     $rolekey .= './';
                   6794:                     $groups_roles->{$rolekey} = $rolecodes;
                   6795:                 }
                   6796:             }
                   6797:         }
                   6798:     }
                   6799:     return;
                   6800: }
                   6801: 
                   6802: sub delete_env_groupprivs {
                   6803:     my ($where,$courseroles,$possroles) = @_;
                   6804:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6805:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6806:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6807:         %{$courseroles->{$udom}} =
                   6808:             &get_my_roles('','','userroles',['active'],
                   6809:                           $possroles,[$udom],1);
                   6810:     }
                   6811:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6812:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6813:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6814:             my $area = '/'.$cdom.'/'.$cnum;
                   6815:             my $privkey = "user.priv.$crsrole.$area";
                   6816:             if ($crssec ne '') {
                   6817:                 $privkey .= '/'.$crssec;
                   6818:             }
                   6819:             $privkey .= ".$area/$group";
                   6820:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6821:         }
                   6822:     }
                   6823:     return;
                   6824: }
                   6825: 
1.994     raeburn  6826: sub check_adhoc_privs {
1.1172.2.86  raeburn  6827:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6828:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6829:     if ($sec) {
                   6830:         $cckey .= '/'.$sec;
                   6831:     }
1.1172.2.9  raeburn  6832:     my $setprivs;
1.994     raeburn  6833:     if ($env{$cckey}) {
                   6834:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6835:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6836:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6837:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6838:             $setprivs = 1;
1.994     raeburn  6839:         }
                   6840:     } else {
1.1172.2.87  raeburn  6841:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6842:         $setprivs = 1;
1.994     raeburn  6843:     }
1.1172.2.9  raeburn  6844:     return $setprivs;
1.994     raeburn  6845: }
                   6846: 
                   6847: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6848: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6849:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6850:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6851:     if ($sec ne '') {
                   6852:         $area .= '/'.$sec;
                   6853:     }
1.994     raeburn  6854:     my $spec = $role.'.'.$area;
                   6855:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6856:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6857:     my %rolehash = ();
1.1172.2.89  raeburn  6858:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6859:         my $rolename = $1;
1.1172.2.84  raeburn  6860:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6861:         my %domdef = &get_domain_defaults($dcdom);
                   6862:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6863:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6864:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6865:             }
                   6866:         }
1.1172.2.84  raeburn  6867:     } else {
                   6868:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6869:     }
1.1172.2.91  raeburn  6870:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6871:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6872:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1172.2.146.  .1(raebu 6873:22):     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
                   6874:22):             ($caller eq 'tiny')) {
1.1088    raeburn  6875:         &appenv( {'request.role'        => $spec,
                   6876:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6877:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6878:                  }
                   6879:                );
                   6880:         my $tadv=0;
                   6881:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6882:         &appenv({'request.role.adv'    => $tadv});
                   6883:     }
1.994     raeburn  6884: }
                   6885: 
1.12      www      6886: # --------------------------------------------------------------- get interface
                   6887: 
                   6888: sub get {
1.131     albertel 6889:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6890:    my $items='';
1.800     albertel 6891:    foreach my $item (@$storearr) {
                   6892:        $items.=&escape($item).'&';
1.191     harris41 6893:    }
1.12      www      6894:    $items=~s/\&$//;
1.620     albertel 6895:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6896:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6897:    my $uhome=&homeserver($uname,$udomain);
                   6898: 
1.133     albertel 6899:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6900:    my @pairs=split(/\&/,$rep);
1.273     albertel 6901:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6902:      return @pairs;
                   6903:    }
1.15      www      6904:    my %returnhash=();
1.42      www      6905:    my $i=0;
1.800     albertel 6906:    foreach my $item (@$storearr) {
                   6907:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6908:       $i++;
1.191     harris41 6909:    }
1.15      www      6910:    return %returnhash;
1.27      www      6911: }
                   6912: 
                   6913: # --------------------------------------------------------------- del interface
                   6914: 
                   6915: sub del {
1.133     albertel 6916:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6917:    my $items='';
1.800     albertel 6918:    foreach my $item (@$storearr) {
                   6919:        $items.=&escape($item).'&';
1.191     harris41 6920:    }
1.984     neumanie 6921: 
1.27      www      6922:    $items=~s/\&$//;
1.620     albertel 6923:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6924:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6925:    my $uhome=&homeserver($uname,$udomain);
                   6926:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6927: }
                   6928: 
                   6929: # -------------------------------------------------------------- dump interface
                   6930: 
1.1172.2.22  raeburn  6931: sub unserialize {
                   6932:     my ($rep, $escapedkeys) = @_;
                   6933: 
                   6934:     return {} if $rep =~ /^error/;
                   6935: 
                   6936:     my %returnhash=();
                   6937:     foreach my $item (split(/\&/,$rep)) {
                   6938:         my ($key, $value) = split(/=/, $item, 2);
                   6939:         $key = unescape($key) unless $escapedkeys;
                   6940:         next if $key =~ /^error: 2 /;
                   6941:         $returnhash{$key} = &thaw_unescape($value);
                   6942:     }
                   6943:     return \%returnhash;
                   6944: }
                   6945: 
                   6946: # see Lond::dump_with_regexp
                   6947: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6948: sub dump {
1.1172.2.146.  .1(raebu 6949:22):     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
1.755     albertel 6950:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6951:     if (!$uname) { $uname=$env{'user.name'}; }
                   6952:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6953: 
1.1172.2.55  raeburn  6954:     if ($regexp) {
                   6955:         $regexp=&escape($regexp);
                   6956:     } else {
                   6957:         $regexp='.';
                   6958:     }
1.1172.2.22  raeburn  6959:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   6960:         # user is hosted on this machine
1.1172.2.55  raeburn  6961:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  6962:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  6963:         return %{&unserialize($reply, $escapedkeys)};
                   6964:     }
1.1172.2.146.  .1(raebu 6965:22):     my $rep;
                   6966:22):     if ($encrypt) {
                   6967:22):         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   6968:22):     } else {
                   6969:22):         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   6970:22):     }
1.755     albertel 6971:     my @pairs=split(/\&/,$rep);
                   6972:     my %returnhash=();
1.1098    foxr     6973:     if (!($rep =~ /^error/ )) {
                   6974: 	foreach my $item (@pairs) {
                   6975: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  6976:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     6977: 	    next if ($key =~ /^error: 2 /);
                   6978: 	    $returnhash{$key}=&thaw_unescape($value);
                   6979: 	}
1.755     albertel 6980:     }
                   6981:     return %returnhash;
1.407     www      6982: }
                   6983: 
1.1098    foxr     6984: 
1.717     albertel 6985: # --------------------------------------------------------- dumpstore interface
                   6986: 
                   6987: sub dumpstore {
                   6988:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  6989:    # same as dump but keys must be escaped. They may contain colon separated
                   6990:    # lists of values that may themself contain colons (e.g. symbs).
                   6991:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6992: }
                   6993: 
1.407     www      6994: # -------------------------------------------------------------- keys interface
                   6995: 
                   6996: sub getkeys {
                   6997:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6998:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6999:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      7000:    my $uhome=&homeserver($uname,$udomain);
                   7001:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   7002:    my @keyarray=();
1.800     albertel 7003:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  7004:       next if ($key =~ /^error: 2 /);
1.800     albertel 7005:       push(@keyarray,&unescape($key));
1.407     www      7006:    }
                   7007:    return @keyarray;
1.318     matthew  7008: }
                   7009: 
1.319     matthew  7010: # --------------------------------------------------------------- currentdump
                   7011: sub currentdump {
1.328     matthew  7012:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 7013:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   7014:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   7015:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  7016:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  7017:    my $rep;
                   7018: 
                   7019:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   7020:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   7021:                    $courseid)));
                   7022:    } else {
                   7023:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   7024:    }
                   7025: 
1.318     matthew  7026:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  7027:    #
1.318     matthew  7028:    my %returnhash=();
1.319     matthew  7029:    #
                   7030:    if ($rep eq "unknown_cmd") { 
                   7031:        # an old lond will not know currentdump
                   7032:        # Do a dump and make it look like a currentdump
1.822     albertel 7033:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  7034:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   7035:        my %hash = @tmp;
                   7036:        @tmp=();
1.424     matthew  7037:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  7038:    } else {
                   7039:        my @pairs=split(/\&/,$rep);
1.800     albertel 7040:        foreach my $pair (@pairs) {
                   7041:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  7042:            my ($symb,$param) = split(/:/,$key);
                   7043:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 7044:                                                         &thaw_unescape($value);
1.319     matthew  7045:        }
1.191     harris41 7046:    }
1.12      www      7047:    return %returnhash;
1.424     matthew  7048: }
                   7049: 
                   7050: sub convert_dump_to_currentdump{
                   7051:     my %hash = %{shift()};
                   7052:     my %returnhash;
                   7053:     # Code ripped from lond, essentially.  The only difference
                   7054:     # here is the unescaping done by lonnet::dump().  Conceivably
                   7055:     # we might run in to problems with parameter names =~ /^v\./
                   7056:     while (my ($key,$value) = each(%hash)) {
                   7057:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 7058: 	$symb  = &unescape($symb);
                   7059: 	$param = &unescape($param);
1.424     matthew  7060:         next if ($v eq 'version' || $symb eq 'keys');
                   7061:         next if (exists($returnhash{$symb}) &&
                   7062:                  exists($returnhash{$symb}->{$param}) &&
                   7063:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   7064:         $returnhash{$symb}->{$param}=$value;
                   7065:         $returnhash{$symb}->{'v.'.$param}=$v;
                   7066:     }
                   7067:     #
                   7068:     # Remove all of the keys in the hashes which keep track of
                   7069:     # the version of the parameter.
                   7070:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   7071:         # use a foreach because we are going to delete from the hash.
                   7072:         foreach my $key (keys(%$param_hash)) {
                   7073:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   7074:         }
                   7075:     }
                   7076:     return \%returnhash;
1.12      www      7077: }
                   7078: 
1.627     albertel 7079: # ------------------------------------------------------ critical inc interface
                   7080: 
                   7081: sub cinc {
                   7082:     return &inc(@_,'critical');
                   7083: }
                   7084: 
1.449     matthew  7085: # --------------------------------------------------------------- inc interface
                   7086: 
                   7087: sub inc {
1.627     albertel 7088:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7089:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7090:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7091:     my $uhome=&homeserver($uname,$udomain);
                   7092:     my $items='';
                   7093:     if (! ref($store)) {
                   7094:         # got a single value, so use that instead
                   7095:         $items = &escape($store).'=&';
                   7096:     } elsif (ref($store) eq 'SCALAR') {
                   7097:         $items = &escape($$store).'=&';        
                   7098:     } elsif (ref($store) eq 'ARRAY') {
                   7099:         $items = join('=&',map {&escape($_);} @{$store});
                   7100:     } elsif (ref($store) eq 'HASH') {
                   7101:         while (my($key,$value) = each(%{$store})) {
                   7102:             $items.= &escape($key).'='.&escape($value).'&';
                   7103:         }
                   7104:     }
                   7105:     $items=~s/\&$//;
1.627     albertel 7106:     if ($critical) {
                   7107: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7108:     } else {
                   7109: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7110:     }
1.449     matthew  7111: }
                   7112: 
1.12      www      7113: # --------------------------------------------------------------- put interface
                   7114: 
                   7115: sub put {
1.1172.2.146.  .1(raebu 7116:22):    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
1.620     albertel 7117:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7118:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7119:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7120:    my $items='';
1.800     albertel 7121:    foreach my $item (keys(%$storehash)) {
                   7122:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7123:    }
1.12      www      7124:    $items=~s/\&$//;
1.1172.2.146.  .1(raebu 7125:22):    if ($encrypt) {
                   7126:22):        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
                   7127:22):    } else {
                   7128:22):        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
                   7129:22):    }
1.47      www      7130: }
                   7131: 
1.631     albertel 7132: # ------------------------------------------------------------ newput interface
                   7133: 
                   7134: sub newput {
                   7135:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7136:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7137:    if (!$uname) { $uname=$env{'user.name'}; }
                   7138:    my $uhome=&homeserver($uname,$udomain);
                   7139:    my $items='';
                   7140:    foreach my $key (keys(%$storehash)) {
                   7141:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7142:    }
                   7143:    $items=~s/\&$//;
                   7144:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7145: }
                   7146: 
                   7147: # ---------------------------------------------------------  putstore interface
                   7148: 
1.524     raeburn  7149: sub putstore {
1.1172.2.59  raeburn  7150:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7151:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7152:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7153:    my $uhome=&homeserver($uname,$udomain);
                   7154:    my $items='';
1.715     albertel 7155:    foreach my $key (keys(%$storehash)) {
                   7156:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7157:    }
1.715     albertel 7158:    $items=~s/\&$//;
1.716     albertel 7159:    my $esc_symb=&escape($symb);
                   7160:    my $esc_v=&escape($version);
1.715     albertel 7161:    my $reply =
1.716     albertel 7162:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7163: 	      $uhome);
1.1172.2.59  raeburn  7164:    if (($tolog) && ($reply eq 'ok')) {
                   7165:        my $namevalue='';
                   7166:        foreach my $key (keys(%{$storehash})) {
                   7167:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7168:        }
1.1172.2.134  raeburn  7169:        my $ip = &get_requestor_ip();
1.1172.2.135  raeburn  7170:        $namevalue .= 'ip='.&escape($ip).
1.1172.2.59  raeburn  7171:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7172:                      '&version='.$esc_v.
                   7173:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7174:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7175:    }
1.715     albertel 7176:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7177:        # gfall back to way things use to be done
1.715     albertel 7178:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7179: 			    $uname);
1.524     raeburn  7180:    }
1.715     albertel 7181:    return $reply;
                   7182: }
                   7183: 
                   7184: sub old_putstore {
1.716     albertel 7185:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7186:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7187:     if (!$uname) { $uname=$env{'user.name'}; }
                   7188:     my $uhome=&homeserver($uname,$udomain);
                   7189:     my %newstorehash;
1.800     albertel 7190:     foreach my $item (keys(%$storehash)) {
                   7191: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7192: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7193:     }
                   7194:     my $items='';
                   7195:     my %allitems = ();
1.800     albertel 7196:     foreach my $item (keys(%newstorehash)) {
                   7197: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7198: 	    my $key = $1.':keys:'.$2;
                   7199: 	    $allitems{$key} .= $3.':';
                   7200: 	}
1.800     albertel 7201: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7202:     }
1.800     albertel 7203:     foreach my $item (keys(%allitems)) {
                   7204: 	$allitems{$item} =~ s/\:$//;
                   7205: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7206:     }
                   7207:     $items=~s/\&$//;
                   7208:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7209: }
                   7210: 
1.47      www      7211: # ------------------------------------------------------ critical put interface
                   7212: 
                   7213: sub cput {
1.134     albertel 7214:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7215:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7216:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7217:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7218:    my $items='';
1.800     albertel 7219:    foreach my $item (keys(%$storehash)) {
                   7220:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7221:    }
1.47      www      7222:    $items=~s/\&$//;
1.134     albertel 7223:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7224: }
                   7225: 
                   7226: # -------------------------------------------------------------- eget interface
                   7227: 
                   7228: sub eget {
1.133     albertel 7229:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7230:    my $items='';
1.800     albertel 7231:    foreach my $item (@$storearr) {
                   7232:        $items.=&escape($item).'&';
1.191     harris41 7233:    }
1.12      www      7234:    $items=~s/\&$//;
1.620     albertel 7235:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7236:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7237:    my $uhome=&homeserver($uname,$udomain);
                   7238:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7239:    my @pairs=split(/\&/,$rep);
                   7240:    my %returnhash=();
1.42      www      7241:    my $i=0;
1.800     albertel 7242:    foreach my $item (@$storearr) {
                   7243:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7244:       $i++;
1.191     harris41 7245:    }
1.12      www      7246:    return %returnhash;
                   7247: }
                   7248: 
1.667     albertel 7249: # ------------------------------------------------------------ tmpput interface
                   7250: sub tmpput {
1.802     raeburn  7251:     my ($storehash,$server,$context)=@_;
1.667     albertel 7252:     my $items='';
1.800     albertel 7253:     foreach my $item (keys(%$storehash)) {
                   7254: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7255:     }
                   7256:     $items=~s/\&$//;
1.802     raeburn  7257:     if (defined($context)) {
                   7258:         $items .= ':'.&escape($context);
                   7259:     }
1.667     albertel 7260:     return &reply("tmpput:$items",$server);
                   7261: }
                   7262: 
                   7263: # ------------------------------------------------------------ tmpget interface
                   7264: sub tmpget {
1.688     albertel 7265:     my ($token,$server)=@_;
                   7266:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7267:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7268:     my %returnhash;
1.1172.2.85  raeburn  7269:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7270:         return %returnhash;
                   7271:     }
1.667     albertel 7272:     foreach my $item (split(/\&/,$rep)) {
                   7273: 	my ($key,$value)=split(/=/,$item);
                   7274: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7275:     }
                   7276:     return %returnhash;
                   7277: }
                   7278: 
1.1113    raeburn  7279: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7280: sub tmpdel {
                   7281:     my ($token,$server)=@_;
                   7282:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7283:     return &reply("tmpdel:$token",$server);
                   7284: }
                   7285: 
1.1172.2.13  raeburn  7286: # ------------------------------------------------------------ get_timebased_id
                   7287: 
                   7288: sub get_timebased_id {
                   7289:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7290:         $maxtries) = @_;
                   7291:     my ($newid,$error,$dellock);
                   7292:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7293:         return ('','ok','invalid call to get suffix');
                   7294:     }
                   7295: 
                   7296: # set defaults for any optional args for which values were not supplied
                   7297:     if ($who eq '') {
                   7298:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7299:     }
                   7300:     if (!$locktries) {
                   7301:         $locktries = 3;
                   7302:     }
                   7303:     if (!$maxtries) {
                   7304:         $maxtries = 10;
                   7305:     }
                   7306: 
                   7307:     if (($cdom eq '') || ($cnum eq '')) {
                   7308:         if ($env{'request.course.id'}) {
                   7309:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7310:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7311:         }
                   7312:         if (($cdom eq '') || ($cnum eq '')) {
                   7313:             return ('','ok','call to get suffix not in course context');
                   7314:         }
                   7315:     }
                   7316: 
                   7317: # construct locking item
                   7318:     my $lockhash = {
                   7319:                       $prefix."\0".'locked_'.$keyid => $who,
                   7320:                    };
                   7321:     my $tries = 0;
                   7322: 
                   7323: # attempt to get lock on nohist_$namespace file
                   7324:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7325:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7326:         $tries ++;
                   7327:         sleep 1;
                   7328:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7329:     }
                   7330: 
                   7331: # attempt to get unique identifier, based on current timestamp
                   7332:     if ($gotlock eq 'ok') {
                   7333:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7334:         my $id = time;
                   7335:         $newid = $id;
1.1172.2.56  raeburn  7336:         if ($idtype eq 'addcode') {
                   7337:             $newid .= &sixnum_code();
                   7338:         }
1.1172.2.13  raeburn  7339:         my $idtries = 0;
                   7340:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7341:             if ($idtype eq 'concat') {
                   7342:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7343:             } elsif ($idtype eq 'addcode') {
                   7344:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7345:             } else {
                   7346:                 $newid ++;
                   7347:             }
                   7348:             $idtries ++;
                   7349:         }
                   7350:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7351:             my %new_item =  (
                   7352:                               $prefix."\0".$newid => $who,
                   7353:                             );
                   7354:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7355:                                                  $cdom,$cnum);
                   7356:             if ($putresult ne 'ok') {
                   7357:                 undef($newid);
                   7358:                 $error = 'error saving new item: '.$putresult;
                   7359:             }
                   7360:         } else {
1.1172.2.56  raeburn  7361:              undef($newid);
1.1172.2.13  raeburn  7362:              $error = ('error: no unique suffix available for the new item ');
                   7363:         }
                   7364: #  remove lock
                   7365:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7366:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7367:     } else {
                   7368:         $error = "error: could not obtain lockfile\n";
                   7369:         $dellock = 'ok';
1.1172.2.58  raeburn  7370:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7371:             $dellock = 'nolock';
                   7372:         }
1.1172.2.13  raeburn  7373:     }
                   7374:     return ($newid,$dellock,$error);
                   7375: }
                   7376: 
1.1172.2.56  raeburn  7377: sub sixnum_code {
                   7378:     my $code;
                   7379:     for (0..6) {
                   7380:         $code .= int( rand(9) );
                   7381:     }
                   7382:     return $code;
                   7383: }
                   7384: 
1.765     albertel 7385: # -------------------------------------------------- portfolio access checking
                   7386: 
                   7387: sub portfolio_access {
1.1172.2.77  raeburn  7388:     my ($requrl,$clientip) = @_;
1.765     albertel 7389:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7390:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7391:     if ($result) {
                   7392:         my %setters;
                   7393:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1172.2.142  raeburn  7394:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
                   7395:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
                   7396:             if (($startblock && $endblock) || ($by_ip))  {
1.814     raeburn  7397:                 return 'B';
                   7398:             }
                   7399:         } else {
1.1172.2.142  raeburn  7400:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdo) =
                   7401:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   7402:             if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  7403:                 return 'B';
                   7404:             }
                   7405:         }
                   7406:     }
1.765     albertel 7407:     if ($result eq 'ok') {
1.766     albertel 7408:        return 'F';
1.765     albertel 7409:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7410:        return 'A';
1.765     albertel 7411:     }
1.766     albertel 7412:     return '';
1.765     albertel 7413: }
                   7414: 
                   7415: sub get_portfolio_access {
1.1172.2.77  raeburn  7416:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7417: 
                   7418:     if (!ref($access_hash)) {
                   7419: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7420: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7421: 						   $file_name);
                   7422: 	$access_hash = $access_controls{$file_name};
                   7423:     }
                   7424: 
1.1172.2.77  raeburn  7425:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7426:     my $now = time;
                   7427:     if (ref($access_hash) eq 'HASH') {
                   7428:         foreach my $key (keys(%{$access_hash})) {
                   7429:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7430:             if ($start > $now) {
                   7431:                 next;
                   7432:             }
                   7433:             if ($end && $end<$now) {
                   7434:                 next;
                   7435:             }
                   7436:             if ($scope eq 'public') {
                   7437:                 $public = $key;
                   7438:                 last;
                   7439:             } elsif ($scope eq 'guest') {
                   7440:                 $guest = $key;
                   7441:             } elsif ($scope eq 'domains') {
                   7442:                 push(@domains,$key);
                   7443:             } elsif ($scope eq 'users') {
                   7444:                 push(@users,$key);
                   7445:             } elsif ($scope eq 'course') {
                   7446:                 push(@courses,$key);
                   7447:             } elsif ($scope eq 'group') {
                   7448:                 push(@groups,$key);
1.1172.2.77  raeburn  7449:             } elsif ($scope eq 'ip') {
                   7450:                 push(@ips,$key);
1.765     albertel 7451:             }
                   7452:         }
                   7453:         if ($public) {
                   7454:             return 'ok';
1.1172.2.77  raeburn  7455:         } elsif (@ips > 0) {
                   7456:             my $allowed;
                   7457:             foreach my $ipkey (@ips) {
                   7458:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7459:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7460:                         $allowed = 1;
                   7461:                         last;
                   7462:                     }
                   7463:                 }
                   7464:             }
                   7465:             if ($allowed) {
                   7466:                 return 'ok';
                   7467:             }
1.765     albertel 7468:         }
                   7469:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7470:             if ($guest) {
                   7471:                 return $guest;
                   7472:             }
                   7473:         } else {
                   7474:             if (@domains > 0) {
                   7475:                 foreach my $domkey (@domains) {
                   7476:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7477:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7478:                             return 'ok';
                   7479:                         }
                   7480:                     }
                   7481:                 }
                   7482:             }
                   7483:             if (@users > 0) {
                   7484:                 foreach my $userkey (@users) {
1.865     raeburn  7485:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7486:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7487:                             if (ref($item) eq 'HASH') {
                   7488:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7489:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7490:                                     return 'ok';
                   7491:                                 }
                   7492:                             }
                   7493:                         }
                   7494:                     } 
1.765     albertel 7495:                 }
                   7496:             }
                   7497:             my %roleshash;
                   7498:             my @courses_and_groups = @courses;
                   7499:             push(@courses_and_groups,@groups); 
                   7500:             if (@courses_and_groups > 0) {
                   7501:                 my (%allgroups,%allroles); 
                   7502:                 my ($start,$end,$role,$sec,$group);
                   7503:                 foreach my $envkey (%env) {
1.1060    raeburn  7504:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7505:                         my $cid = $2.'_'.$3; 
                   7506:                         if ($1 eq 'gr') {
                   7507:                             $group = $4;
                   7508:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7509:                         } else {
                   7510:                             if ($4 eq '') {
                   7511:                                 $sec = 'none';
                   7512:                             } else {
                   7513:                                 $sec = $4;
                   7514:                             }
                   7515:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7516:                         }
1.811     albertel 7517:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7518:                         my $cid = $2.'_'.$3;
                   7519:                         if ($4 eq '') {
                   7520:                             $sec = 'none';
                   7521:                         } else {
                   7522:                             $sec = $4;
                   7523:                         }
                   7524:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7525:                     }
                   7526:                 }
                   7527:                 if (keys(%allroles) == 0) {
                   7528:                     return;
                   7529:                 }
                   7530:                 foreach my $key (@courses_and_groups) {
                   7531:                     my %content = %{$$access_hash{$key}};
                   7532:                     my $cnum = $content{'number'};
                   7533:                     my $cdom = $content{'domain'};
                   7534:                     my $cid = $cdom.'_'.$cnum;
                   7535:                     if (!exists($allroles{$cid})) {
                   7536:                         next;
                   7537:                     }    
                   7538:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7539:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7540:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7541:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7542:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7543:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7544:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7545:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7546:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7547:                                         if (grep/^all$/,@sections) {
                   7548:                                             return 'ok';
                   7549:                                         } else {
                   7550:                                             if (grep/^$sec$/,@sections) {
                   7551:                                                 return 'ok';
                   7552:                                             }
                   7553:                                         }
                   7554:                                     }
                   7555:                                 }
                   7556:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7557:                                     if (grep/^none$/,@groups) {
                   7558:                                         return 'ok';
                   7559:                                     }
                   7560:                                 } else {
                   7561:                                     if (grep/^all$/,@groups) {
                   7562:                                         return 'ok';
                   7563:                                     } 
                   7564:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7565:                                         if (grep/^$group$/,@groups) {
                   7566:                                             return 'ok';
                   7567:                                         }
                   7568:                                     }
                   7569:                                 } 
                   7570:                             }
                   7571:                         }
                   7572:                     }
                   7573:                 }
                   7574:             }
                   7575:             if ($guest) {
                   7576:                 return $guest;
                   7577:             }
                   7578:         }
                   7579:     }
                   7580:     return;
                   7581: }
                   7582: 
                   7583: sub course_group_datechecker {
                   7584:     my ($dates,$now,$status) = @_;
                   7585:     my ($start,$end) = split(/\./,$dates);
                   7586:     if (!$start && !$end) {
                   7587:         return 'ok';
                   7588:     }
                   7589:     if (grep/^active$/,@{$status}) {
                   7590:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7591:             return 'ok';
                   7592:         }
                   7593:     }
                   7594:     if (grep/^previous$/,@{$status}) {
                   7595:         if ($end > $now ) {
                   7596:             return 'ok';
                   7597:         }
                   7598:     }
                   7599:     if (grep/^future$/,@{$status}) {
                   7600:         if ($start > $now) {
                   7601:             return 'ok';
                   7602:         }
                   7603:     }
                   7604:     return; 
                   7605: }
                   7606: 
                   7607: sub parse_portfolio_url {
                   7608:     my ($url) = @_;
                   7609: 
                   7610:     my ($type,$udom,$unum,$group,$file_name);
                   7611:     
1.823     albertel 7612:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7613: 	$type = 1;
                   7614:         $udom = $1;
                   7615:         $unum = $2;
                   7616:         $file_name = $3;
1.823     albertel 7617:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7618: 	$type = 2;
                   7619:         $udom = $1;
                   7620:         $unum = $2;
                   7621:         $group = $3;
                   7622:         $file_name = $3.'/'.$4;
                   7623:     }
                   7624:     if (wantarray) {
                   7625: 	return ($type,$udom,$unum,$file_name,$group);
                   7626:     }
                   7627:     return $type;
                   7628: }
                   7629: 
                   7630: sub is_portfolio_url {
                   7631:     my ($url) = @_;
                   7632:     return scalar(&parse_portfolio_url($url));
                   7633: }
                   7634: 
1.798     raeburn  7635: sub is_portfolio_file {
                   7636:     my ($file) = @_;
1.820     raeburn  7637:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7638:         return 1;
                   7639:     }
                   7640:     return;
                   7641: }
                   7642: 
1.976     raeburn  7643: sub usertools_access {
1.1084    raeburn  7644:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7645:     my ($access,%tools);
                   7646:     if ($context eq '') {
                   7647:         $context = 'tools';
                   7648:     }
                   7649:     if ($context eq 'requestcourses') {
                   7650:         %tools = (
                   7651:                       official   => 1,
                   7652:                       unofficial => 1,
1.1006    raeburn  7653:                       community  => 1,
1.1172.2.37  raeburn  7654:                       textbook   => 1,
1.985     raeburn  7655:                  );
1.1172.2.9  raeburn  7656:     } elsif ($context eq 'requestauthor') {
                   7657:         %tools = (
                   7658:                       requestauthor => 1,
                   7659:                  );
1.985     raeburn  7660:     } else {
                   7661:         %tools = (
                   7662:                       aboutme   => 1,
                   7663:                       blog      => 1,
1.1172.2.6  raeburn  7664:                       webdav    => 1,
1.985     raeburn  7665:                       portfolio => 1,
                   7666:                  );
                   7667:     }
1.976     raeburn  7668:     return if (!defined($tools{$tool}));
                   7669: 
1.1172.2.35  raeburn  7670:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7671:         $udom = $env{'user.domain'};
                   7672:         $uname = $env{'user.name'};
                   7673:     }
                   7674: 
1.978     raeburn  7675:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7676:         if ($action ne 'reload') {
1.985     raeburn  7677:             if ($context eq 'requestcourses') {
                   7678:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7679:             } elsif ($context eq 'requestauthor') {
                   7680:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7681:             } else {
                   7682:                 return $env{'environment.availabletools.'.$tool};
                   7683:             }
                   7684:         }
1.976     raeburn  7685:     }
                   7686: 
1.1172.2.9  raeburn  7687:     my ($toolstatus,$inststatus,$envkey);
                   7688:     if ($context eq 'requestauthor') {
                   7689:         $envkey = $context;
                   7690:     } else {
                   7691:         $envkey = $context.'.'.$tool;
                   7692:     }
1.976     raeburn  7693: 
1.985     raeburn  7694:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7695:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7696:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7697:         $inststatus = $env{'environment.inststatus'};
                   7698:     } else {
1.1084    raeburn  7699:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7700:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7701:             $inststatus = $userenvref->{'inststatus'};
                   7702:         } else {
1.1172.2.9  raeburn  7703:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7704:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7705:             $inststatus = $userenv{'inststatus'};
                   7706:         }
1.976     raeburn  7707:     }
                   7708: 
                   7709:     if ($toolstatus ne '') {
                   7710:         if ($toolstatus) {
                   7711:             $access = 1;
                   7712:         } else {
                   7713:             $access = 0;
                   7714:         }
                   7715:         return $access;
                   7716:     }
                   7717: 
1.1084    raeburn  7718:     my ($is_adv,%domdef);
                   7719:     if (ref($is_advref) eq 'HASH') {
                   7720:         $is_adv = $is_advref->{'is_adv'};
                   7721:     } else {
                   7722:         $is_adv = &is_advanced_user($udom,$uname);
                   7723:     }
                   7724:     if (ref($domdefref) eq 'HASH') {
                   7725:         %domdef = %{$domdefref};
                   7726:     } else {
                   7727:         %domdef = &get_domain_defaults($udom);
                   7728:     }
1.976     raeburn  7729:     if (ref($domdef{$tool}) eq 'HASH') {
                   7730:         if ($is_adv) {
                   7731:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7732:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7733:                     $access = 1;
                   7734:                 } else {
                   7735:                     $access = 0;
                   7736:                 }
                   7737:                 return $access;
                   7738:             }
                   7739:         }
                   7740:         if ($inststatus ne '') {
                   7741:             my ($hasaccess,$hasnoaccess);
                   7742:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7743:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7744:                     if ($domdef{$tool}{$affiliation}) {
                   7745:                         $hasaccess = 1;
                   7746:                     } else {
                   7747:                         $hasnoaccess = 1;
                   7748:                     }
                   7749:                 }
                   7750:             }
                   7751:             if ($hasaccess || $hasnoaccess) {
                   7752:                 if ($hasaccess) {
                   7753:                     $access = 1;
                   7754:                 } elsif ($hasnoaccess) {
                   7755:                     $access = 0; 
                   7756:                 }
                   7757:                 return $access;
                   7758:             }
                   7759:         } else {
                   7760:             if ($domdef{$tool}{'default'} ne '') {
                   7761:                 if ($domdef{$tool}{'default'}) {
                   7762:                     $access = 1;
                   7763:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7764:                     $access = 0;
                   7765:                 }
                   7766:                 return $access;
                   7767:             }
                   7768:         }
                   7769:     } else {
1.1172.2.6  raeburn  7770:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7771:             $access = 1;
                   7772:         } else {
                   7773:             $access = 0;
                   7774:         }
1.976     raeburn  7775:         return $access;
                   7776:     }
                   7777: }
                   7778: 
1.1050    raeburn  7779: sub is_course_owner {
                   7780:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7781:     if (($udom eq '') || ($uname eq '')) {
                   7782:         $udom = $env{'user.domain'};
                   7783:         $uname = $env{'user.name'};
                   7784:     }
                   7785:     unless (($udom eq '') || ($uname eq '')) {
                   7786:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7787:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7788:                 return 1;
                   7789:             } else {
                   7790:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7791:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7792:                     return 1;
                   7793:                 }
                   7794:             }
                   7795:         }
                   7796:     }
                   7797:     return;
                   7798: }
                   7799: 
1.976     raeburn  7800: sub is_advanced_user {
                   7801:     my ($udom,$uname) = @_;
1.1085    raeburn  7802:     if ($udom ne '' && $uname ne '') {
                   7803:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7804:             if (wantarray) {
                   7805:                 return ($env{'user.adv'},$env{'user.author'});
                   7806:             } else {
                   7807:                 return $env{'user.adv'};
                   7808:             }
1.1085    raeburn  7809:         }
                   7810:     }
1.976     raeburn  7811:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7812:     my %allroles;
1.1128    raeburn  7813:     my ($is_adv,$is_author);
1.976     raeburn  7814:     foreach my $role (keys(%roleshash)) {
                   7815:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7816:         my $area = '/'.$tdomain.'/'.$trest;
                   7817:         if ($sec ne '') {
                   7818:             $area .= '/'.$sec;
                   7819:         }
                   7820:         if (($area ne '') && ($trole ne '')) {
                   7821:             my $spec=$trole.'.'.$area;
                   7822:             if ($trole =~ /^cr\//) {
                   7823:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7824:             } elsif ($trole ne 'gr') {
                   7825:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7826:             }
1.1128    raeburn  7827:             if ($trole eq 'au') {
                   7828:                 $is_author = 1;
                   7829:             }
1.976     raeburn  7830:         }
                   7831:     }
                   7832:     foreach my $role (keys(%allroles)) {
                   7833:         last if ($is_adv);
                   7834:         foreach my $item (split(/:/,$allroles{$role})) {
                   7835:             if ($item ne '') {
                   7836:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7837:                 if ($privilege eq 'adv') {
                   7838:                     $is_adv = 1;
                   7839:                     last;
                   7840:                 }
                   7841:             }
                   7842:         }
                   7843:     }
1.1128    raeburn  7844:     if (wantarray) {
                   7845:         return ($is_adv,$is_author);
                   7846:     }
1.976     raeburn  7847:     return $is_adv;
                   7848: }
1.798     raeburn  7849: 
1.1035    raeburn  7850: sub check_can_request {
1.1036    raeburn  7851:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7852:     my $canreq = 0;
                   7853:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7854:     my @options = ('approval','validate','autolimit');
                   7855:     my $optregex = join('|',@options);
                   7856:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7857:         foreach my $type (@{$types}) {
                   7858:             if (&usertools_access($env{'user.name'},
                   7859:                                   $env{'user.domain'},
                   7860:                                   $type,undef,'requestcourses')) {
                   7861:                 $canreq ++;
1.1036    raeburn  7862:                 if (ref($request_domains) eq 'HASH') {
                   7863:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7864:                 }
1.1035    raeburn  7865:                 if ($dom eq $env{'user.domain'}) {
                   7866:                     $can_request->{$type} = 1;
                   7867:                 }
                   7868:             }
                   7869:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7870:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7871:                 if (@curr > 0) {
1.1036    raeburn  7872:                     foreach my $item (@curr) {
                   7873:                         if (ref($request_domains) eq 'HASH') {
                   7874:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7875:                             if ($otherdom ne '') {
                   7876:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7877:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7878:                                         push(@{$request_domains->{$type}},$otherdom);
                   7879:                                     }
                   7880:                                 } else {
                   7881:                                     push(@{$request_domains->{$type}},$otherdom);
                   7882:                                 }
                   7883:                             }
                   7884:                         }
                   7885:                     }
                   7886:                     unless($dom eq $env{'user.domain'}) {
                   7887:                         $canreq ++;
1.1035    raeburn  7888:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7889:                             $can_request->{$type} = 1;
                   7890:                         }
                   7891:                     }
                   7892:                 }
                   7893:             }
                   7894:         }
                   7895:     }
                   7896:     return $canreq;
                   7897: }
                   7898: 
1.341     www      7899: # ---------------------------------------------- Custom access rule evaluation
                   7900: 
                   7901: sub customaccess {
                   7902:     my ($priv,$uri)=@_;
1.807     albertel 7903:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7904:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7905:     $udom = &LONCAPA::clean_domain($udom);
                   7906:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7907:     my $access=0;
1.800     albertel 7908:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7909: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7910: 	if ($type eq 'user') {
                   7911: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7912: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7913: 		if ($tdom) {
                   7914: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7915: 		}
1.896     albertel 7916: 		if ($tuname) {
                   7917: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7918: 		}
                   7919: 		$access=($effect eq 'allow');
                   7920: 		last;
                   7921: 	    }
                   7922: 	} else {
                   7923: 	    if ($role) {
                   7924: 		if ($role ne $urole) { next; }
                   7925: 	    }
                   7926: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7927: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7928: 		if ($tdom) {
                   7929: 		    if ($tdom ne $udom) { next; }
                   7930: 		}
                   7931: 		if ($tcrs) {
                   7932: 		    if ($tcrs ne $ucrs) { next; }
                   7933: 		}
                   7934: 		if ($tsec) {
                   7935: 		    if ($tsec ne $usec) { next; }
                   7936: 		}
                   7937: 		$access=($effect eq 'allow');
                   7938: 		last;
                   7939: 	    }
                   7940: 	    if ($realm eq '' && $role eq '') {
                   7941: 		$access=($effect eq 'allow');
                   7942: 	    }
1.402     bowersj2 7943: 	}
1.341     www      7944:     }
                   7945:     return $access;
                   7946: }
                   7947: 
1.103     harris41 7948: # ------------------------------------------------- Check for a user privilege
1.12      www      7949: 
                   7950: sub allowed {
1.1172.2.146.  .1(raebu 7951:22):     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
1.705     albertel 7952:     my $ver_orguri=$uri;
1.439     www      7953:     $uri=&deversion($uri);
1.152     www      7954:     my $orguri=$uri;
1.52      www      7955:     $uri=&declutter($uri);
1.809     raeburn  7956: 
1.810     raeburn  7957:     if ($priv eq 'evb') {
1.1172.2.146.  .3(raebu 7958:22): # Evade communication block restrictions for specified role in a course or domain
1.810     raeburn  7959:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7960:             return $1;
                   7961:         } else {
                   7962:             return;
                   7963:         }
                   7964:     }
                   7965: 
1.620     albertel 7966:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7967: # Free bre access to adm and meta resources
1.1172.2.146.  .1(raebu 7968:22):     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
1.769     albertel 7969: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7970: 	&& ($priv eq 'bre')) {
1.14      www      7971: 	return 'F';
1.159     www      7972:     }
                   7973: 
1.545     banghart 7974: # Free bre access to user's own portfolio contents
1.714     raeburn  7975:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7976:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7977: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7978:         my %setters;
1.1172.2.142  raeburn  7979:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   7980:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   7981:         if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  7982:             return 'B';
                   7983:         } else {
                   7984:             return 'F';
                   7985:         }
1.545     banghart 7986:     }
                   7987: 
1.762     raeburn  7988: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7989:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7990:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7991:         if (exists($env{'request.course.id'})) {
                   7992:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7993:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7994:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7995:                 my $courseprivid=$env{'request.course.id'};
                   7996:                 $courseprivid=~s/\_/\//;
                   7997:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7998:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7999:                     return $1; 
1.762     raeburn  8000:                 } else {
                   8001:                     if ($env{'request.course.sec'}) {
                   8002:                         $courseprivid.='/'.$env{'request.course.sec'};
                   8003:                     }
                   8004:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   8005:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   8006:                         return $2;
                   8007:                     }
1.714     raeburn  8008:                 }
                   8009:             }
                   8010:         }
                   8011:     }
                   8012: 
1.159     www      8013: # Free bre to public access
                   8014: 
                   8015:     if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8016:22):         my $copyright;
                   8017:22):         unless ($uri =~ /ext\.tool/) {
                   8018:22):             $copyright=&metadata($uri,'copyright');
                   8019:22):         }
1.620     albertel 8020: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      8021:            return 'F'; 
                   8022:         }
1.238     www      8023:         if ($copyright eq 'priv') {
                   8024:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8025: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      8026: 		return '';
                   8027:             }
                   8028:         }
                   8029:         if ($copyright eq 'domain') {
                   8030:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8031: 	    unless (($env{'user.domain'} eq $1) ||
                   8032:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      8033: 		return '';
                   8034:             }
1.262     matthew  8035:         }
1.620     albertel 8036:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  8037:             # Library role, so allow browsing of resources in this domain.
                   8038:             return 'F';
1.238     www      8039:         }
1.341     www      8040:         if ($copyright eq 'custom') {
                   8041: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   8042:         }
1.14      www      8043:     }
1.264     matthew  8044:     # Domain coordinator is trying to create a course
1.620     albertel 8045:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  8046:         # uri is the requested domain in this case.
                   8047:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  8048:         # a role of dc for the domain in question.
1.620     albertel 8049:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  8050:     }
1.29      www      8051: 
1.52      www      8052:     my $thisallowed='';
                   8053:     my $statecond=0;
                   8054:     my $courseprivid='';
                   8055: 
1.1039    raeburn  8056:     my $ownaccess;
1.1043    raeburn  8057:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  8058:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   8059:         if ($uri eq '') {
                   8060:             $ownaccess = 1;
                   8061:         } else {
                   8062:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   8063:                 my $udom = $env{'user.domain'};
                   8064:                 my $uname = $env{'user.name'};
                   8065:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   8066:                     $ownaccess = 1;
1.1040    raeburn  8067:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  8068:                     unless ($uri =~ m{\.\./}) {
                   8069:                         $ownaccess = 1;
                   8070:                     }
                   8071:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   8072:                     my $now = time;
                   8073:                     if ($uri =~ m{^([^/]+)/?$}) {
                   8074:                         my $adom = $1;
                   8075:                         foreach my $key (keys(%env)) {
1.1042    raeburn  8076:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1172.2.142  raeburn  8077:                                 my ($start,$end) = split(/\./,$env{$key});
                   8078:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1039    raeburn  8079:                                     $ownaccess = 1;
                   8080:                                     last;
                   8081:                                 }
                   8082:                             }
                   8083:                         }
                   8084:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8085:                         my $adom = $1;
                   8086:                         my $aname = $2;
1.1042    raeburn  8087:                         foreach my $role ('ca','aa') { 
                   8088:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8089:                                 my ($start,$end) =
1.1172.2.142  raeburn  8090:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
                   8091:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1042    raeburn  8092:                                     $ownaccess = 1;
                   8093:                                     last;
                   8094:                                 }
1.1039    raeburn  8095:                             }
                   8096:                         }
                   8097:                     }
                   8098:                 }
                   8099:             }
                   8100:         }
                   8101:     }
                   8102: 
1.52      www      8103: # Course
                   8104: 
1.620     albertel 8105:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8106:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8107:             $thisallowed.=$1;
                   8108:         }
1.52      www      8109:     }
1.29      www      8110: 
1.52      www      8111: # Domain
                   8112: 
1.620     albertel 8113:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8114:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8115:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8116:             $thisallowed.=$1;
                   8117:         }
1.12      www      8118:     }
1.52      www      8119: 
1.1141    raeburn  8120: # User who is not author or co-author might still be able to edit
                   8121: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8122:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8123:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8124:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8125:             $thisallowed.=$1;
                   8126:         }
                   8127:     }
                   8128: 
1.52      www      8129: # Course: uri itself is a course
1.66      www      8130:     my $courseuri=$uri;
                   8131:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8132:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8133: 
1.620     albertel 8134:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8135:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  8136:         if ($priv eq 'mip') {
                   8137:             my $rem = $1;
                   8138:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8139:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8140:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8141:                 if ($cdom ne '') {
                   8142:                     my %passwdconf = &get_passwdconf($cdom);
                   8143:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8144:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8145:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8146:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8147:                                 unless (@inststatuses) {
                   8148:                                     @inststatuses = ('default');
                   8149:                                 }
                   8150:                                 foreach my $status (@inststatuses) {
                   8151:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8152:                                         $thisallowed.=$rem;
                   8153:                                     }
                   8154:                                 }
                   8155:                             }
                   8156:                         }
                   8157:                     }
                   8158:                 }
                   8159:             }
                   8160:         } else {
                   8161:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8162:                 $thisallowed.=$1;
                   8163:             }
1.1039    raeburn  8164:         }
1.12      www      8165:     }
1.29      www      8166: 
1.665     albertel 8167: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8168: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8169:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8170: 	$thisallowed='';
1.671     raeburn  8171:         my ($match)=&is_on_map($uri);
                   8172:         if ($match) {
                   8173:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8174:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  8175:                 my $value = $1;
1.1172.2.146.  .1(raebu 8176:22):                 my $deeplinkblock;
                   8177:22):                 unless ($nodeeplinkcheck) {
                   8178:22):                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8179:22):                 }
                   8180:22):                 if ($deeplinkblock) {
                   8181:22):                     $thisallowed='D';
                   8182:22):                 } elsif ($noblockcheck) {
1.1172.2.65  raeburn  8183:                     $thisallowed.=$value;
1.1162    raeburn  8184:                 } else {
1.1172.2.126  raeburn  8185:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8186:                     if (@blockers > 0) {
                   8187:                         $thisallowed = 'B';
                   8188:                     } else {
                   8189:                         $thisallowed.=$value;
                   8190:                     }
1.1162    raeburn  8191:                 }
1.671     raeburn  8192:             }
                   8193:         } else {
1.705     albertel 8194:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8195:             if ($refuri) {
                   8196:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8197:                     $thisallowed='F';
1.671     raeburn  8198:                 } else {
                   8199:                     $refuri=&declutter($refuri);
                   8200:                     my ($match) = &is_on_map($refuri);
                   8201:                     if ($match) {
1.1172.2.146.  .1(raebu 8202:22):                         my $deeplinkblock;
                   8203:22):                         unless ($nodeeplinkcheck) {
                   8204:22):                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8205:22):                         }
                   8206:22):                         if ($deeplinkblock) {
                   8207:22):                             $thisallowed='D';
                   8208:22):                         } elsif ($noblockcheck) {
1.1162    raeburn  8209:                             $thisallowed='F';
1.1172.2.65  raeburn  8210:                         } else {
1.1172.2.127  raeburn  8211:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8212:                             if (@blockers > 0) {
                   8213:                                 $thisallowed = 'B';
                   8214:                             } else {
                   8215:                                 $thisallowed='F';
                   8216:                             }
1.1162    raeburn  8217:                         }
1.671     raeburn  8218:                     }
1.669     raeburn  8219:                 }
1.671     raeburn  8220:             }
                   8221:         }
1.314     www      8222:     }
1.492     albertel 8223: 
1.766     albertel 8224:     if ($priv eq 'bre'
                   8225: 	&& $thisallowed ne 'F' 
                   8226: 	&& $thisallowed ne '2'
                   8227: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8228: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8229:     }
                   8230:     
1.52      www      8231: # Full access at system, domain or course-wide level? Exit.
1.29      www      8232:     if ($thisallowed=~/F/) {
                   8233: 	return 'F';
                   8234:     }
                   8235: 
1.52      www      8236: # If this is generating or modifying users, exit with special codes
1.29      www      8237: 
1.643     www      8238:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8239: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8240: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8241: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8242: 	    unless ($auname) { return $thisallowed; }
                   8243: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8244: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8245: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8246: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8247: 	}
1.52      www      8248: 	return $thisallowed;
                   8249:     }
                   8250: #
1.103     harris41 8251: # Gathered so far: system, domain and course wide privileges
1.52      www      8252: #
                   8253: # Course: See if uri or referer is an individual resource that is part of 
                   8254: # the course
                   8255: 
1.620     albertel 8256:     if ($env{'request.course.id'}) {
1.232     www      8257: 
1.1172.2.115  raeburn  8258: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8259: 
                   8260:         if ($priv eq 'mip') {
                   8261:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8262:                 return $thisallowed;
                   8263:             } else {
                   8264:                 return '';
                   8265:             }
                   8266:         }
                   8267: 
1.620     albertel 8268:        $courseprivid=$env{'request.course.id'};
                   8269:        if ($env{'request.course.sec'}) {
                   8270:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8271:        }
                   8272:        $courseprivid=~s/\_/\//;
                   8273:        my $checkreferer=1;
1.232     www      8274:        my ($match,$cond)=&is_on_map($uri);
                   8275:        if ($match) {
                   8276:            $statecond=$cond;
1.620     albertel 8277:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8278:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8279:                my $value = $1;
                   8280:                if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8281:22):                    my $deeplinkblock;
                   8282:22):                    unless ($nodeeplinkcheck) {
                   8283:22):                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8284:22):                    }
                   8285:22):                    if ($deeplinkblock) {
                   8286:22):                        $thisallowed = 'D';
                   8287:22):                    } elsif ($noblockcheck) {
1.1162    raeburn  8288:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8289:                    } else {
1.1172.2.126  raeburn  8290:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8291:                        if (@blockers > 0) {
                   8292:                            $thisallowed = 'B';
                   8293:                        } else {
                   8294:                            $thisallowed.=$value;
                   8295:                        }
1.1162    raeburn  8296:                    }
                   8297:                } else {
                   8298:                    $thisallowed.=$value;
                   8299:                }
1.52      www      8300:                $checkreferer=0;
                   8301:            }
1.29      www      8302:        }
1.1172.2.126  raeburn  8303: 
1.148     www      8304:        if ($checkreferer) {
1.620     albertel 8305: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8306:             unless ($refuri) {
1.800     albertel 8307:                 foreach my $key (keys(%env)) {
                   8308: 		    if ($key=~/^httpref\..*\*/) {
                   8309: 			my $pattern=$key;
1.156     www      8310:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8311:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8312:                         $pattern=~s/\//\\\//g;
1.152     www      8313:                         if ($orguri=~/$pattern/) {
1.800     albertel 8314: 			    $refuri=$env{$key};
1.148     www      8315:                         }
                   8316:                     }
1.191     harris41 8317:                 }
1.148     www      8318:             }
1.232     www      8319: 
1.148     www      8320:          if ($refuri) { 
1.152     www      8321: 	  $refuri=&declutter($refuri);
1.232     www      8322:           my ($match,$cond)=&is_on_map($refuri);
                   8323:             if ($match) {
                   8324:               my $refstatecond=$cond;
1.620     albertel 8325:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8326:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8327:                   my $value = $1;
                   8328:                   if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8329:22):                       my $deeplinkblock;
                   8330:22):                       unless ($nodeeplinkcheck) {
                   8331:22):                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8332:22):                       }
                   8333:22):                       if ($deeplinkblock) {
                   8334:22):                           $thisallowed = 'D';
                   8335:22):                       } elsif ($noblockcheck) {
1.1162    raeburn  8336:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8337:                       } else {
1.1172.2.127  raeburn  8338:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8339:                           if (@blockers > 0) {
                   8340:                               $thisallowed = 'B';
                   8341:                           } else {
                   8342:                               $thisallowed.=$value;
                   8343:                           }
1.1162    raeburn  8344:                       }
                   8345:                   } else {
                   8346:                       $thisallowed.=$value;
                   8347:                   }
1.53      www      8348:                   $uri=$refuri;
                   8349:                   $statecond=$refstatecond;
1.52      www      8350:               }
                   8351:           }
1.148     www      8352:         }
1.29      www      8353:        }
1.52      www      8354:    }
1.29      www      8355: 
1.52      www      8356: #
1.103     harris41 8357: # Gathered now: all privileges that could apply, and condition number
1.52      www      8358: # 
                   8359: #
                   8360: # Full or no access?
                   8361: #
1.29      www      8362: 
1.52      www      8363:     if ($thisallowed=~/F/) {
                   8364: 	return 'F';
                   8365:     }
1.29      www      8366: 
1.52      www      8367:     unless ($thisallowed) {
                   8368:         return '';
                   8369:     }
1.29      www      8370: 
1.52      www      8371: # Restrictions exist, deal with them
                   8372: #
                   8373: #   C:according to course preferences
                   8374: #   R:according to resource settings
                   8375: #   L:unless locked
                   8376: #   X:according to user session state
                   8377: #
                   8378: 
                   8379: # Possibly locked functionality, check all courses
1.1172.2.142  raeburn  8380: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54      www      8381: # Locks might take effect only after 10 minutes cache expiration for other
1.1172.2.142  raeburn  8382: # courses, and 2 minutes for current course, in which user has st or ta role
                   8383: # which is neither expired nor a future role (unless current course).
1.52      www      8384: 
1.1172.2.142  raeburn  8385:     my ($needlockcheck,$now,$crsonly);
1.52      www      8386:     if ($thisallowed=~/L/) {
1.1172.2.142  raeburn  8387:         $now = time;
                   8388:         if ($priv eq 'bre') {
                   8389:             if ($uri ne '') {
                   8390:                 if ($orguri =~ m{^/+res/}) {
                   8391:                     if ($uri =~ m{^lib/templates/}) {
                   8392:                         if ($env{'request.course.id'}) {
                   8393:                             $crsonly = 1;
                   8394:                             $needlockcheck = 1;
                   8395:                         }
                   8396:                     } else {
                   8397:                         $needlockcheck = 1;
                   8398:                     }
                   8399:                 } elsif ($env{'request.course.id'}) {
                   8400:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
                   8401:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
                   8402:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
                   8403:                         $crsonly = 1;
                   8404:                     }
                   8405:                     $needlockcheck = 1;
                   8406:                 }
                   8407:             }
                   8408:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
                   8409:             $needlockcheck = 1;
                   8410:         }
                   8411:     }
                   8412:     if ($needlockcheck) {
                   8413:         foreach my $envkey (keys(%env)) {
1.54      www      8414:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8415:                my $courseid=$2;
                   8416:                my $roleid=$1.'.'.$2;
1.92      www      8417:                $courseid=~s/^\///;
1.1172.2.142  raeburn  8418:                unless ($env{'request.role'} eq $roleid) {
                   8419:                    my ($start,$end) = split(/\./,$env{$envkey});
                   8420:                    next unless (($now >= $start) && (!$end || $end > $now));
                   8421:                }
1.54      www      8422:                my $expiretime=600;
1.620     albertel 8423:                if ($env{'request.role'} eq $roleid) {
1.54      www      8424: 		  $expiretime=120;
                   8425:                }
                   8426: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8427:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8428:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8429: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8430:                }
1.620     albertel 8431:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8432:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8433: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8434:                        &log($env{'user.domain'},$env{'user.name'},
                   8435:                             $env{'user.home'},
1.57      www      8436:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8437:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8438:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8439: 		       return '';
                   8440:                    }
                   8441:                }
1.620     albertel 8442:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8443:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1172.2.142  raeburn  8444: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620     albertel 8445:                        &log($env{'user.domain'},$env{'user.name'},
                   8446:                             $env{'user.home'},
1.57      www      8447:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8448:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8449:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8450: 		       return '';
                   8451:                    }
                   8452:                }
                   8453: 	   }
1.29      www      8454:        }
1.52      www      8455:     }
1.1172.2.126  raeburn  8456: 
1.52      www      8457: #
                   8458: # Rest of the restrictions depend on selected course
                   8459: #
                   8460: 
1.620     albertel 8461:     unless ($env{'request.course.id'}) {
1.766     albertel 8462: 	if ($thisallowed eq 'A') {
                   8463: 	    return 'A';
1.814     raeburn  8464:         } elsif ($thisallowed eq 'B') {
                   8465:             return 'B';
1.766     albertel 8466: 	} else {
                   8467: 	    return '1';
                   8468: 	}
1.52      www      8469:     }
1.29      www      8470: 
1.52      www      8471: #
                   8472: # Now user is definitely in a course
                   8473: #
1.53      www      8474: 
                   8475: 
                   8476: # Course preferences
                   8477: 
                   8478:    if ($thisallowed=~/C/) {
1.620     albertel 8479:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8480:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8481:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8482: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8483: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8484: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8485: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8486: 			$env{'request.course.id'});
                   8487: 	   }
1.237     www      8488:            return '';
                   8489:        }
                   8490: 
1.620     albertel 8491:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8492: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8493: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8494: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8495: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8496: 			$env{'request.course.id'});
                   8497: 	   }
1.54      www      8498:            return '';
                   8499:        }
1.53      www      8500:    }
                   8501: 
                   8502: # Resource preferences
                   8503: 
                   8504:    if ($thisallowed=~/R/) {
1.620     albertel 8505:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8506:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8507: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8508: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8509: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8510: 	   }
                   8511: 	   return '';
1.54      www      8512:        }
1.53      www      8513:    }
1.30      www      8514: 
1.1172.2.146.  .1(raebu 8515:22): # Restricted for deeplinked session?
                   8516:22): 
                   8517:22):     if ($env{'request.deeplink.login'}) {
                   8518:22):         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
                   8519:22):             if (!$symb) { $symb=&symbread($uri,1); }
                   8520:22):             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
                   8521:22):                 return '';
                   8522:22):             }
                   8523:22):         }
                   8524:22):     }
                   8525:22): 
1.246     www      8526: # Restricted by state or randomout?
1.30      www      8527: 
1.52      www      8528:    if ($thisallowed=~/X/) {
1.620     albertel 8529:       if ($env{'acc.randomout'}) {
1.579     albertel 8530: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8531:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8532:             return ''; 
                   8533:          }
1.247     www      8534:       }
                   8535:       if (&condval($statecond)) {
1.52      www      8536: 	 return '2';
                   8537:       } else {
                   8538:          return '';
                   8539:       }
                   8540:    }
1.30      www      8541: 
1.766     albertel 8542:     if ($thisallowed eq 'A') {
                   8543: 	return 'A';
1.814     raeburn  8544:     } elsif ($thisallowed eq 'B') {
                   8545:         return 'B';
1.1172.2.146.  .1(raebu 8546:22):     } elsif ($thisallowed eq 'D') {
                   8547:22):         return 'D';
1.766     albertel 8548:     }
1.52      www      8549:    return 'F';
1.232     www      8550: }
1.1162    raeburn  8551: 
1.1172.2.13  raeburn  8552: # ------------------------------------------- Check construction space access
                   8553: 
                   8554: sub constructaccess {
                   8555:     my ($url,$setpriv)=@_;
                   8556: 
                   8557: # We do not allow editing of previous versions of files
                   8558:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8559: 
                   8560: # Get username and domain from URL
                   8561:     my ($ownername,$ownerdomain,$ownerhome);
                   8562: 
                   8563:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8564:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8565: 
                   8566: # The URL does not really point to any authorspace, forget it
                   8567:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8568: 
                   8569: # Now we need to see if the user has access to the authorspace of
                   8570: # $ownername at $ownerdomain
                   8571: 
                   8572:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8573: # Real author for this?
                   8574:        $ownerhome = $env{'user.home'};
                   8575:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8576:           return ($ownername,$ownerdomain,$ownerhome);
                   8577:        }
                   8578:     } else {
                   8579: # Co-author for this?
                   8580:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8581:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8582:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8583:             return ($ownername,$ownerdomain,$ownerhome);
                   8584:         }
                   8585:     }
                   8586: 
                   8587: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8588: # we might as well leave
                   8589:    unless ($setpriv) { return ''; }
                   8590: 
                   8591: # Backdoor access?
                   8592:     my $allowed=&allowed('eco',$ownerdomain);
                   8593: # Nope
                   8594:     unless ($allowed) { return ''; }
                   8595: # Looks like we may have access, but could be locked by the owner of the construction space
                   8596:     if ($allowed eq 'U') {
                   8597:         my %blocked=&get('environment',['domcoord.author'],
                   8598:                          $ownerdomain,$ownername);
                   8599: # Is blocked by owner
                   8600:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8601:     }
                   8602:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8603: # Grant temporary access
                   8604:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8605:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8606:         if (!$update) { $update = $then; }
                   8607:         my $refresh=$env{'user.refresh.time'};
                   8608:         if (!$refresh) { $refresh = $update; }
                   8609:         my $now = time;
                   8610:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8611:                            $now,'ca','constructaccess');
                   8612:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8613:         return($ownername,$ownerdomain,$ownerhome);
                   8614:     }
                   8615: # No business here
                   8616:     return '';
                   8617: }
                   8618: 
1.1172.2.66  raeburn  8619: # ----------------------------------------------------------- Content Blocking
                   8620: 
                   8621: {
                   8622: # Caches for faster Course Contents display where content blocking
                   8623: # is in operation (i.e., interval param set) for timed quiz.
                   8624: #
                   8625: # User for whom data are being temporarily cached.
                   8626: my $cacheduser='';
1.1172.2.126  raeburn  8627: # Course for which data are being temporarily cached.
                   8628: my $cachedcid='';
1.1172.2.66  raeburn  8629: # Cached blockers for this user (a hash of blocking items).
                   8630: my %cachedblockers=();
                   8631: # When the data were last cached.
                   8632: my $cachedlast='';
                   8633: 
                   8634: sub load_all_blockers {
1.1172.2.128  raeburn  8635:     my ($uname,$udom)=@_;
1.1172.2.66  raeburn  8636:     if (($uname ne '') && ($udom ne '')) {
                   8637:         if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126  raeburn  8638:             ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128  raeburn  8639:             (abs($cachedlast-time)<5)) {
1.1172.2.66  raeburn  8640:             return;
                   8641:         }
                   8642:     }
                   8643:     $cachedlast=time;
                   8644:     $cacheduser=$uname.':'.$udom;
1.1172.2.126  raeburn  8645:     $cachedcid=$env{'request.course.id'};
1.1172.2.128  raeburn  8646:     %cachedblockers = &get_commblock_resources();
1.1172.2.126  raeburn  8647:     return;
1.1172.2.66  raeburn  8648: }
                   8649: 
1.1162    raeburn  8650: sub get_comm_blocks {
                   8651:     my ($cdom,$cnum) = @_;
                   8652:     if ($cdom eq '' || $cnum eq '') {
                   8653:         return unless ($env{'request.course.id'});
                   8654:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8655:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8656:     }
                   8657:     my %commblocks;
                   8658:     my $hashid=$cdom.'_'.$cnum;
                   8659:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8660:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8661:         %commblocks = %{$blocksref};
                   8662:     } else {
                   8663:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8664:         my $cachetime = 600;
                   8665:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8666:     }
                   8667:     return %commblocks;
                   8668: }
                   8669: 
1.1172.2.66  raeburn  8670: sub get_commblock_resources {
                   8671:     my ($blocks) = @_;
                   8672:     my %blockers = ();
                   8673:     return %blockers unless ($env{'request.course.id'});
1.1172.2.142  raeburn  8674:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8675:     if ($env{'request.course.sec'}) {
                   8676:         $courseurl .= '/'.$env{'request.course.sec'};
                   8677:     }
                   8678:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162    raeburn  8679:     my %commblocks;
                   8680:     if (ref($blocks) eq 'HASH') {
                   8681:         %commblocks = %{$blocks};
                   8682:     } else {
                   8683:         %commblocks = &get_comm_blocks();
                   8684:     }
1.1172.2.66  raeburn  8685:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8686:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8687:     return %blockers unless (ref($navmap));
                   8688:     my $now = time;
1.1162    raeburn  8689:     foreach my $block (keys(%commblocks)) {
                   8690:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8691:             my ($start,$end) = ($1,$2);
                   8692:             if ($start <= $now && $end >= $now) {
                   8693:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8694:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8695:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8696:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8697:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8698:                             }
                   8699:                         }
                   8700:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8701:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8702:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8703:                             }
                   8704:                         }
                   8705:                     }
                   8706:                 }
                   8707:             }
                   8708:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8709:             my $item = $1;
                   8710:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8711:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.142  raeburn  8712:                     my (@interval,$mapname);
1.1172.2.66  raeburn  8713:                     my $type = 'map';
                   8714:                     if ($item eq 'course') {
                   8715:                         $type = 'course';
                   8716:                         @interval=&EXT("resource.0.interval");
                   8717:                     } else {
                   8718:                         if ($item =~ /___\d+___/) {
                   8719:                             $type = 'resource';
                   8720:                             @interval=&EXT("resource.0.interval",$item);
1.1162    raeburn  8721:                         } else {
1.1172.2.142  raeburn  8722:                             $mapname = &deversion($item);
                   8723:                             if (ref($navmap)) {
                   8724:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
                   8725:                                 @interval = ($timelimit,'map');
1.1162    raeburn  8726:                             }
                   8727:                         }
1.1172.2.66  raeburn  8728:                     }
1.1172.2.146.  .1(raebu 8729:22):                     if ($interval[0] =~ /^(\d+)/) {
                   8730:22):                         my $timelimit = $1;
1.1172.2.66  raeburn  8731:                         my $first_access;
                   8732:                         if ($type eq 'resource') {
                   8733:                             $first_access=&get_first_access($interval[1],$item);
                   8734:                         } elsif ($type eq 'map') {
                   8735:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8736:                         } else {
                   8737:                             $first_access=&get_first_access($interval[1]);
                   8738:                         }
                   8739:                         if ($first_access) {
1.1172.2.146.  .1(raebu 8740:22):                             my $timesup = $first_access+$timelimit;
1.1172.2.66  raeburn  8741:                             if ($timesup > $now) {
                   8742:                                 my $activeblock;
1.1172.2.142  raeburn  8743:                                 if ($type eq 'resource') {
                   8744:                                     if (ref($navmap)) {
                   8745:                                         my $res = $navmap->getBySymb($item);
                   8746:                                         if ($res->answerable()) {
                   8747:                                             $activeblock = 1;
                   8748:                                         }
                   8749:                                     }
                   8750:                                 } elsif ($type eq 'map') {
                   8751:                                     my $mapsymb = &symbread($mapname,1);
                   8752:                                     if (($mapsymb) && (ref($navmap))) {
                   8753:                                         my $mapres = $navmap->getBySymb($mapsymb);
                   8754:                                         if (ref($mapres)) {
                   8755:                                             my $first = $mapres->map_start();
                   8756:                                             my $finish = $mapres->map_finish();
                   8757:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   8758:                                             if (ref($it)) {
                   8759:                                                 my $res;
                   8760:                                                 while ($res = $it->next(undef,1)) {
                   8761:                                                     next unless (ref($res));
                   8762:                                                     my $symb = $res->symb();
                   8763:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
                   8764:                                                     @interval=&EXT("resource.0.interval",$symb);
                   8765:                                                     if ($interval[1] eq 'map') {
                   8766:                                                         if ($res->answerable()) {
                   8767:                                                             $activeblock = 1;
                   8768:                                                             last;
                   8769:                                                         }
                   8770:                                                     }
                   8771:                                                 }
                   8772:                                             }
                   8773:                                         }
1.1172.2.66  raeburn  8774:                                     }
                   8775:                                 }
                   8776:                                 if ($activeblock) {
                   8777:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8778:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8779:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8780:                                          }
                   8781:                                     }
                   8782:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8783:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8784:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8785:                                         }
1.1162    raeburn  8786:                                     }
                   8787:                                 }
                   8788:                             }
                   8789:                         }
                   8790:                     }
                   8791:                 }
                   8792:             }
                   8793:         }
                   8794:     }
1.1172.2.66  raeburn  8795:     return %blockers;
1.1162    raeburn  8796: }
                   8797: 
1.1172.2.66  raeburn  8798: sub has_comm_blocking {
1.1172.2.128  raeburn  8799:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66  raeburn  8800:     my @blockers;
                   8801:     return unless ($env{'request.course.id'});
                   8802:     return unless ($priv eq 'bre');
                   8803:     return if ($env{'request.state'} eq 'construct');
1.1172.2.142  raeburn  8804:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8805:     if ($env{'request.course.sec'}) {
                   8806:         $courseurl .= '/'.$env{'request.course.sec'};
                   8807:     }
                   8808:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1172.2.128  raeburn  8809:     my %blockinfo;
                   8810:     if (ref($blocks) eq 'HASH') {
                   8811:         %blockinfo = &get_commblock_resources($blocks);
                   8812:     } else {
                   8813:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   8814:         %blockinfo = %cachedblockers;
                   8815:     }
                   8816:     return unless (keys(%blockinfo) > 0);
1.1172.2.66  raeburn  8817:     my (%possibles,@symbs);
                   8818:     if (!$symb) {
1.1172.2.128  raeburn  8819:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  8820:     }
1.1172.2.66  raeburn  8821:     if ($symb) {
                   8822:         @symbs = ($symb);
                   8823:     } elsif (keys(%possibles)) {
                   8824:         @symbs = keys(%possibles);
                   8825:     }
                   8826:     my $noblock;
                   8827:     foreach my $symb (@symbs) {
                   8828:         last if ($noblock);
                   8829:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128  raeburn  8830:         foreach my $block (keys(%blockinfo)) {
1.1172.2.66  raeburn  8831:             if ($block =~ /^firstaccess____(.+)$/) {
                   8832:                 my $item = $1;
1.1172.2.126  raeburn  8833:                 unless ($blocked) {
                   8834:                     if (($item eq $map) || ($item eq $symb)) {
                   8835:                         $noblock = 1;
                   8836:                         last;
                   8837:                     }
1.1172.2.66  raeburn  8838:                 }
1.1162    raeburn  8839:             }
1.1172.2.128  raeburn  8840:             if (ref($blockinfo{$block}) eq 'HASH') {
                   8841:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   8842:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66  raeburn  8843:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8844:                             push(@blockers,$block);
                   8845:                         }
                   8846:                     }
                   8847:                 }
1.1172.2.128  raeburn  8848:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   8849:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126  raeburn  8850:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8851:                             push(@blockers,$block);
                   8852:                         }
1.1172.2.66  raeburn  8853:                     }
                   8854:                 }
1.1162    raeburn  8855:             }
                   8856:         }
                   8857:     }
1.1172.2.126  raeburn  8858:     unless ($noblock) {
                   8859:         return @blockers;
                   8860:     }
                   8861:     return;
1.1172.2.66  raeburn  8862: }
1.1162    raeburn  8863: }
                   8864: 
1.1172.2.146.  .1(raebu 8865:22): sub deeplink_check {
                   8866:22):     my ($priv,$symb,$uri) = @_;
                   8867:22):     return unless ($env{'request.course.id'});
                   8868:22):     return unless ($priv eq 'bre');
                   8869:22):     return if ($env{'request.state'} eq 'construct');
                   8870:22):     return if ($env{'request.role.adv'});
                   8871:22):     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8872:22):     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8873:22):     my (%possibles,@symbs);
                   8874:22):     if (!$symb) {
                   8875:22):         $symb = &symbread($uri,1,1,1,\%possibles);
                   8876:22):     }
                   8877:22):     if ($symb) {
                   8878:22):         @symbs = ($symb);
                   8879:22):     } elsif (keys(%possibles)) {
                   8880:22):         @symbs = keys(%possibles);
                   8881:22):     }
                   8882:22): 
                   8883:22):     my ($deeplink_symb,$allow);
                   8884:22):     if ($env{'request.deeplink.login'}) {
                   8885:22):         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
                   8886:22):     }
                   8887:22):     foreach my $symb (@symbs) {
                   8888:22):         last if ($allow);
                   8889:22):         my $deeplink = &EXT("resource.0.deeplink",$symb);
                   8890:22):         if ($deeplink eq '') {
                   8891:22):             $allow = 1;
                   8892:22):         } else {
                   8893:22):             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
                   8894:22):             if ($state ne 'only') {
                   8895:22):                 $allow = 1;
                   8896:22):             } else {
                   8897:22):                 my $check_deeplink_entry;
                   8898:22):                 if ($protect ne 'none') {
                   8899:22):                     my ($acctype,$item) = split(/:/,$protect);
                   8900:22):                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
                   8901:22):                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
                   8902:22):                             $check_deeplink_entry = 1
                   8903:22):                         }
                   8904:22):                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
                   8905:22):                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
                   8906:22):                             $check_deeplink_entry = 1;
                   8907:22):                         }
                   8908:22):                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
                   8909:22):                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
                   8910:22):                             $check_deeplink_entry = 1;
                   8911:22):                         }
                   8912:22):                     }
                   8913:22):                 }
                   8914:22):                 if (($protect eq 'none') || ($check_deeplink_entry)) {
                   8915:22):                     if ($scope eq 'res') {
                   8916:22):                         if ($symb eq $deeplink_symb) {
                   8917:22):                             $allow = 1;
                   8918:22):                         }
                   8919:22):                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
                   8920:22):                         my ($map_from_symb,$map_from_login);
                   8921:22):                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
                   8922:22):                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   8923:22):                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
                   8924:22):                         } else {
                   8925:22):                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
                   8926:22):                         }
                   8927:22):                         if (($map_from_symb) && ($map_from_login)) {
                   8928:22):                             if ($map_from_symb eq $map_from_login) {
                   8929:22):                                 $allow = 1;
                   8930:22):                             } elsif ($scope eq 'rec') {
                   8931:22):                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
                   8932:22):                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
                   8933:22):                                     $allow = 1;
                   8934:22):                                 }
                   8935:22):                             }
                   8936:22):                         }
                   8937:22):                     }
                   8938:22):                 }
                   8939:22):             }
                   8940:22):         }
                   8941:22):     }
                   8942:22):     return if ($allow);
                   8943:22):     return 1;
                   8944:22): }
                   8945:22): 
1.1172.2.66  raeburn  8946: # -------------------------------- Deversion and split uri into path an filename
                   8947: 
1.1133    foxr     8948: #
1.1172.2.66  raeburn  8949: #   Removes the version from a URI and
1.1133    foxr     8950: #   splits it in to its filename and path to the filename.
                   8951: #   Seems like File::Basename could have done this more clearly.
                   8952: #   Parameters:
                   8953: #      $uri   - input URI
                   8954: #   Returns:
                   8955: #     Two element list consisting of 
                   8956: #     $pathname  - the URI up to and excluding the trailing /
                   8957: #     $filename  - The part of the URI following the last /
                   8958: #  NOTE:
                   8959: #    Another realization of this is simply:
                   8960: #    use File::Basename;
                   8961: #    ...
                   8962: #    $uri = shift;
                   8963: #    $filename = basename($uri);
                   8964: #    $path     = dirname($uri);
                   8965: #    return ($filename, $path);
                   8966: #
                   8967: #     The implementation below is probably faster however.
                   8968: #
1.710     albertel 8969: sub split_uri_for_cond {
                   8970:     my $uri=&deversion(&declutter(shift));
                   8971:     my @uriparts=split(/\//,$uri);
                   8972:     my $filename=pop(@uriparts);
                   8973:     my $pathname=join('/',@uriparts);
                   8974:     return ($pathname,$filename);
                   8975: }
1.232     www      8976: # --------------------------------------------------- Is a resource on the map?
                   8977: 
                   8978: sub is_on_map {
1.710     albertel 8979:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8980:     #Trying to find the conditional for the file
1.620     albertel 8981:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8982: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8983:     if ($match) {
1.289     bowersj2 8984: 	return (1,$1);
                   8985:     } else {
1.434     www      8986: 	return (0,0);
1.289     bowersj2 8987:     }
1.12      www      8988: }
                   8989: 
1.427     www      8990: # --------------------------------------------------------- Get symb from alias
                   8991: 
                   8992: sub get_symb_from_alias {
                   8993:     my $symb=shift;
                   8994:     my ($map,$resid,$url)=&decode_symb($symb);
                   8995: # Already is a symb
                   8996:     if ($url) { return $symb; }
                   8997: # Must be an alias
                   8998:     my $aliassymb='';
                   8999:     my %bighash;
1.620     albertel 9000:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      9001:                             &GDBM_READER(),0640)) {
                   9002:         my $rid=$bighash{'mapalias_'.$symb};
                   9003: 	if ($rid) {
                   9004: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 9005: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   9006: 				    $resid,$bighash{'src_'.$rid});
1.427     www      9007: 	}
                   9008:         untie %bighash;
                   9009:     }
                   9010:     return $aliassymb;
                   9011: }
                   9012: 
1.12      www      9013: # ----------------------------------------------------------------- Define Role
                   9014: 
                   9015: sub definerole {
                   9016:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  9017:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 9018:     foreach my $role (split(':',$sysrole)) {
                   9019: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9020:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   9021:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   9022: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9023:                return "refused:s:$crole&$cqual"; 
                   9024:             }
                   9025:         }
1.191     harris41 9026:     }
1.800     albertel 9027:     foreach my $role (split(':',$domrole)) {
                   9028: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9029:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   9030:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   9031: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      9032:                return "refused:d:$crole&$cqual"; 
                   9033:             }
                   9034:         }
1.191     harris41 9035:     }
1.800     albertel 9036:     foreach my $role (split(':',$courole)) {
                   9037: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9038:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   9039:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   9040: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9041:                return "refused:c:$crole&$cqual"; 
                   9042:             }
                   9043:         }
1.191     harris41 9044:     }
1.1172.2.84  raeburn  9045:     my $uhome;
                   9046:     if (($uname ne '') && ($udom ne '')) {
                   9047:         $uhome = &homeserver($uname,$udom);
                   9048:         return $uhome if ($uhome eq 'no_host');
                   9049:     } else {
                   9050:         $uname = $env{'user.name'};
                   9051:         $udom = $env{'user.domain'};
                   9052:         $uhome = $env{'user.home'};
                   9053:     }
1.620     albertel 9054:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  9055:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      9056:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  9057:     return reply($command,$uhome);
1.12      www      9058:   } else {
                   9059:     return 'refused';
                   9060:   }
1.105     harris41 9061: }
                   9062: 
                   9063: # ---------------- Make a metadata query against the network of library servers
                   9064: 
                   9065: sub metadata_query {
1.1172.2.33  raeburn  9066:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 9067:     my %rhash;
1.845     albertel 9068:     my %libserv = &all_library();
1.244     matthew  9069:     my @server_list = (defined($server_array) ? @$server_array
                   9070:                                               : keys(%libserv) );
                   9071:     for my $server (@server_list) {
1.1172.2.33  raeburn  9072:         my $domains = '';
                   9073:         if (ref($domains_hash) eq 'HASH') {
                   9074:             $domains = $domains_hash->{$server};    
                   9075:         }
1.118     harris41 9076: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  9077: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 9078: 	    $rhash{$server}=$reply;
                   9079: 	}
                   9080: 	else {
                   9081: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  9082: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 9083: 			     $server);
                   9084: 	    $rhash{$server}=$reply;
                   9085: 	}
1.112     harris41 9086:     }
1.118     harris41 9087:     return \%rhash;
1.240     www      9088: }
                   9089: 
                   9090: # ----------------------------------------- Send log queries and wait for reply
                   9091: 
                   9092: sub log_query {
                   9093:     my ($uname,$udom,$query,%filters)=@_;
                   9094:     my $uhome=&homeserver($uname,$udom);
                   9095:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 9096:     my $uhost=&hostname($uhome);
1.800     albertel 9097:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      9098:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   9099:                        $uhome);
1.479     albertel 9100:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      9101:     return get_query_reply($queryid);
                   9102: }
                   9103: 
1.818     raeburn  9104: # -------------------------- Update MySQL table for portfolio file
                   9105: 
                   9106: sub update_portfolio_table {
1.821     raeburn  9107:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  9108:     if ($group ne '') {
                   9109:         $file_name =~s /^\Q$group\E//;
                   9110:     }
1.818     raeburn  9111:     my $homeserver = &homeserver($uname,$udom);
                   9112:     my $queryid=
1.821     raeburn  9113:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   9114:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  9115:     my $reply = &get_query_reply($queryid);
                   9116:     return $reply;
                   9117: }
                   9118: 
1.899     raeburn  9119: # -------------------------- Update MySQL allusers table
                   9120: 
                   9121: sub update_allusers_table {
                   9122:     my ($uname,$udom,$names) = @_;
                   9123:     my $homeserver = &homeserver($uname,$udom);
                   9124:     my $queryid=
                   9125:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   9126:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   9127:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   9128:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   9129:                'generation='.&escape($names->{'generation'}).'%%'.
                   9130:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   9131:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  9132:     return;
1.899     raeburn  9133: }
                   9134: 
1.508     raeburn  9135: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  9136: 
                   9137: sub fetch_enrollment_query {
1.511     raeburn  9138:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  9139:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  9140:     my $maxtries = 1;
1.508     raeburn  9141:     if ($context eq 'automated') {
                   9142:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  9143:         $sleep = 2;
                   9144:         $loopmax = 100;
1.547     raeburn  9145:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  9146:     } else {
                   9147:         $homeserver = &homeserver($cnum,$dom);
                   9148:     }
1.838     albertel 9149:     my $host=&hostname($homeserver);
1.506     raeburn  9150:     my $cmd = '';
1.1000    raeburn  9151:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 9152:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  9153:     }
                   9154:     $cmd =~ s/%%$//;
                   9155:     $cmd = &escape($cmd);
                   9156:     my $query = 'fetchenrollment';
1.620     albertel 9157:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  9158:     unless ($queryid=~/^\Q$host\E\_/) { 
                   9159:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   9160:         return 'error: '.$queryid;
                   9161:     }
1.1172.2.93  raeburn  9162:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9163:     my $tries = 1;
                   9164:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  9165:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9166:         $tries ++;
                   9167:     }
1.526     raeburn  9168:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 9169:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  9170:     } else {
1.901     albertel 9171:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  9172:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 9173:             foreach my $line (@responses) {
                   9174:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  9175:                 $$replyref{$key} = $value;
                   9176:             }
                   9177:         } else {
1.1117    foxr     9178:             my $pathname = LONCAPA::tempdir();
1.800     albertel 9179:             foreach my $line (@responses) {
                   9180:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  9181:                 $$replyref{$key} = $value;
                   9182:                 if ($value > 0) {
1.800     albertel 9183:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   9184:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  9185:                         my $destname = $pathname.'/'.$filename;
                   9186:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  9187:                         if ($xml_classlist =~ /^error/) {
                   9188:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   9189:                         } else {
1.1172.2.96  raeburn  9190:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  9191:                                 print FILE &unescape($xml_classlist);
                   9192:                                 close(FILE);
1.526     raeburn  9193:                             } else {
                   9194:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  9195:                             }
                   9196:                         }
                   9197:                     }
                   9198:                 }
                   9199:             }
                   9200:         }
                   9201:         return 'ok';
                   9202:     }
                   9203:     return 'error';
                   9204: }
                   9205: 
1.242     www      9206: sub get_query_reply {
1.1172.2.79  raeburn  9207:     my ($queryid,$sleep,$loopmax) = @_;
                   9208:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9209:         $sleep = 0.2;
                   9210:     }
                   9211:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9212:         $loopmax = 100;
                   9213:     }
1.1117    foxr     9214:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9215:     my $reply='';
1.1172.2.79  raeburn  9216:     for (1..$loopmax) {
                   9217: 	sleep($sleep);
1.240     www      9218:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  9219: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9220: 		$reply = join('',<$fh>);
                   9221: 		close($fh);
1.240     www      9222: 	   } else { return 'error: reply_file_error'; }
1.242     www      9223:            return &unescape($reply);
                   9224: 	}
1.240     www      9225:     }
1.242     www      9226:     return 'timeout:'.$queryid;
1.240     www      9227: }
                   9228: 
                   9229: sub courselog_query {
1.241     www      9230: #
                   9231: # possible filters:
                   9232: # url: url or symb
                   9233: # username
                   9234: # domain
                   9235: # action: view, submit, grade
                   9236: # start: timestamp
                   9237: # end: timestamp
                   9238: #
1.240     www      9239:     my (%filters)=@_;
1.620     albertel 9240:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9241:     if ($filters{'url'}) {
                   9242: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9243:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9244:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9245:     }
1.620     albertel 9246:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9247:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9248:     return &log_query($cname,$cdom,'courselog',%filters);
                   9249: }
                   9250: 
                   9251: sub userlog_query {
1.858     raeburn  9252: #
                   9253: # possible filters:
                   9254: # action: log check role
                   9255: # start: timestamp
                   9256: # end: timestamp
                   9257: #
1.240     www      9258:     my ($uname,$udom,%filters)=@_;
                   9259:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9260: }
                   9261: 
1.506     raeburn  9262: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9263: 
                   9264: sub auto_run {
1.508     raeburn  9265:     my ($cnum,$cdom) = @_;
1.876     raeburn  9266:     my $response = 0;
                   9267:     my $settings;
                   9268:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9269:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9270:         $settings = $domconfig{'autoenroll'};
                   9271:         if ($settings->{'run'} eq '1') {
                   9272:             $response = 1;
                   9273:         }
                   9274:     } else {
1.934     raeburn  9275:         my $homeserver;
                   9276:         if (&is_course($cdom,$cnum)) {
                   9277:             $homeserver = &homeserver($cnum,$cdom);
                   9278:         } else {
                   9279:             $homeserver = &domain($cdom,'primary');
                   9280:         }
                   9281:         if ($homeserver ne 'no_host') {
                   9282:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9283:         }
1.876     raeburn  9284:     }
1.506     raeburn  9285:     return $response;
                   9286: }
1.776     albertel 9287: 
1.506     raeburn  9288: sub auto_get_sections {
1.508     raeburn  9289:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9290:     my $homeserver;
                   9291:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9292:         $homeserver = &homeserver($cnum,$cdom);
                   9293:     }
                   9294:     if (!defined($homeserver)) { 
                   9295:         if ($cdom =~ /^$match_domain$/) {
                   9296:             $homeserver = &domain($cdom,'primary');
                   9297:         }
                   9298:     }
                   9299:     my @secs;
                   9300:     if (defined($homeserver)) {
                   9301:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9302:         unless ($response eq 'refused') {
                   9303:             @secs = split(/:/,$response);
                   9304:         }
1.506     raeburn  9305:     }
                   9306:     return @secs;
                   9307: }
1.776     albertel 9308: 
1.506     raeburn  9309: sub auto_new_course {
1.1099    raeburn  9310:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9311:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9312:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9313:     return $response;
                   9314: }
1.776     albertel 9315: 
1.506     raeburn  9316: sub auto_validate_courseID {
1.508     raeburn  9317:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9318:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9319:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9320:     return $response;
                   9321: }
1.776     albertel 9322: 
1.1007    raeburn  9323: sub auto_validate_instcode {
1.1020    raeburn  9324:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9325:     my ($homeserver,$response);
                   9326:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9327:         $homeserver = &homeserver($cnum,$cdom);
                   9328:     }
                   9329:     if (!defined($homeserver)) {
                   9330:         if ($cdom =~ /^$match_domain$/) {
                   9331:             $homeserver = &domain($cdom,'primary');
                   9332:         }
                   9333:     }
1.1065    raeburn  9334:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9335:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  9336:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9337:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9338: }
                   9339: 
1.1172.2.141  raeburn  9340: sub auto_validate_inst_crosslist {
                   9341:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
                   9342:     my ($homeserver,$response);
                   9343:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9344:         $homeserver = &homeserver($cnum,$cdom);
                   9345:     }
                   9346:     if (!defined($homeserver)) {
                   9347:         if ($cdom =~ /^$match_domain$/) {
                   9348:             $homeserver = &domain($cdom,'primary');
                   9349:         }
                   9350:     }
                   9351:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
                   9352:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
                   9353:                          &escape($instcode).':'.&escape($inst_xlist).':'.
                   9354:                          &escape($coowner),$homeserver);
                   9355:     }
                   9356:     return $response;
                   9357: }
                   9358: 
1.506     raeburn  9359: sub auto_create_password {
1.873     raeburn  9360:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9361:     my ($homeserver,$response);
1.506     raeburn  9362:     my $create_passwd = 0;
                   9363:     my $authchk = '';
1.873     raeburn  9364:     if ($udom =~ /^$match_domain$/) {
                   9365:         $homeserver = &domain($udom,'primary');
                   9366:     }
                   9367:     if ($homeserver eq '') {
                   9368:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9369:             $homeserver = &homeserver($cnum,$cdom);
                   9370:         }
                   9371:     }
                   9372:     if ($homeserver eq '') {
                   9373:         $authchk = 'nodomain';
1.506     raeburn  9374:     } else {
1.873     raeburn  9375:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9376:         if ($response eq 'refused') {
                   9377:             $authchk = 'refused';
                   9378:         } else {
1.901     albertel 9379:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9380:         }
1.506     raeburn  9381:     }
                   9382:     return ($authparam,$create_passwd,$authchk);
                   9383: }
                   9384: 
1.706     raeburn  9385: sub auto_photo_permission {
                   9386:     my ($cnum,$cdom,$students) = @_;
                   9387:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9388:     my ($outcome,$perm_reqd,$conditions) = 
                   9389: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9390:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9391: 	return (undef,undef);
                   9392:     }
1.706     raeburn  9393:     return ($outcome,$perm_reqd,$conditions);
                   9394: }
                   9395: 
                   9396: sub auto_checkphotos {
                   9397:     my ($uname,$udom,$pid) = @_;
                   9398:     my $homeserver = &homeserver($uname,$udom);
                   9399:     my ($result,$resulttype);
                   9400:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9401: 				   &escape($uname).':'.&escape($pid),
                   9402: 				   $homeserver));
1.709     albertel 9403:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9404: 	return (undef,undef);
                   9405:     }
1.706     raeburn  9406:     if ($outcome) {
                   9407:         ($result,$resulttype) = split(/:/,$outcome);
                   9408:     } 
                   9409:     return ($result,$resulttype);
                   9410: }
                   9411: 
                   9412: sub auto_photochoice {
                   9413:     my ($cnum,$cdom) = @_;
                   9414:     my $homeserver = &homeserver($cnum,$cdom);
                   9415:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9416: 						       &escape($cdom),
                   9417: 						       $homeserver)));
1.709     albertel 9418:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9419: 	return (undef,undef);
                   9420:     }
1.706     raeburn  9421:     return ($update,$comment);
                   9422: }
                   9423: 
                   9424: sub auto_photoupdate {
                   9425:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9426:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9427:     my $host=&hostname($homeserver);
1.706     raeburn  9428:     my $cmd = '';
                   9429:     my $maxtries = 1;
1.800     albertel 9430:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9431:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9432:     }
                   9433:     $cmd =~ s/%%$//;
                   9434:     $cmd = &escape($cmd);
                   9435:     my $query = 'institutionalphotos';
                   9436:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9437:     unless ($queryid=~/^\Q$host\E\_/) {
                   9438:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9439:         return 'error: '.$queryid;
                   9440:     }
                   9441:     my $reply = &get_query_reply($queryid);
                   9442:     my $tries = 1;
                   9443:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9444:         $reply = &get_query_reply($queryid);
                   9445:         $tries ++;
                   9446:     }
                   9447:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9448:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9449:     } else {
                   9450:         my @responses = split(/:/,$reply);
                   9451:         my $outcome = shift(@responses); 
                   9452:         foreach my $item (@responses) {
                   9453:             my ($key,$value) = split(/=/,$item);
                   9454:             $$photo{$key} = $value;
                   9455:         }
                   9456:         return $outcome;
                   9457:     }
                   9458:     return 'error';
                   9459: }
                   9460: 
1.521     raeburn  9461: sub auto_instcode_format {
1.793     albertel 9462:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9463: 	$cat_order) = @_;
1.521     raeburn  9464:     my $courses = '';
1.772     raeburn  9465:     my @homeservers;
1.521     raeburn  9466:     if ($caller eq 'global') {
1.841     albertel 9467: 	my %servers = &get_servers($codedom,'library');
                   9468: 	foreach my $tryserver (keys(%servers)) {
                   9469: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9470: 		push(@homeservers,$tryserver);
                   9471: 	    }
1.584     raeburn  9472:         }
1.1022    raeburn  9473:     } elsif ($caller eq 'requests') {
                   9474:         if ($codedom =~ /^$match_domain$/) {
                   9475:             my $chome = &domain($codedom,'primary');
                   9476:             unless ($chome eq 'no_host') {
                   9477:                 push(@homeservers,$chome);
                   9478:             }
                   9479:         }
1.521     raeburn  9480:     } else {
1.772     raeburn  9481:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9482:     }
1.793     albertel 9483:     foreach my $code (keys(%{$instcodes})) {
                   9484:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9485:     }
                   9486:     chop($courses);
1.772     raeburn  9487:     my $ok_response = 0;
                   9488:     my $response;
                   9489:     while (@homeservers > 0 && $ok_response == 0) {
                   9490:         my $server = shift(@homeservers); 
                   9491:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9492:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9493:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9494: 		split(/:/,$response);
1.772     raeburn  9495:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9496:             push(@{$codetitles},&str2array($codetitles_str));
                   9497:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9498:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9499:             $ok_response = 1;
                   9500:         }
                   9501:     }
                   9502:     if ($ok_response) {
1.521     raeburn  9503:         return 'ok';
1.772     raeburn  9504:     } else {
                   9505:         return $response;
1.521     raeburn  9506:     }
                   9507: }
                   9508: 
1.792     raeburn  9509: sub auto_instcode_defaults {
                   9510:     my ($domain,$returnhash,$code_order) = @_;
                   9511:     my @homeservers;
1.841     albertel 9512: 
                   9513:     my %servers = &get_servers($domain,'library');
                   9514:     foreach my $tryserver (keys(%servers)) {
                   9515: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9516: 	    push(@homeservers,$tryserver);
                   9517: 	}
1.792     raeburn  9518:     }
1.841     albertel 9519: 
1.792     raeburn  9520:     my $response;
1.841     albertel 9521:     foreach my $server (@homeservers) {
1.792     raeburn  9522:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9523:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9524: 	
                   9525: 	foreach my $pair (split(/\&/,$response)) {
                   9526: 	    my ($name,$value)=split(/\=/,$pair);
                   9527: 	    if ($name eq 'code_order') {
                   9528: 		@{$code_order} = split(/\&/,&unescape($value));
                   9529: 	    } else {
                   9530: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9531: 	    }
                   9532: 	}
                   9533: 	return 'ok';
1.792     raeburn  9534:     }
1.841     albertel 9535: 
                   9536:     return $response;
1.1003    raeburn  9537: }
                   9538: 
                   9539: sub auto_possible_instcodes {
1.1007    raeburn  9540:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9541:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9542:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9543:         return;
                   9544:     }
1.1003    raeburn  9545:     my (@homeservers,$uhome);
                   9546:     if (defined(&domain($domain,'primary'))) {
                   9547:         $uhome=&domain($domain,'primary');
                   9548:         push(@homeservers,&domain($domain,'primary'));
                   9549:     } else {
                   9550:         my %servers = &get_servers($domain,'library');
                   9551:         foreach my $tryserver (keys(%servers)) {
                   9552:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9553:                 push(@homeservers,$tryserver);
                   9554:             }
                   9555:         }
                   9556:     }
                   9557:     my $response;
                   9558:     foreach my $server (@homeservers) {
                   9559:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9560:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9561:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9562:             split(':',$response);
                   9563:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9564:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9565:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9566:             my ($name,$value)=split('=',$item);
                   9567:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9568:         }
                   9569:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9570:             my ($name,$value)=split('=',$item);
                   9571:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9572:         }
                   9573:         return 'ok';
                   9574:     }
                   9575:     return $response;
                   9576: }
1.792     raeburn  9577: 
1.1010    raeburn  9578: sub auto_courserequest_checks {
                   9579:     my ($dom) = @_;
1.1020    raeburn  9580:     my ($homeserver,%validations);
                   9581:     if ($dom =~ /^$match_domain$/) {
                   9582:         $homeserver = &domain($dom,'primary');
                   9583:     }
                   9584:     unless ($homeserver eq 'no_host') {
                   9585:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9586:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9587:             my @items = split(/&/,$response);
                   9588:             foreach my $item (@items) {
                   9589:                 my ($key,$value) = split('=',$item);
                   9590:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9591:             }
                   9592:         }
                   9593:     }
1.1010    raeburn  9594:     return %validations; 
                   9595: }
                   9596: 
1.1020    raeburn  9597: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9598:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9599:     my ($homeserver,$response);
                   9600:     if ($dom =~ /^$match_domain$/) {
                   9601:         $homeserver = &domain($dom,'primary');
                   9602:     }
1.1172.2.43  raeburn  9603:     unless ($homeserver eq 'no_host') {
                   9604:         my $customdata;
                   9605:         if (ref($custominfo) eq 'HASH') {
                   9606:             $customdata = &freeze_escape($custominfo);
                   9607:         }
1.1020    raeburn  9608:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9609:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9610:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9611:                                     $customdata,$homeserver));
1.1020    raeburn  9612:     }
                   9613:     return $response;
                   9614: }
                   9615: 
1.777     albertel 9616: sub auto_validate_class_sec {
1.918     raeburn  9617:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9618:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9619:     my $ownerlist;
                   9620:     if (ref($owners) eq 'ARRAY') {
                   9621:         $ownerlist = join(',',@{$owners});
                   9622:     } else {
                   9623:         $ownerlist = $owners;
                   9624:     }
1.773     raeburn  9625:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9626:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9627:     return $response;
                   9628: }
                   9629: 
1.1172.2.141  raeburn  9630: sub auto_instsec_reformat {
                   9631:     my ($cdom,$action,$instsecref) = @_;
                   9632:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
                   9633:     my @homeservers;
                   9634:     if (defined(&domain($cdom,'primary'))) {
                   9635:         push(@homeservers,&domain($cdom,'primary'));
                   9636:     } else {
                   9637:         my %servers = &get_servers($cdom,'library');
                   9638:         foreach my $tryserver (keys(%servers)) {
                   9639:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9640:                 push(@homeservers,$tryserver);
                   9641:             }
                   9642:         }
                   9643:     }
                   9644:     my $response;
                   9645:     my %reformatted = %{$instsecref};
                   9646:     foreach my $server (@homeservers) {
                   9647:         if (ref($instsecref) eq 'HASH') {
                   9648:             my $info = &freeze_escape($instsecref);
                   9649:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
                   9650:                                 $action.':'.$info,$server);
                   9651:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
                   9652:             my @items = split(/&/,$response);
                   9653:             foreach my $item (@items) {
                   9654:                 my ($key,$value) = split(/=/,$item);
                   9655:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
                   9656:             }
                   9657:         }
                   9658:     }
                   9659:     return %reformatted;
                   9660: }
                   9661: 
1.1172.2.94  raeburn  9662: sub auto_validate_instclasses {
                   9663:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9664:     my ($homeserver,%validations);
                   9665:     $homeserver = &homeserver($cnum,$cdom);
                   9666:     unless ($homeserver eq 'no_host') {
                   9667:         my $ownerlist;
                   9668:         if (ref($owners) eq 'ARRAY') {
                   9669:             $ownerlist = join(',',@{$owners});
                   9670:         } else {
                   9671:             $ownerlist = $owners;
                   9672:         }
                   9673:         if (ref($classesref) eq 'HASH') {
                   9674:             my $classes = &freeze_escape($classesref);
                   9675:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9676:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9677:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9678:                 my @items = split(/&/,$response);
                   9679:                 foreach my $item (@items) {
                   9680:                     my ($key,$value) = split('=',$item);
                   9681:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9682:                 }
                   9683:             }
                   9684:         }
                   9685:     }
                   9686:     return %validations;
                   9687: }
                   9688: 
1.1172.2.38  raeburn  9689: sub auto_crsreq_update {
                   9690:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9691:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9692:     my ($homeserver,%crsreqresponse);
                   9693:     if ($cdom =~ /^$match_domain$/) {
                   9694:         $homeserver = &domain($cdom,'primary');
                   9695:     }
                   9696:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9697:         my $info;
                   9698:         if (ref($inbound) eq 'HASH') {
                   9699:             $info = &freeze_escape($inbound);
                   9700:         }
                   9701:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9702:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9703:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9704:                             &escape($title).':'.&escape($code).':'.
                   9705:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9706:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9707:             my @items = split(/&/,$response);
                   9708:             foreach my $item (@items) {
                   9709:                 my ($key,$value) = split('=',$item);
                   9710:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9711:             }
                   9712:         }
                   9713:     }
                   9714:     return \%crsreqresponse;
                   9715: }
                   9716: 
1.1172.2.78  raeburn  9717: sub auto_export_grades {
                   9718:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9719:     my ($homeserver,%exportresponse);
                   9720:     if ($cdom =~ /^$match_domain$/) {
                   9721:         $homeserver = &domain($cdom,'primary');
                   9722:     }
                   9723:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9724:         my $info;
                   9725:         if (ref($inforef) eq 'HASH') {
                   9726:             $info = &freeze_escape($inforef);
                   9727:         }
                   9728:         if (ref($gradesref) eq 'HASH') {
                   9729:             my $grades = &freeze_escape($gradesref);
                   9730:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9731:                                 $info.':'.$grades,$homeserver);
                   9732:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9733:                 my @items = split(/&/,$response);
                   9734:                 foreach my $item (@items) {
                   9735:                     my ($key,$value) = split('=',$item);
                   9736:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9737:                 }
                   9738:             }
                   9739:         }
                   9740:     }
                   9741:     return \%exportresponse;
                   9742: }
                   9743: 
1.1172.2.68  raeburn  9744: sub check_instcode_cloning {
                   9745:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9746:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9747:         return;
                   9748:     }
                   9749:     my $canclone;
                   9750:     if (@{$code_order} > 0) {
                   9751:         my $instcoderegexp ='^';
                   9752:         my @clonecodes = split(/\&/,$cloner);
                   9753:         foreach my $item (@{$code_order}) {
                   9754:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9755:                 foreach my $pair (@clonecodes) {
                   9756:                     my ($key,$val) = split(/\=/,$pair,2);
                   9757:                     $val = &unescape($val);
                   9758:                     if ($key eq $item) {
                   9759:                         $instcoderegexp .= '('.$val.')';
                   9760:                         last;
                   9761:                     }
                   9762:                 }
                   9763:             } else {
                   9764:                 $instcoderegexp .= $codedefaults->{$item};
                   9765:             }
                   9766:         }
                   9767:         $instcoderegexp .= '$';
                   9768:         my (@from,@to);
                   9769:         eval {
                   9770:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9771:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9772:         };
                   9773:         if ((@from > 0) && (@to > 0)) {
                   9774:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9775:             if (!@diffs) {
                   9776:                 $canclone = 1;
                   9777:             }
                   9778:         }
                   9779:     }
                   9780:     return $canclone;
                   9781: }
                   9782: 
                   9783: sub default_instcode_cloning {
                   9784:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9785:     my (%codedefaults,@code_order,$canclone);
                   9786:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9787:         %codedefaults = %{$codedefaultsref};
                   9788:         @code_order = @{$codeorderref};
                   9789:     } elsif ($clonedom) {
                   9790:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9791:     }
                   9792:     if (($domdefclone) && (@code_order)) {
                   9793:         my @clonecodes = split(/\+/,$domdefclone);
                   9794:         my $instcoderegexp ='^';
                   9795:         foreach my $item (@code_order) {
                   9796:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9797:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9798:             } else {
                   9799:                 $instcoderegexp .= $codedefaults{$item};
                   9800:             }
                   9801:         }
                   9802:         $instcoderegexp .= '$';
                   9803:         my (@from,@to);
                   9804:         eval {
                   9805:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9806:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9807:         };
                   9808:         if ((@from > 0) && (@to > 0)) {
                   9809:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9810:             if (!@diffs) {
                   9811:                 $canclone = 1;
                   9812:             }
                   9813:         }
                   9814:     }
                   9815:     return $canclone;
                   9816: }
                   9817: 
1.679     raeburn  9818: # ------------------------------------------------------- Course Group routines
                   9819: 
                   9820: sub get_coursegroups {
1.809     raeburn  9821:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9822:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9823: }
                   9824: 
1.679     raeburn  9825: sub modify_coursegroup {
                   9826:     my ($cdom,$cnum,$groupsettings) = @_;
                   9827:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9828: }
                   9829: 
1.809     raeburn  9830: sub toggle_coursegroup_status {
                   9831:     my ($cdom,$cnum,$group,$action) = @_;
                   9832:     my ($from_namespace,$to_namespace);
                   9833:     if ($action eq 'delete') {
                   9834:         $from_namespace = 'coursegroups';
                   9835:         $to_namespace = 'deleted_groups';
                   9836:     } else {
                   9837:         $from_namespace = 'deleted_groups';
                   9838:         $to_namespace = 'coursegroups';
                   9839:     }
                   9840:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9841:     if (my $tmp = &error(%curr_group)) {
                   9842:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9843:         return ('read error',$tmp);
                   9844:     } else {
                   9845:         my %savedsettings = %curr_group; 
1.809     raeburn  9846:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9847:         my $deloutcome;
                   9848:         if ($result eq 'ok') {
1.809     raeburn  9849:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9850:         } else {
                   9851:             return ('write error',$result);
                   9852:         }
                   9853:         if ($deloutcome eq 'ok') {
                   9854:             return 'ok';
                   9855:         } else {
                   9856:             return ('delete error',$deloutcome);
                   9857:         }
                   9858:     }
                   9859: }
                   9860: 
1.679     raeburn  9861: sub modify_group_roles {
1.957     raeburn  9862:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9863:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9864:     my $role = 'gr/'.&escape($userprivs);
                   9865:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9866:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9867:     if ($result eq 'ok') {
                   9868:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9869:     }
1.679     raeburn  9870:     return $result;
                   9871: }
                   9872: 
                   9873: sub modify_coursegroup_membership {
                   9874:     my ($cdom,$cnum,$membership) = @_;
                   9875:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9876:     return $result;
                   9877: }
                   9878: 
1.682     raeburn  9879: sub get_active_groups {
                   9880:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9881:     my $now = time;
                   9882:     my %groups = ();
                   9883:     foreach my $key (keys(%env)) {
1.811     albertel 9884:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9885:             my ($start,$end) = split(/\./,$env{$key});
                   9886:             if (($end!=0) && ($end<$now)) { next; }
                   9887:             if (($start!=0) && ($start>$now)) { next; }
                   9888:             if ($1 eq $cdom && $2 eq $cnum) {
                   9889:                 $groups{$3} = $env{$key} ;
                   9890:             }
                   9891:         }
                   9892:     }
                   9893:     return %groups;
                   9894: }
                   9895: 
1.683     raeburn  9896: sub get_group_membership {
                   9897:     my ($cdom,$cnum,$group) = @_;
                   9898:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9899: }
                   9900: 
                   9901: sub get_users_groups {
                   9902:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9903:     my @usersgroups;
1.683     raeburn  9904:     my $cachetime=1800;
                   9905: 
                   9906:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9907:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9908:     if (defined($cached)) {
1.734     albertel 9909:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9910:     } else {  
                   9911:         $grouplist = '';
1.816     raeburn  9912:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9913:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9914:         my $access_end = $env{'course.'.$courseid.
                   9915:                               '.default_enrollment_end_date'};
                   9916:         my $now = time;
                   9917:         foreach my $key (keys(%roleshash)) {
                   9918:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9919:                 my $group = $1;
                   9920:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9921:                     my $start = $2;
                   9922:                     my $end = $1;
                   9923:                     if ($start == -1) { next; } # deleted from group
                   9924:                     if (($start!=0) && ($start>$now)) { next; }
                   9925:                     if (($end!=0) && ($end<$now)) {
                   9926:                         if ($access_end && $access_end < $now) {
                   9927:                             if ($access_end - $end < 86400) {
                   9928:                                 push(@usersgroups,$group);
1.733     raeburn  9929:                             }
                   9930:                         }
1.817     raeburn  9931:                         next;
1.733     raeburn  9932:                     }
1.817     raeburn  9933:                     push(@usersgroups,$group);
1.683     raeburn  9934:                 }
                   9935:             }
                   9936:         }
1.817     raeburn  9937:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9938:         $grouplist = join(':',@usersgroups);
                   9939:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9940:     }
1.733     raeburn  9941:     return @usersgroups;
1.683     raeburn  9942: }
                   9943: 
                   9944: sub devalidate_getgroups_cache {
                   9945:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9946:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9947: 
1.683     raeburn  9948:     my $hashid="$udom:$uname:$courseid";
                   9949:     &devalidate_cache_new('getgroups',$hashid);
                   9950: }
                   9951: 
1.12      www      9952: # ------------------------------------------------------------------ Plain Text
                   9953: 
                   9954: sub plaintext {
1.988     raeburn  9955:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9956:     if ($short =~ m{^cr/}) {
1.758     albertel 9957: 	return (split('/',$short))[-1];
                   9958:     }
1.742     raeburn  9959:     if (!defined($cid)) {
                   9960:         $cid = $env{'request.course.id'};
                   9961:     }
                   9962:     my %rolenames = (
1.1008    raeburn  9963:                       Course    => 'std',
                   9964:                       Community => 'alt1',
1.742     raeburn  9965:                     );
1.1037    raeburn  9966:     if ($cid ne '') {
                   9967:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9968:             unless ($forcedefault) {
                   9969:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9970:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9971:                 return &Apache::lonlocal::mt($roletext);
                   9972:             }
                   9973:         }
                   9974:     }
                   9975:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9976:         (defined($rolenames{$type})) && 
                   9977:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9978:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9979:     } elsif ($cid ne '') {
                   9980:         my $crstype = $env{'course.'.$cid.'.type'};
                   9981:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9982:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9983:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9984:         }
1.742     raeburn  9985:     }
1.1037    raeburn  9986:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9987: }
                   9988: 
                   9989: # ----------------------------------------------------------------- Assign Role
                   9990: 
                   9991: sub assignrole {
1.957     raeburn  9992:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9993:         $context)=@_;
1.21      www      9994:     my $mrole;
                   9995:     if ($role =~ /^cr\//) {
1.393     www      9996:         my $cwosec=$url;
1.811     albertel 9997:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9998: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9999:            my $refused = 1;
                   10000:            if ($context eq 'requestcourses') {
                   10001:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   10002:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   10003:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   10004:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10005:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10006:                            if ($crsenv{'internal.courseowner'} eq
                   10007:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   10008:                                $refused = '';
                   10009:                            }
                   10010:                        }
                   10011:                    }
                   10012:                }
                   10013:            }
                   10014:            if ($refused) {
                   10015:                &logthis('Refused custom assignrole: '.
                   10016:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   10017:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   10018:                return 'refused';
                   10019:            }
1.104     www      10020:         }
1.21      www      10021:         $mrole='cr';
1.678     raeburn  10022:     } elsif ($role =~ /^gr\//) {
                   10023:         my $cwogrp=$url;
1.811     albertel 10024:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  10025:         unless (&allowed('mdg',$cwogrp)) {
                   10026:             &logthis('Refused group assignrole: '.
                   10027:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   10028:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   10029:             return 'refused';
                   10030:         }
                   10031:         $mrole='gr';
1.21      www      10032:     } else {
1.82      www      10033:         my $cwosec=$url;
1.811     albertel 10034:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  10035:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   10036:             my $refused;
                   10037:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   10038:                 if (!(&allowed('c'.$role,$url))) {
                   10039:                     $refused = 1;
                   10040:                 }
                   10041:             } else {
                   10042:                 $refused = 1;
                   10043:             }
1.947     raeburn  10044:             if ($refused) {
1.1045    raeburn  10045:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10046:                 if (!$selfenroll && $context eq 'course') {
                   10047:                     my %crsenv;
                   10048:                     if ($role eq 'cc' || $role eq 'co') {
                   10049:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10050:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   10051:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   10052:                                 if ($crsenv{'internal.courseowner'} eq 
                   10053:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10054:                                     $refused = '';
                   10055:                                 }
                   10056:                             }
                   10057:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   10058:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   10059:                                 if ($crsenv{'internal.courseowner'} eq 
                   10060:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10061:                                     $refused = '';
                   10062:                                 }
                   10063:                             }
                   10064:                         }
                   10065:                     }
                   10066:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  10067:                     $refused = '';
1.1017    raeburn  10068:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  10069:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  10070:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  10071:                         my $wrongcc;
                   10072:                         if ($cnum =~ /^$match_community$/) {
                   10073:                             $wrongcc = 1 if ($role eq 'cc');
                   10074:                         } else {
                   10075:                             $wrongcc = 1 if ($role eq 'co');
                   10076:                         }
                   10077:                         unless ($wrongcc) {
                   10078:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10079:                             if ($crsenv{'internal.courseowner'} eq 
                   10080:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   10081:                                 $refused = '';
                   10082:                             }
1.1017    raeburn  10083:                         }
                   10084:                     }
1.1172.2.9  raeburn  10085:                 } elsif ($context eq 'requestauthor') {
                   10086:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   10087:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   10088:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   10089:                             $refused = '';
                   10090:                         } else {
                   10091:                             my %domdefaults = &get_domain_defaults($udom);
                   10092:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   10093:                                 my $checkbystatus;
                   10094:                                 if ($env{'user.adv'}) {
                   10095:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   10096:                                     if ($disposition eq 'automatic') {
                   10097:                                         $refused = '';
                   10098:                                     } elsif ($disposition eq '') {
                   10099:                                         $checkbystatus = 1;
                   10100:                                     }
                   10101:                                 } else {
                   10102:                                     $checkbystatus = 1;
                   10103:                                 }
                   10104:                                 if ($checkbystatus) {
                   10105:                                     if ($env{'environment.inststatus'}) {
                   10106:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   10107:                                         foreach my $type (@inststatuses) {
                   10108:                                             if (($type ne '') &&
                   10109:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   10110:                                                 $refused = '';
                   10111:                                             }
                   10112:                                         }
                   10113:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   10114:                                         $refused = '';
                   10115:                                     }
                   10116:                                 }
                   10117:                             }
                   10118:                         }
                   10119:                     }
1.1017    raeburn  10120:                 }
                   10121:                 if ($refused) {
1.947     raeburn  10122:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   10123:                              ' '.$role.' '.$end.' '.$start.' by '.
                   10124: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   10125:                     return 'refused';
                   10126:                 }
1.932     raeburn  10127:             }
1.1131    raeburn  10128:         } elsif ($role eq 'au') {
                   10129:             if ($url ne '/'.$udom.'/') {
                   10130:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   10131:                          ' to assign author role for '.$uname.':'.$udom.
                   10132:                          ' in domain: '.$url.' refused (wrong domain).');
                   10133:                 return 'refused';
                   10134:             }
1.104     www      10135:         }
1.21      www      10136:         $mrole=$role;
                   10137:     }
1.620     albertel 10138:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      10139:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      10140:     if ($end) { $command.='_'.$end; }
1.21      www      10141:     if ($start) {
                   10142: 	if ($end) { 
1.81      www      10143:            $command.='_'.$start; 
1.21      www      10144:         } else {
1.81      www      10145:            $command.='_0_'.$start;
1.21      www      10146:         }
                   10147:     }
1.739     raeburn  10148:     my $origstart = $start;
                   10149:     my $origend = $end;
1.957     raeburn  10150:     my $delflag;
1.357     www      10151: # actually delete
                   10152:     if ($deleteflag) {
1.373     www      10153: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      10154: # modify command to delete the role
1.620     albertel 10155:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      10156:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 10157: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      10158: # set start and finish to negative values for userrolelog
                   10159:            $start=-1;
                   10160:            $end=-1;
1.957     raeburn  10161:            $delflag = 1;
1.357     www      10162:         }
                   10163:     }
                   10164: # send command
1.349     www      10165:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      10166: # log new user role if status is ok
1.349     www      10167:     if ($answer eq 'ok') {
1.663     raeburn  10168: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  10169:         if (($role eq 'cc') || ($role eq 'in') ||
                   10170:             ($role eq 'ep') || ($role eq 'ad') ||
                   10171:             ($role eq 'ta') || ($role eq 'st') ||
                   10172:             ($role=~/^cr/) || ($role eq 'gr') ||
                   10173:             ($role eq 'co')) {
1.1172.2.13  raeburn  10174: # for course roles, perform group memberships changes triggered by role change.
                   10175:             unless ($role =~ /^gr/) {
                   10176:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   10177:                                                  $origstart,$selfenroll,$context);
                   10178:             }
1.1172.2.9  raeburn  10179:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10180:                            $selfenroll,$context);
                   10181:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  10182:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   10183:                  ($role eq 'da')) {
1.1172.2.9  raeburn  10184:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10185:                            $context);
                   10186:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   10187:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10188:                              $context);
                   10189:         }
1.1053    raeburn  10190:         if ($role eq 'cc') {
                   10191:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   10192:         }
1.349     www      10193:     }
                   10194:     return $answer;
1.169     harris41 10195: }
                   10196: 
1.1053    raeburn  10197: sub autoupdate_coowners {
                   10198:     my ($url,$end,$start,$uname,$udom) = @_;
                   10199:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   10200:     if (($cdom ne '') && ($cnum ne '')) {
                   10201:         my $now = time;
                   10202:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   10203:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   10204:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   10205:             my $instcode = $coursehash{'internal.coursecode'};
1.1172.2.141  raeburn  10206:             my $xlists = $coursehash{'internal.crosslistings'};
1.1053    raeburn  10207:             if ($instcode ne '') {
1.1056    raeburn  10208:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   10209:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  10210:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  10211:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1172.2.141  raeburn  10212:                         unless ($result eq 'valid') {
                   10213:                             if ($xlists ne '') {
                   10214:                                 foreach my $xlist (split(',',$xlists)) {
                   10215:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
                   10216:                                     $result =
                   10217:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
                   10218:                                                                       $inst_crosslist,$uname.':'.$udom);
                   10219:                                     last if ($result eq 'valid');
                   10220:                                 }
                   10221:                             }
                   10222:                         }
1.1056    raeburn  10223:                         if ($result eq 'valid') {
                   10224:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  10225:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10226:                                     push(@newcoowners,$coowner);
                   10227:                                 }
                   10228:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   10229:                                     push(@newcoowners,$uname.':'.$udom);
                   10230:                                 }
                   10231:                                 @newcoowners = sort(@newcoowners);
                   10232:                             } else {
                   10233:                                 push(@newcoowners,$uname.':'.$udom);
                   10234:                             }
1.1172.2.141  raeburn  10235:                         } elsif ($coursehash{'internal.co-owners'}) {
                   10236:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10237:                                 unless ($coowner eq $uname.':'.$udom) {
                   10238:                                     push(@newcoowners,$coowner);
1.1053    raeburn  10239:                                 }
                   10240:                             }
1.1172.2.141  raeburn  10241:                             unless (@newcoowners > 0) {
                   10242:                                 $delcoowners = 1;
                   10243:                                 $coowners = '';
                   10244:                             }
1.1053    raeburn  10245:                         }
                   10246:                         if (@newcoowners || $delcoowners) {
                   10247:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   10248:                                             $delcoowners,@newcoowners);
                   10249:                         }
                   10250:                     }
                   10251:                 }
                   10252:             }
                   10253:         }
                   10254:     }
                   10255: }
                   10256: 
                   10257: sub store_coowners {
                   10258:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   10259:     my $cid = $cdom.'_'.$cnum;
                   10260:     my ($coowners,$delresult,$putresult);
                   10261:     if (@newcoowners) {
                   10262:         $coowners = join(',',@newcoowners);
                   10263:         my %coownershash = (
                   10264:                             'internal.co-owners' => $coowners,
                   10265:                            );
                   10266:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   10267:         if ($putresult eq 'ok') {
                   10268:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   10269:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   10270:             }
                   10271:         }
                   10272:     }
                   10273:     if ($delcoowners) {
                   10274:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   10275:         if ($delresult eq 'ok') {
                   10276:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   10277:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   10278:             }
                   10279:         }
                   10280:     }
                   10281:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   10282:         my %crsinfo =
                   10283:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   10284:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   10285:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   10286:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   10287:         }
                   10288:     }
                   10289: }
                   10290: 
1.169     harris41 10291: # -------------------------------------------------- Modify user authentication
1.197     www      10292: # Overrides without validation
                   10293: 
1.169     harris41 10294: sub modifyuserauth {
                   10295:     my ($udom,$uname,$umode,$upass)=@_;
                   10296:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  10297:     my $allowed;
                   10298:     if (&allowed('mau',$udom)) {
                   10299:         $allowed = 1;
                   10300:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   10301:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   10302:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   10303:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10304:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10305:         if (($cdom ne '') && ($cnum ne '')) {
                   10306:             my $is_owner = &is_course_owner($cdom,$cnum);
                   10307:             if ($is_owner) {
                   10308:                 $allowed = 1;
                   10309:             }
                   10310:         }
                   10311:     }
                   10312:     unless ($allowed) { return 'refused'; }
1.197     www      10313:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 10314:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10315:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 10316:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10317: 		     &escape($upass),$uhome);
1.1172.2.134  raeburn  10318:     my $ip = &get_requestor_ip();
1.620     albertel 10319:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10320:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.134  raeburn  10321:          '(Remote '.$ip.'): '.$reply);
1.197     www      10322:     &log($udom,,$uname,$uhome,
1.620     albertel 10323:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10324:                                      $env{'user.name'}.', '.$umode.
1.1172.2.134  raeburn  10325:          '(Remote '.$ip.'): '.$reply);
1.169     harris41 10326:     unless ($reply eq 'ok') {
1.197     www      10327:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10328: 	return 'error: '.$reply;
                   10329:     }   
1.170     harris41 10330:     return 'ok';
1.80      www      10331: }
                   10332: 
1.81      www      10333: # --------------------------------------------------------------- Modify a user
1.80      www      10334: 
1.81      www      10335: sub modifyuser {
1.206     matthew  10336:     my ($udom,    $uname, $uid,
                   10337:         $umode,   $upass, $first,
                   10338:         $middle,  $last,  $gene,
1.1058    raeburn  10339:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10340:     $udom= &LONCAPA::clean_domain($udom);
                   10341:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10342:     my $showcandelete = 'none';
                   10343:     if (ref($candelete) eq 'ARRAY') {
                   10344:         if (@{$candelete} > 0) {
                   10345:             $showcandelete = join(', ',@{$candelete});
                   10346:         }
                   10347:     }
1.81      www      10348:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10349:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10350: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10351:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10352:                                      ' desiredhome not specified'). 
1.620     albertel 10353:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10354:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10355:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10356:     my $newuser;
                   10357:     if ($uhome eq 'no_host') {
                   10358:         $newuser = 1;
                   10359:     }
1.80      www      10360: # ----------------------------------------------------------------- Create User
1.406     albertel 10361:     if (($uhome eq 'no_host') && 
                   10362: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      10363:         my $unhome='';
1.844     albertel 10364:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10365:             $unhome = $desiredhome;
1.620     albertel 10366: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10367: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10368:         } else { # load balancing routine for determining $unhome
1.81      www      10369:             my $loadm=10000000;
1.841     albertel 10370: 	    my %servers = &get_servers($udom,'library');
                   10371: 	    foreach my $tryserver (keys(%servers)) {
                   10372: 		my $answer=reply('load',$tryserver);
                   10373: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10374: 		    $loadm=$answer;
                   10375: 		    $unhome=$tryserver;
                   10376: 		}
1.80      www      10377: 	    }
                   10378:         }
                   10379:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10380: 	    return 'error: unable to find a home server for '.$uname.
                   10381:                    ' in domain '.$udom;
1.80      www      10382:         }
                   10383:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10384:                          &escape($upass),$unhome);
                   10385: 	unless ($reply eq 'ok') {
                   10386:             return 'error: '.$reply;
                   10387:         }   
1.230     stredwic 10388:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10389:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10390: 	    return 'error: unable verify users home machine.';
1.80      www      10391:         }
1.209     matthew  10392:     }   # End of creation of new user
1.80      www      10393: # ---------------------------------------------------------------------- Add ID
                   10394:     if ($uid) {
                   10395:        $uid=~tr/A-Z/a-z/;
                   10396:        my %uidhash=&idrget($udom,$uname);
1.196     www      10397:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10398:          && (!$forceid)) {
1.80      www      10399: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10400: 	      return 'error: user id "'.$uid.'" does not match '.
                   10401:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10402:           }
                   10403:        } else {
                   10404: 	  &idput($udom,($uname => $uid));
                   10405:        }
                   10406:     }
                   10407: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10408:     my @tmp=&get('environment',
1.899     raeburn  10409: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10410:                     'permanentemail','inststatus'],
1.134     albertel 10411: 		   $udom,$uname);
1.1075    raeburn  10412:     my (%names,%oldnames);
1.313     matthew  10413:     if ($tmp[0] =~ m/^error:.*/) { 
                   10414:         %names=(); 
                   10415:     } else {
                   10416:         %names = @tmp;
1.1075    raeburn  10417:         %oldnames = %names;
1.313     matthew  10418:     }
1.388     www      10419: #
1.1058    raeburn  10420: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10421: # of users did not contain them), do not overwrite existing values
                   10422: # unless field is in $candelete array ref.  
                   10423: #
                   10424: 
                   10425:     my @fields = ('firstname','middlename','lastname','generation',
                   10426:                   'permanentemail','id');
                   10427:     my %newvalues;
                   10428:     if (ref($candelete) eq 'ARRAY') {
                   10429:         foreach my $field (@fields) {
                   10430:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10431:                 if ($field eq 'firstname') {
                   10432:                     $names{$field} = $first;
                   10433:                 } elsif ($field eq 'middlename') {
                   10434:                     $names{$field} = $middle;
                   10435:                 } elsif ($field eq 'lastname') {
                   10436:                     $names{$field} = $last;
                   10437:                 } elsif ($field eq 'generation') { 
                   10438:                     $names{$field} = $gene;
                   10439:                 } elsif ($field eq 'permanentemail') {
                   10440:                     $names{$field} = $email;
                   10441:                 } elsif ($field eq 'id') {
                   10442:                     $names{$field}  = $uid;
                   10443:                 }
                   10444:             }
                   10445:         }
                   10446:     }
1.388     www      10447:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10448:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10449:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10450:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10451:     if ($email) {
                   10452:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10453:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10454:     }
1.899     raeburn  10455:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10456:     if (defined($inststatus)) {
                   10457:         $names{'inststatus'} = '';
                   10458:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10459:         if (ref($usertypes) eq 'HASH') {
                   10460:             my @okstatuses; 
                   10461:             foreach my $item (split(/:/,$inststatus)) {
                   10462:                 if (defined($usertypes->{$item})) {
                   10463:                     push(@okstatuses,$item);  
                   10464:                 }
                   10465:             }
                   10466:             if (@okstatuses) {
                   10467:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10468:             }
                   10469:         }
                   10470:     }
1.1075    raeburn  10471:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10472:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10473:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10474:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10475:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10476:     } else {
                   10477:         $logmsg .= ' during self creation';
                   10478:     }
1.1075    raeburn  10479:     my $changed;
                   10480:     if ($newuser) {
                   10481:         $changed = 1;
                   10482:     } else {
                   10483:         foreach my $field (@fields) {
                   10484:             if ($names{$field} ne $oldnames{$field}) {
                   10485:                 $changed = 1;
                   10486:                 last;
                   10487:             }
                   10488:         }
                   10489:     }
                   10490:     unless ($changed) {
                   10491:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10492:         &logthis($logmsg);
                   10493:         return 'ok';
                   10494:     }
                   10495:     my $reply = &put('environment', \%names, $udom,$uname);
                   10496:     if ($reply ne 'ok') { 
                   10497:         return 'error: '.$reply;
                   10498:     }
1.1087    raeburn  10499:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10500:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10501:     }
1.1075    raeburn  10502:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10503:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10504:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10505:     &logthis($logmsg);
1.134     albertel 10506:     return 'ok';
1.80      www      10507: }
                   10508: 
1.81      www      10509: # -------------------------------------------------------------- Modify student
1.80      www      10510: 
1.81      www      10511: sub modifystudent {
                   10512:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10513:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10514:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10515:     if (!$cid) {
1.620     albertel 10516: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10517: 	    return 'not_in_class';
                   10518: 	}
1.80      www      10519:     }
                   10520: # --------------------------------------------------------------- Make the user
1.81      www      10521:     my $reply=&modifyuser
1.209     matthew  10522: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10523:          $desiredhome,$email,$inststatus);
1.80      www      10524:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10525:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10526:     # student's environment
1.297     matthew  10527:     $uid = undef if (!$forceid);
1.455     albertel 10528:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10529: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10530:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10531:     return $reply;
                   10532: }
                   10533: 
                   10534: sub modify_student_enrollment {
1.1172.2.23  raeburn  10535:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10536:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10537:     my ($cdom,$cnum,$chome);
                   10538:     if (!$cid) {
1.620     albertel 10539: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10540: 	    return 'not_in_class';
                   10541: 	}
1.620     albertel 10542: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10543: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10544:     } else {
                   10545: 	($cdom,$cnum)=split(/_/,$cid);
                   10546:     }
1.620     albertel 10547:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10548:     if (!$chome) {
1.457     raeburn  10549: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10550:     }
1.455     albertel 10551:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10552:     # Make sure the user exists
1.81      www      10553:     my $uhome=&homeserver($uname,$udom);
                   10554:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10555: 	return 'error: no such user';
                   10556:     }
1.297     matthew  10557:     # Get student data if we were not given enough information
                   10558:     if (!defined($first)  || $first  eq '' || 
                   10559:         !defined($last)   || $last   eq '' || 
                   10560:         !defined($uid)    || $uid    eq '' || 
                   10561:         !defined($middle) || $middle eq '' || 
                   10562:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10563:         # They did not supply us with enough data to enroll the student, so
                   10564:         # we need to pick up more information.
1.297     matthew  10565:         my %tmp = &get('environment',
1.294     matthew  10566:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10567:                        ,$udom,$uname);
                   10568: 
1.800     albertel 10569:         #foreach my $key (keys(%tmp)) {
                   10570:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10571:         #}
1.294     matthew  10572:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10573:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10574:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10575:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10576:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10577:     }
1.556     albertel 10578:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10579:     my $user = "$uname:$udom";
                   10580:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10581:     my $reply=cput('classlist',
1.1148    raeburn  10582: 		   {$user => 
1.1172.2.76  raeburn  10583: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10584: 		   $cdom,$cnum);
1.1148    raeburn  10585:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10586:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10587:     } else { 
1.81      www      10588: 	return 'error: '.$reply;
                   10589:     }
1.297     matthew  10590:     # Add student role to user
1.83      www      10591:     my $uurl='/'.$cid;
1.81      www      10592:     $uurl=~s/\_/\//g;
                   10593:     if ($usec) {
                   10594: 	$uurl.='/'.$usec;
                   10595:     }
1.1148    raeburn  10596:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10597:                              $selfenroll,$context);
                   10598:     if ($result ne 'ok') {
                   10599:         if ($old_entry{$user} ne '') {
                   10600:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10601:         } else {
                   10602:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10603:         }
                   10604:     }
                   10605:     return $result; 
1.21      www      10606: }
                   10607: 
1.556     albertel 10608: sub format_name {
                   10609:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10610:     my $name;
                   10611:     if ($first ne 'lastname') {
                   10612: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10613:     } else {
                   10614: 	if ($lastname=~/\S/) {
                   10615: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10616: 	    $name=~s/\s+,/,/;
                   10617: 	} else {
                   10618: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10619: 	}
                   10620:     }
                   10621:     $name=~s/^\s+//;
                   10622:     $name=~s/\s+$//;
                   10623:     $name=~s/\s+/ /g;
                   10624:     return $name;
                   10625: }
                   10626: 
1.84      www      10627: # ------------------------------------------------- Write to course preferences
                   10628: 
                   10629: sub writecoursepref {
                   10630:     my ($courseid,%prefs)=@_;
                   10631:     $courseid=~s/^\///;
                   10632:     $courseid=~s/\_/\//g;
                   10633:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10634:     my $chome=homeserver($cnum,$cdomain);
                   10635:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10636: 	return 'error: no such course';
                   10637:     }
                   10638:     my $cstring='';
1.800     albertel 10639:     foreach my $pref (keys(%prefs)) {
                   10640: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10641:     }
1.84      www      10642:     $cstring=~s/\&$//;
                   10643:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10644: }
                   10645: 
                   10646: # ---------------------------------------------------------- Make/modify course
                   10647: 
                   10648: sub createcourse {
1.741     raeburn  10649:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1172.2.146.  .1(raebu 10650:22):         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      10651:     $url=&declutter($url);
                   10652:     my $cid='';
1.1028    raeburn  10653:     if ($context eq 'requestcourses') {
                   10654:         my $can_create = 0;
                   10655:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10656:         if ($udom eq $ownerdom) {
1.1172.2.146.  .1(raebu 10657:22):             my $reload;
                   10658:22):             if (($callercontext eq 'auto') &&
                   10659:22):                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   10660:22):                 $reload = 'reload';
                   10661:22):             }
                   10662:22):             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  10663:                                   $context)) {
                   10664:                 $can_create = 1;
                   10665:             }
                   10666:         } else {
                   10667:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10668:                                            $category);
                   10669:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10670:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10671:                 if (@curr > 0) {
                   10672:                     my @options = qw(approval validate autolimit);
                   10673:                     my $optregex = join('|',@options);
                   10674:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10675:                         $can_create = 1;
                   10676:                     }
                   10677:                 }
                   10678:             }
                   10679:         }
                   10680:         if ($can_create) {
                   10681:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10682:                 unless (&allowed('ccc',$udom)) {
                   10683:                     return 'refused'; 
                   10684:                 }
1.1017    raeburn  10685:             }
                   10686:         } else {
                   10687:             return 'refused';
                   10688:         }
1.1028    raeburn  10689:     } elsif (!&allowed('ccc',$udom)) {
                   10690:         return 'refused';
1.84      www      10691:     }
1.1011    raeburn  10692: # --------------------------------------------------------------- Get Unique ID
                   10693:     my $uname;
                   10694:     if ($cnum =~ /^$match_courseid$/) {
                   10695:         my $chome=&homeserver($cnum,$udom,'true');
                   10696:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10697:             $uname = $cnum;
                   10698:         } else {
1.1038    raeburn  10699:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10700:         }
                   10701:     } else {
1.1038    raeburn  10702:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10703:     }
                   10704:     return $uname if ($uname =~ /^error/);
                   10705: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10706:     if (!defined($course_server)) {
                   10707:         if (defined(&domain($udom,'primary'))) {
                   10708:             $course_server = &domain($udom,'primary');
                   10709:         } else {
                   10710:             $course_server = $env{'user.home'}; 
                   10711:         }
                   10712:     }
                   10713:     my %host_servers =
                   10714:         &Apache::lonnet::get_servers($udom,'library');
                   10715:     unless ($host_servers{$course_server}) {
                   10716:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10717:     }
1.84      www      10718: # ------------------------------------------------------------- Make the course
                   10719:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10720:                       $course_server);
1.84      www      10721:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10722:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10723:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10724: 	return 'error: no such course';
                   10725:     }
1.271     www      10726: # ----------------------------------------------------------------- Course made
1.516     raeburn  10727: # log existence
1.1029    raeburn  10728:     my $now = time;
1.918     raeburn  10729:     my $newcourse = {
                   10730:                     $udom.'_'.$uname => {
1.921     raeburn  10731:                                      description => $description,
                   10732:                                      inst_code   => $inst_code,
                   10733:                                      owner       => $course_owner,
                   10734:                                      type        => $crstype,
1.1029    raeburn  10735:                                      creator     => $env{'user.name'}.':'.
                   10736:                                                     $env{'user.domain'},
                   10737:                                      created     => $now,
                   10738:                                      context     => $context,
1.918     raeburn  10739:                                                 },
                   10740:                     };
1.921     raeburn  10741:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10742: # set toplevel url
1.271     www      10743:     my $topurl=$url;
                   10744:     unless ($nonstandard) {
                   10745: # ------------------------------------------ For standard courses, make top url
                   10746:         my $mapurl=&clutter($url);
1.278     www      10747:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10748:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10749: <map>
                   10750: <resource id="1" type="start"></resource>
                   10751: <resource id="2" src="$mapurl"></resource>
                   10752: <resource id="3" type="finish"></resource>
                   10753: <link index="1" from="1" to="2"></link>
                   10754: <link index="2" from="2" to="3"></link>
                   10755: </map>
                   10756: ENDINITMAP
                   10757:         $topurl=&declutter(
1.638     albertel 10758:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10759:                           );
                   10760:     }
                   10761: # ----------------------------------------------------------- Write preferences
1.84      www      10762:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10763:                      ('description'              => $description,
                   10764:                       'url'                      => $topurl,
                   10765:                       'internal.creator'         => $env{'user.name'}.':'.
                   10766:                                                     $env{'user.domain'},
                   10767:                       'internal.created'         => $now,
                   10768:                       'internal.creationcontext' => $context)
                   10769:                     );
1.84      www      10770:     return '/'.$udom.'/'.$uname;
                   10771: }
                   10772: 
1.1011    raeburn  10773: # ------------------------------------------------------------------- Create ID
                   10774: sub generate_coursenum {
1.1038    raeburn  10775:     my ($udom,$crstype) = @_;
1.1011    raeburn  10776:     my $domdesc = &domain($udom);
                   10777:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10778:     my $first;
                   10779:     if ($crstype eq 'Community') {
                   10780:         $first = '0';
                   10781:     } else {
                   10782:         $first = int(1+rand(9)); 
                   10783:     } 
                   10784:     my $uname=$first.
1.1011    raeburn  10785:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10786:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10787:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10788: # ----------------------------------------------- Make sure that does not exist
                   10789:     my $uhome=&homeserver($uname,$udom,'true');
                   10790:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10791:         if ($crstype eq 'Community') {
                   10792:             $first = '0';
                   10793:         } else {
                   10794:             $first = int(1+rand(9));
                   10795:         }
                   10796:         $uname=$first.
1.1011    raeburn  10797:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10798:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10799:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10800:         $uhome=&homeserver($uname,$udom,'true');
                   10801:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10802:             return 'error: unable to generate unique course-ID';
                   10803:         }
                   10804:     }
                   10805:     return $uname;
                   10806: }
                   10807: 
1.813     albertel 10808: sub is_course {
1.1167    droeschl 10809:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10810:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10811:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10812:     my $uhome=&homeserver($cnum,$cdom);
                   10813:     my $iscourse;
                   10814:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10815:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10816:     } else {
                   10817:         my $hashid = $cdom.':'.$cnum;
                   10818:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10819:         unless (defined($cached)) {
                   10820:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10821:                                         $cnum,undef,undef,'.');
                   10822:             $iscourse = 0;
                   10823:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10824:                 $iscourse = 1;
                   10825:             }
                   10826:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10827:         }
                   10828:     }
                   10829:     return unless($iscourse);
1.1167    droeschl 10830:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10831: }
                   10832: 
1.1015    raeburn  10833: sub store_userdata {
                   10834:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10835:     my $result;
1.1016    raeburn  10836:     if ($datakey ne '') {
1.1013    raeburn  10837:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10838:             if ($udom eq '' || $uname eq '') {
                   10839:                 $udom = $env{'user.domain'};
                   10840:                 $uname = $env{'user.name'};
                   10841:             }
                   10842:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10843:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10844:                 $result = 'error: no_host';
                   10845:             } else {
1.1172.2.138  raeburn  10846:                 $storehash->{'ip'} = &get_requestor_ip();
1.1013    raeburn  10847:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10848: 
                   10849:                 my $namevalue='';
                   10850:                 foreach my $key (keys(%{$storehash})) {
                   10851:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10852:                 }
                   10853:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10854:                 unless ($namespace eq 'courserequests') {
                   10855:                     $datakey = &escape($datakey);
                   10856:                 }
1.1105    raeburn  10857:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10858:                                   $namevalue,$uhome);
1.1013    raeburn  10859:             }
                   10860:         } else {
                   10861:             $result = 'error: data to store was not a hash reference'; 
                   10862:         }
                   10863:     } else {
                   10864:         $result= 'error: invalid requestkey'; 
                   10865:     }
                   10866:     return $result;
                   10867: }
                   10868: 
1.21      www      10869: # ---------------------------------------------------------- Assign Custom Role
                   10870: 
                   10871: sub assigncustomrole {
1.957     raeburn  10872:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10873:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10874:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10875: }
                   10876: 
                   10877: # ----------------------------------------------------------------- Revoke Role
                   10878: 
                   10879: sub revokerole {
1.957     raeburn  10880:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10881:     my $now=time;
1.965     raeburn  10882:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10883: }
                   10884: 
                   10885: # ---------------------------------------------------------- Revoke Custom Role
                   10886: 
                   10887: sub revokecustomrole {
1.957     raeburn  10888:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10889:     my $now=time;
1.357     www      10890:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10891:            $deleteflag,$selfenroll,$context);
1.17      www      10892: }
                   10893: 
1.533     banghart 10894: # ------------------------------------------------------------ Disk usage
1.535     albertel 10895: sub diskusage {
1.955     raeburn  10896:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10897:     $directorypath =~ s/\/$//;
                   10898:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10899:                        .&escape($getpropath).':'.&escape($uname).':'
                   10900:                        .&escape($udom),homeserver($uname,$udom));
                   10901:     if ($listing eq 'unknown_cmd') {
                   10902:         if ($getpropath) {
                   10903:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10904:         }
                   10905:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10906:     }
1.514     albertel 10907:     return $listing;
1.512     banghart 10908: }
                   10909: 
1.566     banghart 10910: sub is_locked {
1.1096    raeburn  10911:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10912:     my @check;
                   10913:     my $is_locked;
1.1093    raeburn  10914:     push (@check,$file_name);
1.613     albertel 10915:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10916: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10917:     my ($tmp)=keys(%locked);
                   10918:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10919:     
1.566     banghart 10920:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10921:         $is_locked = 'false';
                   10922:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10923:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10924:                $is_locked = 'true';
1.1096    raeburn  10925:                if (ref($which) eq 'ARRAY') {
                   10926:                    push(@{$which},$entry);
                   10927:                } else {
                   10928:                    last;
                   10929:                }
1.745     raeburn  10930:            }
                   10931:        }
1.566     banghart 10932:     } else {
                   10933:         $is_locked = 'false';
                   10934:     }
1.1093    raeburn  10935:     return $is_locked;
1.566     banghart 10936: }
                   10937: 
1.759     albertel 10938: sub declutter_portfile {
                   10939:     my ($file) = @_;
1.833     albertel 10940:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10941:     return $file;
                   10942: }
                   10943: 
1.559     banghart 10944: # ------------------------------------------------------------- Mark as Read Only
                   10945: 
                   10946: sub mark_as_readonly {
                   10947:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10948:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10949:     my ($tmp)=keys(%current_permissions);
                   10950:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10951:     foreach my $file (@{$files}) {
1.759     albertel 10952: 	$file = &declutter_portfile($file);
1.561     banghart 10953:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10954:     }
1.613     albertel 10955:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10956:     return;
                   10957: }
                   10958: 
1.572     banghart 10959: # ------------------------------------------------------------Save Selected Files
                   10960: 
                   10961: sub save_selected_files {
                   10962:     my ($user, $path, @files) = @_;
                   10963:     my $filename = $user."savedfiles";
1.573     banghart 10964:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  10965:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10966:     foreach my $file (@files) {
1.620     albertel 10967:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10968:     }
                   10969:     foreach my $file (@other_files) {
1.574     banghart 10970:         print (OUT $file."\n");
1.572     banghart 10971:     }
1.574     banghart 10972:     close (OUT);
1.572     banghart 10973:     return 'ok';
                   10974: }
                   10975: 
1.574     banghart 10976: sub clear_selected_files {
                   10977:     my ($user) = @_;
                   10978:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  10979:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10980:     print (OUT undef);
                   10981:     close (OUT);
                   10982:     return ("ok");    
                   10983: }
                   10984: 
1.572     banghart 10985: sub files_in_path {
                   10986:     my ($user, $path) = @_;
                   10987:     my $filename = $user."savedfiles";
                   10988:     my %return_files;
1.1172.2.96  raeburn  10989:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10990:     while (my $line_in = <IN>) {
1.574     banghart 10991:         chomp ($line_in);
                   10992:         my @paths_and_file = split (m!/!, $line_in);
                   10993:         my $file_part = pop (@paths_and_file);
                   10994:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10995:         $path_part.='/';
                   10996:         my $path_and_file = $path_part.$file_part;
                   10997:         if ($path_part eq $path) {
                   10998:             $return_files{$file_part}= 'selected';
                   10999:         }
                   11000:     }
1.574     banghart 11001:     close (IN);
                   11002:     return (\%return_files);
1.572     banghart 11003: }
                   11004: 
                   11005: # called in portfolio select mode, to show files selected NOT in current directory
                   11006: sub files_not_in_path {
                   11007:     my ($user, $path) = @_;
                   11008:     my $filename = $user."savedfiles";
                   11009:     my @return_files;
                   11010:     my $path_part;
1.1172.2.96  raeburn  11011:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 11012:     while (my $line = <IN>) {
1.572     banghart 11013:         #ok, I know it's clunky, but I want it to work
1.800     albertel 11014:         my @paths_and_file = split(m|/|, $line);
                   11015:         my $file_part = pop(@paths_and_file);
                   11016:         chomp($file_part);
                   11017:         my $path_part = join('/', @paths_and_file);
1.572     banghart 11018:         $path_part .= '/';
                   11019:         my $path_and_file = $path_part.$file_part;
                   11020:         if ($path_part ne $path) {
1.800     albertel 11021:             push(@return_files, ($path_and_file));
1.572     banghart 11022:         }
                   11023:     }
1.800     albertel 11024:     close(OUT);
1.574     banghart 11025:     return (@return_files);
1.572     banghart 11026: }
                   11027: 
1.745     raeburn  11028: #----------------------------------------------Get portfolio file permissions
1.629     banghart 11029: 
1.745     raeburn  11030: sub get_portfile_permissions {
                   11031:     my ($domain,$user) = @_;
1.613     albertel 11032:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11033:     my ($tmp)=keys(%current_permissions);
                   11034:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11035:     return \%current_permissions;
                   11036: }
                   11037: 
                   11038: #---------------------------------------------Get portfolio file access controls
                   11039: 
1.749     raeburn  11040: sub get_access_controls {
1.745     raeburn  11041:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 11042:     my %access;
                   11043:     my $real_file = $file;
                   11044:     $file =~ s/\.meta$//;
1.745     raeburn  11045:     if (defined($file)) {
1.749     raeburn  11046:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   11047:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 11048:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  11049:             }
                   11050:         }
1.745     raeburn  11051:     } else {
1.749     raeburn  11052:         foreach my $key (keys(%{$current_permissions})) {
                   11053:             if ($key =~ /\0accesscontrol$/) {
                   11054:                 if (defined($group)) {
                   11055:                     if ($key !~ m-^\Q$group\E/-) {
                   11056:                         next;
                   11057:                     }
                   11058:                 }
                   11059:                 my ($fullpath) = split(/\0/,$key);
                   11060:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   11061:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   11062:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   11063:                     }
                   11064:                 }
                   11065:             }
                   11066:         }
                   11067:     }
                   11068:     return %access;
                   11069: }
                   11070: 
                   11071: sub modify_access_controls {
                   11072:     my ($file_name,$changes,$domain,$user)=@_;
                   11073:     my ($outcome,$deloutcome);
                   11074:     my %store_permissions;
                   11075:     my %new_values;
                   11076:     my %new_control;
                   11077:     my %translation;
                   11078:     my @deletions = ();
                   11079:     my $now = time;
                   11080:     if (exists($$changes{'activate'})) {
                   11081:         if (ref($$changes{'activate'}) eq 'HASH') {
                   11082:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   11083:             my $numnew = scalar(@newitems);
                   11084:             for (my $i=0; $i<$numnew; $i++) {
                   11085:                 my $newkey = $newitems[$i];
                   11086:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  11087:                 if ($newkey =~ /^\d+:/) { 
                   11088:                     $newkey =~ s/^(\d+)/$newid/;
                   11089:                     $translation{$1} = $newid;
                   11090:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   11091:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   11092:                     $translation{$1} = $newid;
                   11093:                 }
1.749     raeburn  11094:                 $new_values{$file_name."\0".$newkey} = 
                   11095:                                           $$changes{'activate'}{$newitems[$i]};
                   11096:                 $new_control{$newkey} = $now;
                   11097:             }
                   11098:         }
                   11099:     }
                   11100:     my %todelete;
                   11101:     my %changed_items;
                   11102:     foreach my $action ('delete','update') {
                   11103:         if (exists($$changes{$action})) {
                   11104:             if (ref($$changes{$action}) eq 'HASH') {
                   11105:                 foreach my $key (keys(%{$$changes{$action}})) {
                   11106:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   11107:                     if ($action eq 'delete') { 
                   11108:                         $todelete{$itemnum} = 1;
                   11109:                     } else {
                   11110:                         $changed_items{$itemnum} = $key;
                   11111:                     }
                   11112:                 }
1.745     raeburn  11113:             }
                   11114:         }
1.749     raeburn  11115:     }
                   11116:     # get lock on access controls for file.
                   11117:     my $lockhash = {
                   11118:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   11119:                                                        ':'.$env{'user.domain'},
                   11120:                    }; 
                   11121:     my $tries = 0;
                   11122:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11123:    
1.1172.2.79  raeburn  11124:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  11125:         $tries ++;
1.1172.2.79  raeburn  11126:         sleep(0.1);
1.749     raeburn  11127:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11128:     }
                   11129:     if ($gotlock eq 'ok') {
                   11130:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   11131:         my ($tmp)=keys(%curr_permissions);
                   11132:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   11133:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   11134:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   11135:             if (ref($curr_controls) eq 'HASH') {
                   11136:                 foreach my $control_item (keys(%{$curr_controls})) {
                   11137:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   11138:                     if (defined($todelete{$itemnum})) {
                   11139:                         push(@deletions,$file_name."\0".$control_item);
                   11140:                     } else {
                   11141:                         if (defined($changed_items{$itemnum})) {
                   11142:                             $new_control{$changed_items{$itemnum}} = $now;
                   11143:                             push(@deletions,$file_name."\0".$control_item);
                   11144:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   11145:                         } else {
                   11146:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   11147:                         }
                   11148:                     }
1.745     raeburn  11149:                 }
                   11150:             }
                   11151:         }
1.970     raeburn  11152:         my ($group);
                   11153:         if (&is_course($domain,$user)) {
                   11154:             ($group,my $file) = split(/\//,$file_name,2);
                   11155:         }
1.749     raeburn  11156:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   11157:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   11158:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   11159:         #  remove lock
                   11160:         my @del_lock = ($file_name."\0".'locked_access_records');
                   11161:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  11162:         my $sqlresult =
1.970     raeburn  11163:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  11164:                                     $group);
1.749     raeburn  11165:     } else {
                   11166:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  11167:     }
1.749     raeburn  11168:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  11169: }
                   11170: 
1.827     raeburn  11171: sub make_public_indefinitely {
                   11172:     my ($requrl) = @_;
                   11173:     my $now = time;
                   11174:     my $action = 'activate';
                   11175:     my $aclnum = 0;
                   11176:     if (&is_portfolio_url($requrl)) {
                   11177:         my (undef,$udom,$unum,$file_name,$group) =
                   11178:             &parse_portfolio_url($requrl);
                   11179:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   11180:         my %access_controls = &get_access_controls($current_perms,
                   11181:                                                    $group,$file_name);
                   11182:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   11183:             my ($num,$scope,$end,$start) = 
                   11184:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   11185:             if ($scope eq 'public') {
                   11186:                 if ($start <= $now && $end == 0) {
                   11187:                     $action = 'none';
                   11188:                 } else {
                   11189:                     $action = 'update';
                   11190:                     $aclnum = $num;
                   11191:                 }
                   11192:                 last;
                   11193:             }
                   11194:         }
                   11195:         if ($action eq 'none') {
                   11196:              return 'ok';
                   11197:         } else {
                   11198:             my %changes;
                   11199:             my $newend = 0;
                   11200:             my $newstart = $now;
                   11201:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   11202:             $changes{$action}{$newkey} = {
                   11203:                 type => 'public',
                   11204:                 time => {
                   11205:                     start => $newstart,
                   11206:                     end   => $newend,
                   11207:                 },
                   11208:             };
                   11209:             my ($outcome,$deloutcome,$new_values,$translation) =
                   11210:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   11211:             return $outcome;
                   11212:         }
                   11213:     } else {
                   11214:         return 'invalid';
                   11215:     }
                   11216: }
                   11217: 
1.745     raeburn  11218: #------------------------------------------------------Get Marked as Read Only
                   11219: 
                   11220: sub get_marked_as_readonly {
                   11221:     my ($domain,$user,$what,$group) = @_;
                   11222:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 11223:     my @readonly_files;
1.629     banghart 11224:     my $cmp1=$what;
                   11225:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  11226:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11227:         if (defined($group)) {
                   11228:             if ($file_name !~ m-^\Q$group\E/-) {
                   11229:                 next;
                   11230:             }
                   11231:         }
1.561     banghart 11232:         if (ref($value) eq "ARRAY"){
                   11233:             foreach my $stored_what (@{$value}) {
1.629     banghart 11234:                 my $cmp2=$stored_what;
1.759     albertel 11235:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  11236:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  11237:                 }
1.629     banghart 11238:                 if ($cmp1 eq $cmp2) {
1.561     banghart 11239:                     push(@readonly_files, $file_name);
1.745     raeburn  11240:                     last;
1.563     banghart 11241:                 } elsif (!defined($what)) {
                   11242:                     push(@readonly_files, $file_name);
1.745     raeburn  11243:                     last;
1.561     banghart 11244:                 }
                   11245:             }
1.745     raeburn  11246:         }
1.561     banghart 11247:     }
                   11248:     return @readonly_files;
                   11249: }
1.577     banghart 11250: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 11251: 
1.577     banghart 11252: sub get_marked_as_readonly_hash {
1.745     raeburn  11253:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 11254:     my %readonly_files;
1.745     raeburn  11255:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11256:         if (defined($group)) {
                   11257:             if ($file_name !~ m-^\Q$group\E/-) {
                   11258:                 next;
                   11259:             }
                   11260:         }
1.577     banghart 11261:         if (ref($value) eq "ARRAY"){
                   11262:             foreach my $stored_what (@{$value}) {
1.745     raeburn  11263:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 11264:                     foreach my $lock_descriptor(@{$stored_what}) {
                   11265:                         if ($lock_descriptor eq 'graded') {
                   11266:                             $readonly_files{$file_name} = 'graded';
                   11267:                         } elsif ($lock_descriptor eq 'handback') {
                   11268:                             $readonly_files{$file_name} = 'handback';
                   11269:                         } else {
                   11270:                             if (!exists($readonly_files{$file_name})) {
                   11271:                                 $readonly_files{$file_name} = 'locked';
                   11272:                             }
                   11273:                         }
1.745     raeburn  11274:                     }
1.750     banghart 11275:                 } 
1.577     banghart 11276:             }
                   11277:         } 
                   11278:     }
                   11279:     return %readonly_files;
                   11280: }
1.559     banghart 11281: # ------------------------------------------------------------ Unmark as Read Only
                   11282: 
                   11283: sub unmark_as_readonly {
1.629     banghart 11284:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   11285:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  11286:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 11287:     $file_name = &declutter_portfile($file_name);
1.634     albertel 11288:     my $symb_crs = $what;
                   11289:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  11290:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 11291:     my ($tmp)=keys(%current_permissions);
                   11292:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11293:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 11294:     foreach my $file (@readonly_files) {
1.759     albertel 11295: 	my $clean_file = &declutter_portfile($file);
                   11296: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 11297: 	my $current_locks = $current_permissions{$file};
1.563     banghart 11298:         my @new_locks;
                   11299:         my @del_keys;
                   11300:         if (ref($current_locks) eq "ARRAY"){
                   11301:             foreach my $locker (@{$current_locks}) {
1.632     albertel 11302:                 my $compare=$locker;
1.749     raeburn  11303:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  11304:                     $compare=join('',@{$locker});
1.746     raeburn  11305:                     if ($compare ne $symb_crs) {
                   11306:                         push(@new_locks, $locker);
                   11307:                     }
1.563     banghart 11308:                 }
                   11309:             }
1.650     albertel 11310:             if (scalar(@new_locks) > 0) {
1.563     banghart 11311:                 $current_permissions{$file} = \@new_locks;
                   11312:             } else {
                   11313:                 push(@del_keys, $file);
1.613     albertel 11314:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11315:                 delete($current_permissions{$file});
1.563     banghart 11316:             }
                   11317:         }
1.561     banghart 11318:     }
1.613     albertel 11319:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11320:     return;
                   11321: }
1.512     banghart 11322: 
1.17      www      11323: # ------------------------------------------------------------ Directory lister
                   11324: 
                   11325: sub dirlist {
1.955     raeburn  11326:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11327:     $uri=~s/^\///;
                   11328:     $uri=~s/\/$//;
1.253     stredwic 11329:     my ($udom, $uname);
1.955     raeburn  11330:     if ($getuserdir) {
1.253     stredwic 11331:         $udom = $userdomain;
                   11332:         $uname = $username;
1.955     raeburn  11333:     } else {
                   11334:         (undef,$udom,$uname)=split(/\//,$uri);
                   11335:         if(defined($userdomain)) {
                   11336:             $udom = $userdomain;
                   11337:         }
                   11338:         if(defined($username)) {
                   11339:             $uname = $username;
                   11340:         }
1.253     stredwic 11341:     }
1.955     raeburn  11342:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11343: 
1.955     raeburn  11344:     $dirRoot = $perlvar{'lonDocRoot'};
                   11345:     if (defined($getpropath)) {
                   11346:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11347:         $dirRoot =~ s/\/$//;
1.955     raeburn  11348:     } elsif (defined($getuserdir)) {
                   11349:         my $subdir=$uname.'__';
                   11350:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11351:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11352:                    ."/$udom/$subdir/$uname";
                   11353:     } elsif (defined($alternateRoot)) {
                   11354:         $dirRoot = $alternateRoot;
1.751     banghart 11355:     }
1.253     stredwic 11356: 
                   11357:     if($udom) {
                   11358:         if($uname) {
1.1135    raeburn  11359:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11360:             if ($uhome eq 'no_host') {
                   11361:                 return ([],'no_host');
                   11362:             }
1.955     raeburn  11363:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11364:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11365:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11366:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11367:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11368:             } else {
                   11369:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11370:             }
1.605     matthew  11371:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11372:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11373:                 @listing_results = split(/:/,$listing);
                   11374:             } else {
                   11375:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11376:             }
1.1135    raeburn  11377:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11378:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11379:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11380:                 return ([],$listing);
                   11381:             } else {
                   11382:                 return (\@listing_results);
1.1135    raeburn  11383:             }
1.955     raeburn  11384:         } elsif(!$alternateRoot) {
1.1136    raeburn  11385:             my (%allusers,%listerror);
1.841     albertel 11386: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11387:  	    foreach my $tryserver (keys(%servers)) {
                   11388:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11389:                                   &escape($udom),$tryserver);
                   11390:                 if ($listing eq 'unknown_cmd') {
                   11391: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11392: 				      $udom, $tryserver);
                   11393:                 } else {
                   11394:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11395:                 }
1.841     albertel 11396: 		if ($listing eq 'unknown_cmd') {
                   11397: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11398: 				      $udom, $tryserver);
                   11399: 		    @listing_results = split(/:/,$listing);
                   11400: 		} else {
                   11401: 		    @listing_results =
                   11402: 			map { &unescape($_); } split(/:/,$listing);
                   11403: 		}
1.1136    raeburn  11404:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11405:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11406:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11407:                     $listerror{$tryserver} = $listing;
                   11408:                 } else {
1.841     albertel 11409: 		    foreach my $line (@listing_results) {
                   11410: 			my ($entry) = split(/&/,$line,2);
                   11411: 			$allusers{$entry} = 1;
                   11412: 		    }
                   11413: 		}
1.253     stredwic 11414:             }
1.1136    raeburn  11415:             my @alluserslist=();
1.800     albertel 11416:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11417:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11418:             }
1.1172.2.80  raeburn  11419:             if (!%listerror) {
                   11420:                 # no errors
                   11421:                 return (\@alluserslist);
                   11422:             } elsif (scalar(keys(%servers)) == 1) {
                   11423:                 # one library server, one error
                   11424:                 my ($key) = keys(%listerror);
                   11425:                 return (\@alluserslist, $listerror{$key});
                   11426:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11427:                 # con_lost indicates that we might miss data from at least one
                   11428:                 # library server
                   11429:                 return (\@alluserslist, 'con_lost');
                   11430:             } else {
                   11431:                 # multiple library servers and no con_lost -> data should be
                   11432:                 # complete.
                   11433:                 return (\@alluserslist);
                   11434:             }
                   11435: 
1.253     stredwic 11436:         } else {
1.1136    raeburn  11437:             return ([],'missing username');
1.253     stredwic 11438:         }
1.955     raeburn  11439:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11440:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11441:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11442:         return (\@all_domains);
1.955     raeburn  11443:     } else {
1.1136    raeburn  11444:         return ([],'missing domain');
1.275     stredwic 11445:     }
                   11446: }
                   11447: 
                   11448: # --------------------------------------------- GetFileTimestamp
                   11449: # This function utilizes dirlist and returns the date stamp for
                   11450: # when it was last modified.  It will also return an error of -1
                   11451: # if an error occurs
                   11452: 
                   11453: sub GetFileTimestamp {
1.955     raeburn  11454:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11455:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11456:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11457:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11458:                                     undef,$getuserdir);
                   11459:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11460:         return -1;
                   11461:     }
                   11462:     if (ref($fileref) eq 'ARRAY') {
                   11463:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11464:         # @stats contains first the filename, then the stat output
                   11465:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11466:     } else {
                   11467:         return -1;
1.253     stredwic 11468:     }
1.26      www      11469: }
                   11470: 
1.712     albertel 11471: sub stat_file {
                   11472:     my ($uri) = @_;
1.787     albertel 11473:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11474: 
1.955     raeburn  11475:     my ($udom,$uname,$file);
1.712     albertel 11476:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11477: 	($udom,$uname,$file) =
1.811     albertel 11478: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11479: 	$file = 'userfiles/'.$file;
                   11480:     }
                   11481:     if ($uri =~ m-^/res/-) {
                   11482: 	($udom,$uname) = 
1.807     albertel 11483: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11484: 	$file = $uri;
                   11485:     }
                   11486: 
                   11487:     if (!$udom || !$uname || !$file) {
                   11488: 	# unable to handle the uri
                   11489: 	return ();
                   11490:     }
1.956     raeburn  11491:     my $getpropath;
                   11492:     if ($file =~ /^userfiles\//) {
                   11493:         $getpropath = 1;
                   11494:     }
1.1136    raeburn  11495:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11496:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11497:         return ();
                   11498:     } else {
                   11499:         if (ref($listref) eq 'ARRAY') {
                   11500:             my @stats = split('&',$listref->[0]);
                   11501: 	    shift(@stats); #filename is first
                   11502: 	    return @stats;
                   11503:         }
1.712     albertel 11504:     }
                   11505:     return ();
                   11506: }
                   11507: 
1.26      www      11508: # -------------------------------------------------------- Value of a Condition
                   11509: 
1.713     albertel 11510: # gets the value of a specific preevaluated condition
                   11511: #    stored in the string  $env{user.state.<cid>}
                   11512: # or looks up a condition reference in the bighash and if if hasn't
                   11513: # already been evaluated recurses into docondval to get the value of
                   11514: # the condition, then memoizing it to 
                   11515: #   $env{user.state.<cid>.<condition>}
1.40      www      11516: sub directcondval {
                   11517:     my $number=shift;
1.620     albertel 11518:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11519: 	&Apache::lonuserstate::evalstate();
                   11520:     }
1.713     albertel 11521:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11522: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11523:     } elsif ($number =~ /^_/) {
                   11524: 	my $sub_condition;
                   11525: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11526: 		&GDBM_READER(),0640)) {
                   11527: 	    $sub_condition=$bighash{'conditions'.$number};
                   11528: 	    untie(%bighash);
                   11529: 	}
                   11530: 	my $value = &docondval($sub_condition);
1.949     raeburn  11531: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11532: 	return $value;
                   11533:     }
1.620     albertel 11534:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11535:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11536:     } else {
                   11537:        return 2;
                   11538:     }
                   11539: }
                   11540: 
1.713     albertel 11541: # get the collection of conditions for this resource
1.26      www      11542: sub condval {
                   11543:     my $condidx=shift;
1.54      www      11544:     my $allpathcond='';
1.713     albertel 11545:     foreach my $cond (split(/\|/,$condidx)) {
                   11546: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11547: 	    $allpathcond.=
                   11548: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11549: 	}
1.191     harris41 11550:     }
1.54      www      11551:     $allpathcond=~s/\|$//;
1.713     albertel 11552:     return &docondval($allpathcond);
                   11553: }
                   11554: 
                   11555: #evaluates an expression of conditions
                   11556: sub docondval {
                   11557:     my ($allpathcond) = @_;
                   11558:     my $result=0;
                   11559:     if ($env{'request.course.id'}
                   11560: 	&& defined($allpathcond)) {
                   11561: 	my $operand='|';
                   11562: 	my @stack;
                   11563: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11564: 	    if ($chunk eq '(') {
                   11565: 		push @stack,($operand,$result);
                   11566: 	    } elsif ($chunk eq ')') {
                   11567: 		my $before=pop @stack;
                   11568: 		if (pop @stack eq '&') {
                   11569: 		    $result=$result>$before?$before:$result;
                   11570: 		} else {
                   11571: 		    $result=$result>$before?$result:$before;
                   11572: 		}
                   11573: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11574: 		$operand=$chunk;
                   11575: 	    } else {
                   11576: 		my $new=directcondval($chunk);
                   11577: 		if ($operand eq '&') {
                   11578: 		    $result=$result>$new?$new:$result;
                   11579: 		} else {
                   11580: 		    $result=$result>$new?$result:$new;
                   11581: 		}
                   11582: 	    }
                   11583: 	}
1.26      www      11584:     }
                   11585:     return $result;
1.421     albertel 11586: }
                   11587: 
                   11588: # ---------------------------------------------------- Devalidate courseresdata
                   11589: 
                   11590: sub devalidatecourseresdata {
                   11591:     my ($coursenum,$coursedomain)=@_;
                   11592:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11593:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11594: }
                   11595: 
1.763     www      11596: 
1.200     www      11597: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11598: #
                   11599: #  Parameters:
                   11600: #      $coursenum    - Number of the course.
                   11601: #      $coursedomain - Domain at which the course was created.
                   11602: #  Returns:
                   11603: #     A hash of the course parameters along (I think) with timestamps
                   11604: #     and version info.
1.877     foxr     11605: 
1.624     albertel 11606: sub get_courseresdata {
                   11607:     my ($coursenum,$coursedomain)=@_;
1.200     www      11608:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11609:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11610:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11611:     my %dumpreply;
1.417     albertel 11612:     unless (defined($cached)) {
1.624     albertel 11613: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11614: 	$result=\%dumpreply;
1.251     albertel 11615: 	my ($tmp) = keys(%dumpreply);
                   11616: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11617: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11618: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11619: 	    return $tmp;
1.416     albertel 11620: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11621: 	    $result=undef;
1.599     albertel 11622: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11623: 	}
                   11624:     }
1.624     albertel 11625:     return $result;
                   11626: }
                   11627: 
1.633     albertel 11628: sub devalidateuserresdata {
                   11629:     my ($uname,$udom)=@_;
                   11630:     my $hashid="$udom:$uname";
                   11631:     &devalidate_cache_new('userres',$hashid);
                   11632: }
                   11633: 
1.624     albertel 11634: sub get_userresdata {
                   11635:     my ($uname,$udom)=@_;
                   11636:     #most student don\'t have any data set, check if there is some data
                   11637:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11638: 
                   11639:     my $hashid="$udom:$uname";
                   11640:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11641:     if (!defined($cached)) {
                   11642: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11643: 	$result=\%resourcedata;
                   11644: 	&do_cache_new('userres',$hashid,$result,600);
                   11645:     }
                   11646:     my ($tmp)=keys(%$result);
                   11647:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11648: 	return $result;
                   11649:     }
                   11650:     #error 2 occurs when the .db doesn't exist
                   11651:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11652:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11653: 	    &logthis("<font color=\"blue\">WARNING:".
                   11654: 		     " Trying to get resource data for ".
                   11655: 		     $uname." at ".$udom.": ".
                   11656: 		     $tmp."</font>");
                   11657:         }
1.624     albertel 11658:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11659: 	#&EXT_cache_set($udom,$uname);
                   11660: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11661: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11662:     }
                   11663:     return $tmp;
                   11664: }
1.879     foxr     11665: #----------------------------------------------- resdata - return resource data
                   11666: #  Purpose:
                   11667: #    Return resource data for either users or for a course.
                   11668: #  Parameters:
                   11669: #     $name      - Course/user name.
                   11670: #     $domain    - Name of the domain the user/course is registered on.
                   11671: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   11672: #     @which     - Array of names of resources desired.
                   11673: #  Returns:
                   11674: #     The value of the first reasource in @which that is found in the
                   11675: #     resource hash.
                   11676: #  Exceptional Conditions:
                   11677: #     If the $type passed in is not valid (not the string 'course' or 
                   11678: #     'user', an undefined  reference is returned.
                   11679: #     If none of the resources are found, an undef is returned
1.624     albertel 11680: sub resdata {
                   11681:     my ($name,$domain,$type,@which)=@_;
                   11682:     my $result;
                   11683:     if ($type eq 'course') {
                   11684: 	$result=&get_courseresdata($name,$domain);
                   11685:     } elsif ($type eq 'user') {
                   11686: 	$result=&get_userresdata($name,$domain);
                   11687:     }
                   11688:     if (!ref($result)) { return $result; }    
1.251     albertel 11689:     foreach my $item (@which) {
1.927     albertel 11690: 	if (defined($result->{$item->[0]})) {
                   11691: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11692: 	}
1.250     albertel 11693:     }
1.291     albertel 11694:     return undef;
1.200     www      11695: }
                   11696: 
1.1172.2.146.  .1(raebu 11697:22): sub get_domain_lti {
                   11698:22):     my ($cdom,$context) = @_;
                   11699:22):     my ($name,%lti);
                   11700:22):     if ($context eq 'consumer') {
                   11701:22):         $name = 'ltitools';
                   11702:22):     } elsif ($context eq 'provider') {
                   11703:22):         $name = 'lti';
                   11704:22):     } else {
                   11705:22):         return %lti;
                   11706:22):     }
                   11707:22):     my ($result,$cached)=&is_cached_new($name,$cdom);
                   11708:22):     if (defined($cached)) {
                   11709:22):         if (ref($result) eq 'HASH') {
                   11710:22):             %lti = %{$result};
                   11711:22):         }
                   11712:22):     } else {
                   11713:22):         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   11714:22):         if (ref($domconfig{$name}) eq 'HASH') {
                   11715:22):             %lti = %{$domconfig{$name}};
                   11716:22):             my %encdomconfig = &get_dom('encconfig',[$name],$cdom,undef,1);
                   11717:22):             if (ref($encdomconfig{$name}) eq 'HASH') {
                   11718:22):                 foreach my $id (keys(%lti)) {
                   11719:22):                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
                   11720:22):                         foreach my $item ('key','secret') {
                   11721:22):                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
                   11722:22):                         }
                   11723:22):                     }
                   11724:22):                 }
                   11725:22):             }
                   11726:22):         }
                   11727:22):         my $cachetime = 24*60*60;
                   11728:22):         &do_cache_new($name,$cdom,\%lti,$cachetime);
                   11729:22):     }
                   11730:22):     return %lti;
                   11731:22): }
                   11732:22): 
                   11733:22): sub get_course_lti {
                   11734:22):     my ($cnum,$cdom) = @_;
                   11735:22):     my $hashid=$cdom.'_'.$cnum;
                   11736:22):     my %courselti;
                   11737:22):     my ($result,$cached)=&is_cached_new('courselti',$hashid);
                   11738:22):     if (defined($cached)) {
                   11739:22):         if (ref($result) eq 'HASH') {
                   11740:22):             %courselti = %{$result};
                   11741:22):         }
                   11742:22):     } else {
                   11743:22):         %courselti = &dump('lti',$cdom,$cnum,undef,undef,undef,1);
                   11744:22):         my $cachetime = 24*60*60;
                   11745:22):         &do_cache_new('courselti',$hashid,\%courselti,$cachetime);
                   11746:22):     }
                   11747:22):     return %courselti;
                   11748:22): }
                   11749:22): 
          .3(raebu 11750:22): sub courselti_itemid {
                   11751:22):     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
                   11752:22):     my ($chome,$itemid);
                   11753:22):     $chome = &homeserver($cnum,$cdom);
                   11754:22):     return if ($chome eq 'no_host');
                   11755:22):     if (ref($params) eq 'HASH') {
                   11756:22):         my $items = &freeze_escape($params);
                   11757:22):         my $rep;
                   11758:22):         if (grep { $_ eq $chome } current_machine_ids()) {
                   11759:22):             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
                   11760:22):         } else {
                   11761:22):             my $escurl = &escape($url);
                   11762:22):             my $escmethod = &escape($method);
                   11763:22):             my $items = &freeze_escape($params);
                   11764:22):             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
                   11765:22):         }
                   11766:22):         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   11767:22):                 ($rep eq 'unknown_cmd')) {
                   11768:22):             $itemid = $rep;
                   11769:22):         }
                   11770:22):     }
                   11771:22):     return $itemid;
                   11772:22): }
                   11773:22): 
                   11774:22): sub domainlti_itemid {
                   11775:22):     my ($cdom,$url,$method,$params,$context) = @_;
                   11776:22):     my ($primary_id,$itemid);
                   11777:22):     $primary_id = &domain($cdom,'primary');
                   11778:22):     return if ($primary_id eq '');
                   11779:22):     if (ref($params) eq 'HASH') {
                   11780:22):         my $items = &freeze_escape($params);
                   11781:22):         my $rep;
                   11782:22):         if (grep { $_ eq $primary_id } current_machine_ids()) {
                   11783:22):             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
                   11784:22):         } else {
                   11785:22):             my $cnum = '';
                   11786:22):             my $escurl = &escape($url);
                   11787:22):             my $escmethod = &escape($method);
                   11788:22):             my $items = &freeze_escape($params);
                   11789:22):             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
                   11790:22):         }
                   11791:22):         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   11792:22):                 ($rep eq 'unknown_cmd')) {
                   11793:22):             $itemid = $rep;
                   11794:22):         }
                   11795:22):     }
                   11796:22):     return $itemid;
                   11797:22): }
                   11798:22): 
1.1172.2.31  raeburn  11799: sub get_numsuppfiles {
                   11800:     my ($cnum,$cdom,$ignorecache)=@_;
                   11801:     my $hashid=$cnum.':'.$cdom;
                   11802:     my ($suppcount,$cached);
                   11803:     unless ($ignorecache) {
                   11804:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11805:     }
                   11806:     unless (defined($cached)) {
                   11807:         my $chome=&homeserver($cnum,$cdom);
                   11808:         unless ($chome eq 'no_host') {
                   11809:             ($suppcount,my $errors) = (0,0);
                   11810:             my $suppmap = 'supplemental.sequence';
                   11811:             ($suppcount,$errors) =
                   11812:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11813:         }
                   11814:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11815:     }
                   11816:     return $suppcount;
                   11817: }
                   11818: 
1.379     matthew  11819: #
                   11820: # EXT resource caching routines
                   11821: #
                   11822: 
1.1172.2.146.  .1(raebu 11823:22): {
                   11824:22): # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   11825:22): #
                   11826:22): # The course for which we cache
                   11827:22): my $cachedmapkey='';
                   11828:22): # The cached recursive maps for this course
                   11829:22): my %cachedmaps=();
                   11830:22): # When this was last done
                   11831:22): my $cachedmaptime='';
                   11832:22): 
1.379     matthew  11833: sub clear_EXT_cache_status {
1.383     albertel 11834:     &delenv('cache.EXT.');
1.379     matthew  11835: }
                   11836: 
                   11837: sub EXT_cache_status {
                   11838:     my ($target_domain,$target_user) = @_;
1.383     albertel 11839:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11840:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11841:         # We know already the user has no data
                   11842:         return 1;
                   11843:     } else {
                   11844:         return 0;
                   11845:     }
                   11846: }
                   11847: 
                   11848: sub EXT_cache_set {
                   11849:     my ($target_domain,$target_user) = @_;
1.383     albertel 11850:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11851:     #&appenv({$cachename => time});
1.379     matthew  11852: }
                   11853: 
1.28      www      11854: # --------------------------------------------------------- Value of a Variable
1.58      www      11855: sub EXT {
1.715     albertel 11856: 
1.1172.2.28  raeburn  11857:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11858:     unless ($varname) { return ''; }
1.218     albertel 11859:     #get real user name/domain, courseid and symb
                   11860:     my $courseid;
1.359     albertel 11861:     my $publicuser;
1.427     www      11862:     if ($symbparm) {
                   11863: 	$symbparm=&get_symb_from_alias($symbparm);
                   11864:     }
1.218     albertel 11865:     if (!($uname && $udom)) {
1.790     albertel 11866:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11867:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11868:     } else {
1.620     albertel 11869: 	$courseid=$env{'request.course.id'};
1.218     albertel 11870:     }
1.48      www      11871:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11872:     my $rest;
1.320     albertel 11873:     if (defined($therest[0])) {
1.48      www      11874:        $rest=join('.',@therest);
                   11875:     } else {
                   11876:        $rest='';
                   11877:     }
1.320     albertel 11878: 
1.57      www      11879:     my $qualifierrest=$qualifier;
                   11880:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11881:     my $spacequalifierrest=$space;
                   11882:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11883:     if ($realm eq 'user') {
1.48      www      11884: # --------------------------------------------------------------- user.resource
                   11885: 	if ($space eq 'resource') {
1.651     albertel 11886: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11887: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11888: 		 &&
1.1172.2.142  raeburn  11889: 		 ($symbparm eq &symbread()) ) {
1.744     albertel 11890: 		# if we are in the middle of processing the resource the
                   11891: 		# get the value we are planning on committing
                   11892:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11893:                     return $Apache::lonhomework::results{$qualifierrest};
                   11894:                 } else {
                   11895:                     return $Apache::lonhomework::history{$qualifierrest};
                   11896:                 }
1.335     albertel 11897: 	    } else {
1.359     albertel 11898: 		my %restored;
1.620     albertel 11899: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11900: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11901: 		} else {
                   11902: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11903: 		}
1.335     albertel 11904: 		return $restored{$qualifierrest};
                   11905: 	    }
1.48      www      11906: # ----------------------------------------------------------------- user.access
                   11907:         } elsif ($space eq 'access') {
1.218     albertel 11908: 	    # FIXME - not supporting calls for a specific user
1.48      www      11909:             return &allowed($qualifier,$rest);
                   11910: # ------------------------------------------ user.preferences, user.environment
                   11911:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11912: 	    if (($uname eq $env{'user.name'}) &&
                   11913: 		($udom eq $env{'user.domain'})) {
                   11914: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11915: 	    } else {
1.359     albertel 11916: 		my %returnhash;
                   11917: 		if (!$publicuser) {
                   11918: 		    %returnhash=&userenvironment($udom,$uname,
                   11919: 						 $qualifierrest);
                   11920: 		}
1.218     albertel 11921: 		return $returnhash{$qualifierrest};
                   11922: 	    }
1.48      www      11923: # ----------------------------------------------------------------- user.course
                   11924:         } elsif ($space eq 'course') {
1.218     albertel 11925: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11926:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11927: # ------------------------------------------------------------------- user.role
                   11928:         } elsif ($space eq 'role') {
1.218     albertel 11929: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11930:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11931:             if ($qualifier eq 'value') {
                   11932: 		return $role;
                   11933:             } elsif ($qualifier eq 'extent') {
                   11934:                 return $where;
                   11935:             }
                   11936: # ----------------------------------------------------------------- user.domain
                   11937:         } elsif ($space eq 'domain') {
1.218     albertel 11938:             return $udom;
1.48      www      11939: # ------------------------------------------------------------------- user.name
                   11940:         } elsif ($space eq 'name') {
1.218     albertel 11941:             return $uname;
1.48      www      11942: # ---------------------------------------------------- Any other user namespace
1.29      www      11943:         } else {
1.359     albertel 11944: 	    my %reply;
                   11945: 	    if (!$publicuser) {
                   11946: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11947: 	    }
                   11948: 	    return $reply{$qualifierrest};
1.48      www      11949:         }
1.236     www      11950:     } elsif ($realm eq 'query') {
                   11951: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11952:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11953: 						[$spacequalifierrest]);
1.620     albertel 11954: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11955:    } elsif ($realm eq 'request') {
1.48      www      11956: # ------------------------------------------------------------- request.browser
                   11957:         if ($space eq 'browser') {
1.1145    bisitz   11958:             return $env{'browser.'.$qualifier};
1.57      www      11959: # ------------------------------------------------------------ request.filename
                   11960:         } else {
1.620     albertel 11961:             return $env{'request.'.$spacequalifierrest};
1.29      www      11962:         }
1.28      www      11963:     } elsif ($realm eq 'course') {
1.48      www      11964: # ---------------------------------------------------------- course.description
1.620     albertel 11965:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11966:     } elsif ($realm eq 'resource') {
1.165     www      11967: 
1.620     albertel 11968: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11969: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11970: 	}
1.693     albertel 11971: 
1.1172.2.30  raeburn  11972:         if ($qualifier eq '') {
                   11973: 	    if ($space eq 'title') {
                   11974: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11975: 	        return &gettitle($symbparm);
                   11976: 	    }
1.693     albertel 11977: 	
1.1172.2.30  raeburn  11978: 	    if ($space eq 'map') {
                   11979: 	        my ($map) = &decode_symb($symbparm);
                   11980: 	        return &symbread($map);
                   11981: 	    }
                   11982:             if ($space eq 'maptitle') {
                   11983:                 my ($map) = &decode_symb($symbparm);
                   11984:                 return &gettitle($map);
                   11985:             }
                   11986: 	    if ($space eq 'filename') {
                   11987: 	        if ($symbparm) {
                   11988: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11989: 	        }
                   11990: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11991: 	    }
1.1172.2.30  raeburn  11992: 
                   11993:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11994:                 if ($space eq 'visibleparts') {
                   11995:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11996:                     my $item;
                   11997:                     if (ref($navmap)) {
                   11998:                         my $res = $navmap->getBySymb($symbparm);
                   11999:                         my $parts = $res->parts();
                   12000:                         if (ref($parts) eq 'ARRAY') {
                   12001:                             $item = join(',',@{$parts});
                   12002:                         }
                   12003:                         undef($navmap);
                   12004:                     }
                   12005:                     return $item;
                   12006:                 }
                   12007:             }
                   12008:         }
1.693     albertel 12009: 
                   12010: 	my ($section, $group, @groups);
1.593     albertel 12011: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  12012:         if (($courseid eq '') && ($cid)) {
                   12013:             $courseid = $cid;
                   12014:         }
                   12015: 	if (($symbparm && $courseid) && 
                   12016: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      12017: 
1.218     albertel 12018: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      12019: 
1.60      www      12020: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 12021: 	    my $symbp=$symbparm;
1.735     albertel 12022: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 12023: 
                   12024: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   12025: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   12026: 
1.620     albertel 12027: 	    if (($env{'user.name'} eq $uname) &&
                   12028: 		($env{'user.domain'} eq $udom)) {
                   12029: 		$section=$env{'request.course.sec'};
1.733     raeburn  12030:                 @groups = split(/:/,$env{'request.course.groups'});  
                   12031:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 12032: 	    } else {
1.539     albertel 12033: 		if (! defined($usection)) {
1.551     albertel 12034: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 12035: 		} else {
                   12036: 		    $section = $usection;
                   12037: 		}
1.733     raeburn  12038:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 12039: 	    }
                   12040: 
                   12041: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   12042: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   12043: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   12044: 
1.593     albertel 12045: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 12046: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 12047: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      12048: 
1.60      www      12049: # ----------------------------------------------------------- first, check user
1.624     albertel 12050: 
                   12051: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 12052: 				       ([$courselevelr,'resource'],
                   12053: 					[$courselevelm,'map'     ],
                   12054: 					[$courselevel, 'course'  ]));
1.931     albertel 12055: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      12056: 
1.594     albertel 12057: # ------------------------------------------------ second, check some of course
1.684     raeburn  12058:             my $coursereply;
1.691     raeburn  12059:             if (@groups > 0) {
                   12060:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   12061:                                        $mapparm,$spacequalifierrest);
1.927     albertel 12062:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  12063:             }
1.96      www      12064: 
1.684     raeburn  12065: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 12066: 				  $env{'course.'.$courseid.'.domain'},
                   12067: 				  'course',
                   12068: 				  ([$seclevelr,   'resource'],
                   12069: 				   [$seclevelm,   'map'     ],
                   12070: 				   [$seclevel,    'course'  ],
                   12071: 				   [$courselevelr,'resource']));
                   12072: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      12073: 
1.60      www      12074: # ------------------------------------------------------ third, check map parms
1.218     albertel 12075: 	    my %parmhash=();
                   12076: 	    my $thisparm='';
                   12077: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 12078: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 12079: 		    &GDBM_READER(),0640)) {
1.218     albertel 12080: 		$thisparm=$parmhash{$symbparm};
                   12081: 		untie(%parmhash);
                   12082: 	    }
1.927     albertel 12083: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 12084: 	}
1.594     albertel 12085: # ------------------------------------------ fourth, look in resource metadata
1.71      www      12086: 
1.218     albertel 12087: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 12088: 	my $filename;
                   12089: 	if (!$symbparm) { $symbparm=&symbread(); }
                   12090: 	if ($symbparm) {
1.409     www      12091: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 12092: 	} else {
1.620     albertel 12093: 	    $filename=$env{'request.filename'};
1.282     albertel 12094: 	}
                   12095: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 12096: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 12097: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 12098: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      12099: 
1.927     albertel 12100: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 12101: 	if ($symbparm && defined($courseid) && 
1.620     albertel 12102: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 12103: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   12104: 				     $env{'course.'.$courseid.'.domain'},
                   12105: 				     'course',
1.927     albertel 12106: 				     ([$courselevelm,'map'   ],
                   12107: 				      [$courselevel, 'course']));
                   12108: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 12109: 	}
1.145     www      12110: # ------------------------------------------------------------------ Cascade up
1.218     albertel 12111: 	unless ($space eq '0') {
1.336     albertel 12112: 	    my @parts=split(/_/,$space);
                   12113: 	    my $id=pop(@parts);
                   12114: 	    my $part=join('_',@parts);
                   12115: 	    if ($part eq '') { $part='0'; }
1.927     albertel 12116: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 12117: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  12118: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 12119: 	}
1.395     albertel 12120: 	if ($recurse) { return undef; }
                   12121: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 12122: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      12123: # ---------------------------------------------------- Any other user namespace
                   12124:     } elsif ($realm eq 'environment') {
                   12125: # ----------------------------------------------------------------- environment
1.620     albertel 12126: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   12127: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 12128: 	} else {
1.770     albertel 12129: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   12130: 		return '';
                   12131: 	    }
1.219     albertel 12132: 	    my %returnhash=&userenvironment($udom,$uname,
                   12133: 					    $spacequalifierrest);
                   12134: 	    return $returnhash{$spacequalifierrest};
                   12135: 	}
1.28      www      12136:     } elsif ($realm eq 'system') {
1.48      www      12137: # ----------------------------------------------------------------- system.time
                   12138: 	if ($space eq 'time') {
                   12139: 	    return time;
                   12140:         }
1.696     albertel 12141:     } elsif ($realm eq 'server') {
                   12142: # ----------------------------------------------------------------- system.time
                   12143: 	if ($space eq 'name') {
                   12144: 	    return $ENV{'SERVER_NAME'};
                   12145:         }
1.1172.2.146.  .1(raebu 12146:22):     } elsif ($realm eq 'client') {
                   12147:22):         if ($space eq 'remote_addr') {
                   12148:22):             return &get_requestor_ip();
                   12149:22):         }
1.28      www      12150:     }
1.48      www      12151:     return '';
1.61      www      12152: }
                   12153: 
1.927     albertel 12154: sub get_reply {
                   12155:     my ($reply_value) = @_;
1.940     raeburn  12156:     if (ref($reply_value) eq 'ARRAY') {
                   12157:         if (wantarray) {
                   12158: 	    return @$reply_value;
                   12159:         }
                   12160:         return $reply_value->[0];
                   12161:     } else {
                   12162:         return $reply_value;
1.927     albertel 12163:     }
                   12164: }
                   12165: 
1.691     raeburn  12166: sub check_group_parms {
                   12167:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   12168:     my @groupitems = ();
                   12169:     my $resultitem;
1.927     albertel 12170:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  12171:     foreach my $group (@{$groups}) {
                   12172:         foreach my $level (@levels) {
1.927     albertel 12173:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   12174:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  12175:         }
                   12176:     }
                   12177:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   12178:                             $env{'course.'.$courseid.'.domain'},
                   12179:                                      'course',@groupitems);
                   12180:     return $coursereply;
                   12181: }
                   12182: 
1.1172.2.146.  .1(raebu 12183:22): sub get_map_hierarchy {
                   12184:22):     my ($mapname,$courseid) = @_;
                   12185:22):     my @recurseup = ();
                   12186:22):     if ($mapname) {
                   12187:22):         if (($cachedmapkey eq $courseid) &&
                   12188:22):             (abs($cachedmaptime-time)<5)) {
                   12189:22):             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   12190:22):                 return @{$cachedmaps{$mapname}};
                   12191:22):             }
                   12192:22):         }
                   12193:22):         my $navmap = Apache::lonnavmaps::navmap->new();
                   12194:22):         if (ref($navmap)) {
                   12195:22):             @recurseup = $navmap->recurseup_maps($mapname);
                   12196:22):             undef($navmap);
                   12197:22):             $cachedmaps{$mapname} = \@recurseup;
                   12198:22):             $cachedmaptime=time;
                   12199:22):             $cachedmapkey=$courseid;
                   12200:22):         }
                   12201:22):     }
                   12202:22):     return @recurseup;
                   12203:22): }
                   12204:22): 
          .2(raebu 12205:22): }
          .1(raebu 12206:22): 
1.691     raeburn  12207: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  12208:     my ($courseid,@groups) = @_;
                   12209:     @groups = sort(@groups);
1.691     raeburn  12210:     return @groups;
                   12211: }
                   12212: 
1.395     albertel 12213: sub packages_tab_default {
                   12214:     my ($uri,$varname)=@_;
                   12215:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 12216: 
                   12217:     my (@extension,@specifics,$do_default);
                   12218:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 12219: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 12220: 	if ($pack_type eq 'default') {
                   12221: 	    $do_default=1;
                   12222: 	} elsif ($pack_type eq 'extension') {
                   12223: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 12224: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 12225: 	    # only look at packages defaults for packages that this id is
1.738     albertel 12226: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   12227: 	}
                   12228:     }
                   12229:     # first look for a package that matches the requested part id
                   12230:     foreach my $package (@specifics) {
                   12231: 	my (undef,$pack_type,$pack_part)=@{$package};
                   12232: 	next if ($pack_part ne $part);
                   12233: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12234: 	    return $packagetab{"$pack_type&$name&default"};
                   12235: 	}
                   12236:     }
                   12237:     # look for any possible matching non extension_ package
                   12238:     foreach my $package (@specifics) {
                   12239: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 12240: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12241: 	    return $packagetab{"$pack_type&$name&default"};
                   12242: 	}
1.585     albertel 12243: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 12244: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   12245: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 12246: 	}
                   12247:     }
1.738     albertel 12248:     # look for any posible extension_ match
                   12249:     foreach my $package (@extension) {
                   12250: 	my ($package,$pack_type)=@{$package};
                   12251: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12252: 	    return $packagetab{"$pack_type&$name&default"};
                   12253: 	}
                   12254: 	if (defined($packagetab{$package."&$name&default"})) {
                   12255: 	    return $packagetab{$package."&$name&default"};
                   12256: 	}
                   12257:     }
                   12258:     # look for a global default setting
                   12259:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   12260: 	return $packagetab{"default&$name&default"};
                   12261:     }
1.395     albertel 12262:     return undef;
                   12263: }
                   12264: 
1.334     albertel 12265: sub add_prefix_and_part {
                   12266:     my ($prefix,$part)=@_;
                   12267:     my $keyroot;
                   12268:     if (defined($prefix) && $prefix !~ /^__/) {
                   12269: 	# prefix that has a part already
                   12270: 	$keyroot=$prefix;
                   12271:     } elsif (defined($prefix)) {
                   12272: 	# prefix that is missing a part
                   12273: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   12274:     } else {
                   12275: 	# no prefix at all
                   12276: 	if (defined($part)) { $keyroot='_'.$part; }
                   12277:     }
                   12278:     return $keyroot;
                   12279: }
                   12280: 
1.71      www      12281: # ---------------------------------------------------------------- Get metadata
                   12282: 
1.599     albertel 12283: my %metaentry;
1.1070    www      12284: my %importedpartids;
1.1172.2.99  raeburn  12285: my %importedrespids;
1.71      www      12286: sub metadata {
1.176     www      12287:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      12288:     $uri=&declutter($uri);
1.288     albertel 12289:     # if it is a non metadata possible uri return quickly
1.529     albertel 12290:     if (($uri eq '') || 
                   12291: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.146.  .1(raebu 12292:22): 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  12293:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 12294: 	return undef;
                   12295:     }
1.1172.2.49  raeburn  12296:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 12297: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 12298: 	return undef;
1.288     albertel 12299:     }
1.73      www      12300:     my $filename=$uri;
                   12301:     $uri=~s/\.meta$//;
1.172     www      12302: #
                   12303: # Is the metadata already cached?
1.177     www      12304: # Look at timestamp of caching
1.172     www      12305: # Everything is cached by the main uri, libraries are never directly cached
                   12306: #
1.428     albertel 12307:     if (!defined($liburi)) {
1.599     albertel 12308: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 12309: 	if (defined($cached)) { return $result->{':'.$what}; }
                   12310:     }
                   12311:     {
1.1069    www      12312: # Imported parts would go here
1.1172.2.99  raeburn  12313:         my @origfiletagids=();
1.1069    www      12314:         my $importedparts=0;
1.1172.2.99  raeburn  12315: 
                   12316: # Imported responseids would go here
                   12317:         my $importedresponses=0;
1.172     www      12318: #
                   12319: # Is this a recursive call for a library?
                   12320: #
1.599     albertel 12321: #	if (! exists($metacache{$uri})) {
                   12322: #	    $metacache{$uri}={};
                   12323: #	}
1.924     albertel 12324: 	my $cachetime = 60*60;
1.171     www      12325:         if ($liburi) {
                   12326: 	    $liburi=&declutter($liburi);
                   12327:             $filename=$liburi;
1.401     bowersj2 12328:         } else {
1.599     albertel 12329: 	    &devalidate_cache_new('meta',$uri);
                   12330: 	    undef(%metaentry);
1.401     bowersj2 12331: 	}
1.140     www      12332:         my %metathesekeys=();
1.73      www      12333:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 12334: 	my $metastring;
1.1140    www      12335: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 12336: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 12337: 	    $metastring = 
1.929     albertel 12338: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 12339: 					  ('grade_target' => 'meta'));
                   12340: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  12341: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   12342:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 12343: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 12344: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 12345: 	    $metastring=&getfile($file);
1.489     albertel 12346: 	}
1.208     albertel 12347:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      12348:         my $token;
1.140     www      12349:         undef %metathesekeys;
1.71      www      12350:         while ($token=$parser->get_token) {
1.339     albertel 12351: 	    if ($token->[0] eq 'S') {
                   12352: 		if (defined($token->[2]->{'package'})) {
1.172     www      12353: #
                   12354: # This is a package - get package info
                   12355: #
1.339     albertel 12356: 		    my $package=$token->[2]->{'package'};
                   12357: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12358: 		    if (defined($token->[2]->{'id'})) { 
                   12359: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12360: 		    }
1.599     albertel 12361: 		    if ($metaentry{':packages'}) {
                   12362: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12363: 		    } else {
1.599     albertel 12364: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12365: 		    }
1.736     albertel 12366: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12367: 			my $part=$keyroot;
                   12368: 			$part=~s/^\_//;
1.736     albertel 12369: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12370: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12371: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12372: 			    # ignore package.tab specified default values
                   12373:                             # here &package_tab_default() will fetch those
                   12374: 			    if ($subp eq 'default') { next; }
1.736     albertel 12375: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12376: 			    my $unikey;
                   12377: 			    if ($pack =~ /_0$/) {
                   12378: 				$unikey='parameter_0_'.$name;
                   12379: 				$part=0;
                   12380: 			    } else {
                   12381: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12382: 			    }
1.339     albertel 12383: 			    if ($subp eq 'display') {
                   12384: 				$value.=' [Part: '.$part.']';
                   12385: 			    }
1.599     albertel 12386: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12387: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12388: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12389: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12390: 			    }
1.599     albertel 12391: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12392: 				$metaentry{':'.$unikey}=
                   12393: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12394: 			    }
1.339     albertel 12395: 			}
                   12396: 		    }
                   12397: 		} else {
1.172     www      12398: #
                   12399: # This is not a package - some other kind of start tag
1.339     albertel 12400: #
                   12401: 		    my $entry=$token->[1];
1.1068    www      12402: 		    my $unikey='';
1.175     www      12403: 
1.339     albertel 12404: 		    if ($entry eq 'import') {
1.175     www      12405: #
                   12406: # Importing a library here
1.339     albertel 12407: #
1.1067    www      12408:                         my $location=$parser->get_text('/import');
                   12409:                         my $dir=$filename;
                   12410:                         $dir=~s|[^/]*$||;
                   12411:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  12412: 
                   12413:                         my $importid=$token->[2]->{'id'};
1.1068    www      12414:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  12415: #
                   12416: # Check metadata for imported file to
                   12417: # see if it contained response items
                   12418: #
                   12419:                         my %currmetaentry = %metaentry;
                   12420:                         my $libresponseorder = &metadata($location,'responseorder');
                   12421:                         my $origfile;
                   12422:                         if ($libresponseorder ne '') {
                   12423:                             if ($#origfiletagids<0) {
                   12424:                                 undef(%importedrespids);
                   12425:                                 undef(%importedpartids);
                   12426:                             }
                   12427:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   12428:                             if (@{$importedrespids{$importid}} > 0) {
                   12429:                                 $importedresponses = 1;
                   12430: # We need to get the original file and the imported file to get the response order correct
                   12431: # Load and inspect original file
                   12432:                                 if ($#origfiletagids<0) {
                   12433:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12434:                                     $origfile=&getfile($origfilelocation);
                   12435:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12436:                                 }
                   12437:                             }
                   12438:                         }
                   12439: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12440: # hash populated for imported library file
                   12441:                         %metaentry = %currmetaentry;
                   12442:                         undef(%currmetaentry);
1.1068    www      12443:                         if ($importmode eq 'problem') {
1.1069    www      12444: # Import as problem/response
1.1068    www      12445:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12446:                         } elsif ($importmode eq 'part') {
                   12447: # Import as part(s)
1.1069    www      12448:                            $importedparts=1;
                   12449: # We need to get the original file and the imported file to get the part order correct
                   12450: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  12451: # Load and inspect original file if we didn't do that already
                   12452:                            if ($#origfiletagids<0) {
                   12453:                                undef(%importedrespids);
                   12454:                                undef(%importedpartids);
                   12455:                                if ($origfile eq '') {
                   12456:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12457:                                    $origfile=&getfile($origfilelocation);
                   12458:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12459:                                }
1.1070    www      12460:                            }
                   12461: 
1.1069    www      12462: # Load and inspect imported file
                   12463:                            my $impfile=&getfile($location);
                   12464:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12465:                            if ($#impfilepartids>=0) {
                   12466: # This problem had parts
1.1070    www      12467:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12468:                            } else {
                   12469: # Importing by turning a single problem into a problem part
                   12470: # It gets the import-tags ID as part-ID
                   12471:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12472:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12473:                            }
1.1068    www      12474:                         } else {
                   12475: # Normal import
                   12476:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12477:                            if (defined($token->[2]->{'id'})) {
                   12478:                               $unikey.='_'.$token->[2]->{'id'};
                   12479:                            }
1.1067    www      12480:                         }
                   12481: 
1.339     albertel 12482: 			if ($depthcount<20) {
1.736     albertel 12483: 			    my $metadata = 
                   12484: 				&metadata($uri,'keys', $location,$unikey,
                   12485: 					  $depthcount+1);
                   12486: 			    foreach my $meta (split(',',$metadata)) {
                   12487: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12488: 				$metathesekeys{$meta}=1;
1.339     albertel 12489: 			    }
1.1068    www      12490: 			
                   12491:                         }
1.1067    www      12492: 		    } else {
                   12493: #
                   12494: # Not importing, some other kind of non-package, non-library start tag
                   12495: # 
                   12496:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12497:                         if (defined($token->[2]->{'id'})) {
                   12498:                             $unikey.='_'.$token->[2]->{'id'};
                   12499:                         }
1.339     albertel 12500: 			if (defined($token->[2]->{'name'})) { 
                   12501: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12502: 			}
                   12503: 			$metathesekeys{$unikey}=1;
1.736     albertel 12504: 			foreach my $param (@{$token->[3]}) {
                   12505: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12506: 				$token->[2]->{$param};
1.339     albertel 12507: 			}
                   12508: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12509: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12510: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12511: 		 # only ws inside the tag, and not in default, so use default
                   12512: 		 # as value
1.599     albertel 12513: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12514: 			} elsif ( $internaltext =~ /\S/ ) {
                   12515: 		  # something interesting inside the tag
                   12516: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12517: 			} else {
1.908     albertel 12518: 		  # no interesting values, don't set a default
1.339     albertel 12519: 			}
1.172     www      12520: # end of not-a-package not-a-library import
1.339     albertel 12521: 		    }
1.172     www      12522: # end of not-a-package start tag
1.339     albertel 12523: 		}
1.172     www      12524: # the next is the end of "start tag"
1.339     albertel 12525: 	    }
                   12526: 	}
1.483     albertel 12527: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12528: 	$extension = lc($extension);
                   12529: 	if ($extension eq 'htm') { $extension='html'; }
                   12530: 
1.737     albertel 12531: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12532: 	    #no specific packages #how's our extension
                   12533: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12534: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12535: 					 \%metathesekeys);
                   12536: 	}
1.883     albertel 12537: 
                   12538: 	if (!exists($metaentry{':packages'})
                   12539: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12540: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12541: 		#no specific packages well let's get default then
                   12542: 		if ($key!~/^default&/) { next; }
1.488     albertel 12543: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12544: 					     \%metathesekeys);
                   12545: 	    }
                   12546: 	}
1.338     www      12547: # are there custom rights to evaluate
1.599     albertel 12548: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12549: 
1.338     www      12550:     #
                   12551:     # Importing a rights file here
1.339     albertel 12552:     #
                   12553: 	    unless ($depthcount) {
1.599     albertel 12554: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12555: 		my $dir=$filename;
                   12556: 		$dir=~s|[^/]*$||;
                   12557: 		$location=&filelocation($dir,$location);
1.736     albertel 12558: 		my $rights_metadata =
                   12559: 		    &metadata($uri,'keys',$location,'_rights',
                   12560: 			      $depthcount+1);
                   12561: 		foreach my $rights (split(',',$rights_metadata)) {
                   12562: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12563: 		    $metathesekeys{$rights}=1;
1.339     albertel 12564: 		}
                   12565: 	    }
                   12566: 	}
1.737     albertel 12567: 	# uniqifiy package listing
                   12568: 	my %seen;
                   12569: 	my @uniq_packages =
                   12570: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12571: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12572: 
1.1172.2.99  raeburn  12573:         if (($importedresponses) || ($importedparts)) {
                   12574:             if ($importedparts) {
1.1070    www      12575: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  12576:                 $metaentry{':partorder'}='';
                   12577:                 $metathesekeys{'partorder'}=1;
                   12578:             }
                   12579:             if ($importedresponses) {
                   12580: # We had imported responses and need to rebuild responseorder
                   12581:                 $metaentry{':responseorder'}='';
                   12582:                 $metathesekeys{'responseorder'}=1;
                   12583:             }
                   12584:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12585:                 my $origid = $origfiletagids[$index+1];
                   12586:                 if ($origfiletagids[$index] eq 'part') {
                   12587: # Original part, part of the problem
                   12588:                     if ($importedparts) {
                   12589:                         $metaentry{':partorder'}.=','.$origid;
                   12590:                     }
                   12591:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12592:                     if ($importedparts) {
                   12593: # We have imported parts at this position
                   12594:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12595:                     }
                   12596:                     if ($importedresponses) {
                   12597: # We have imported responses at this position
                   12598:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   12599:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   12600:                         }
                   12601:                     }
                   12602:                 } else {
                   12603: # Original response item, part of the problem
                   12604:                     if ($importedresponses) {
                   12605:                         $metaentry{':responseorder'}.=','.$origid;
                   12606:                     }
                   12607:                 }
                   12608:             }
                   12609:             if ($importedparts) {
                   12610:                 $metaentry{':partorder'}=~s/^\,//;
                   12611:             }
                   12612:             if ($importedresponses) {
                   12613:                 $metaentry{':responseorder'}=~s/^\,//;
                   12614:             }
1.1070    www      12615:         }
                   12616: 
1.737     albertel 12617: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12618: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  12619: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 12620: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      12621: # this is the end of "was not already recently cached
1.71      www      12622:     }
1.599     albertel 12623:     return $metaentry{':'.$what};
1.261     albertel 12624: }
                   12625: 
1.488     albertel 12626: sub metadata_create_package_def {
1.483     albertel 12627:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12628:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12629:     if ($subp eq 'default') { next; }
                   12630:     
1.599     albertel 12631:     if (defined($metaentry{':packages'})) {
                   12632: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12633:     } else {
1.599     albertel 12634: 	$metaentry{':packages'}=$package;
1.483     albertel 12635:     }
                   12636:     my $value=$packagetab{$key};
                   12637:     my $unikey;
                   12638:     $unikey='parameter_0_'.$name;
1.599     albertel 12639:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12640:     $$metathesekeys{$unikey}=1;
1.599     albertel 12641:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12642: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12643:     }
1.599     albertel 12644:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12645: 	$metaentry{':'.$unikey}=
                   12646: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12647:     }
                   12648: }
                   12649: 
1.261     albertel 12650: sub metadata_generate_part0 {
                   12651:     my ($metadata,$metacache,$uri) = @_;
                   12652:     my %allnames;
1.737     albertel 12653:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12654: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12655: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12656: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12657: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12658: 	    $allnames{$name}=$part;
                   12659: 	  }
                   12660: 	}
                   12661:     }
                   12662:     foreach my $name (keys(%allnames)) {
                   12663:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12664:       my $key=":parameter_0_$name";
1.261     albertel 12665:       $$metacache{"$key.part"}='0';
                   12666:       $$metacache{"$key.name"}=$name;
1.428     albertel 12667:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12668: 					   $allnames{$name}.'_'.$name.
                   12669: 					   '.type'};
1.428     albertel 12670:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12671: 			     '.display'};
1.644     www      12672:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12673:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12674:       $$metacache{"$key.display"}=$olddis;
                   12675:     }
1.71      www      12676: }
                   12677: 
1.764     albertel 12678: # ------------------------------------------------------ Devalidate title cache
                   12679: 
                   12680: sub devalidate_title_cache {
                   12681:     my ($url)=@_;
                   12682:     if (!$env{'request.course.id'}) { return; }
                   12683:     my $symb=&symbread($url);
                   12684:     if (!$symb) { return; }
                   12685:     my $key=$env{'request.course.id'}."\0".$symb;
                   12686:     &devalidate_cache_new('title',$key);
                   12687: }
                   12688: 
1.1014    droeschl 12689: # ------------------------------------------------- Get the title of a course
                   12690: 
                   12691: sub current_course_title {
                   12692:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12693: }
1.301     www      12694: # ------------------------------------------------- Get the title of a resource
                   12695: 
                   12696: sub gettitle {
                   12697:     my $urlsymb=shift;
                   12698:     my $symb=&symbread($urlsymb);
1.534     albertel 12699:     if ($symb) {
1.620     albertel 12700: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12701: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12702: 	if (defined($cached)) { 
                   12703: 	    return $result;
                   12704: 	}
1.534     albertel 12705: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12706: 	my $title='';
1.907     albertel 12707: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12708: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12709: 	} else {
                   12710: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12711: 		    &GDBM_READER(),0640)) {
                   12712: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12713: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12714: 		untie(%bighash);
                   12715: 	    }
1.534     albertel 12716: 	}
                   12717: 	$title=~s/\&colon\;/\:/gs;
                   12718: 	if ($title) {
1.1159    www      12719: # Remember both $symb and $title for dynamic metadata
                   12720:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12721:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12722: # Cache this title and then return it
1.599     albertel 12723: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12724: 	}
                   12725: 	$urlsymb=$url;
                   12726:     }
                   12727:     my $title=&metadata($urlsymb,'title');
                   12728:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12729:     return $title;
1.301     www      12730: }
1.613     albertel 12731: 
1.614     albertel 12732: sub get_slot {
                   12733:     my ($which,$cnum,$cdom)=@_;
                   12734:     if (!$cnum || !$cdom) {
1.790     albertel 12735: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12736: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12737: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12738:     }
1.703     albertel 12739:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12740:     my %slotinfo;
                   12741:     if (exists($remembered{$key})) {
                   12742: 	$slotinfo{$which} = $remembered{$key};
                   12743:     } else {
                   12744: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12745: 	&Apache::lonhomework::showhash(%slotinfo);
                   12746: 	my ($tmp)=keys(%slotinfo);
                   12747: 	if ($tmp=~/^error:/) { return (); }
                   12748: 	$remembered{$key} = $slotinfo{$which};
                   12749:     }
1.616     albertel 12750:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12751: 	return %{$slotinfo{$which}};
                   12752:     }
                   12753:     return $slotinfo{$which};
1.614     albertel 12754: }
1.1150    raeburn  12755: 
                   12756: sub get_reservable_slots {
                   12757:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12758:     my $now = time;
                   12759:     my $reservable_info;
                   12760:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12761:     if (exists($remembered{$key})) {
                   12762:         $reservable_info = $remembered{$key};
                   12763:     } else {
                   12764:         my %resv;
                   12765:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12766:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12767:         $reservable_info = \%resv;
                   12768:         $remembered{$key} = $reservable_info;
                   12769:     }
                   12770:     return $reservable_info;
                   12771: }
                   12772: 
                   12773: sub get_course_slots {
                   12774:     my ($cnum,$cdom) = @_;
                   12775:     my $hashid=$cnum.':'.$cdom;
                   12776:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12777:     if (defined($cached)) {
                   12778:         if (ref($result) eq 'HASH') {
                   12779:             return %{$result};
                   12780:         }
                   12781:     } else {
                   12782:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12783:         my ($tmp) = keys(%slots);
                   12784:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12785:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12786:             return %slots;
                   12787:         }
                   12788:     }
                   12789:     return;
                   12790: }
                   12791: 
                   12792: sub devalidate_slots_cache {
                   12793:     my ($cnum,$cdom)=@_;
                   12794:     my $hashid=$cnum.':'.$cdom;
                   12795:     &devalidate_cache_new('allslots',$hashid);
                   12796: }
                   12797: 
1.1172.2.8  raeburn  12798: sub get_coursechange {
                   12799:     my ($cdom,$cnum) = @_;
                   12800:     if ($cdom eq '' || $cnum eq '') {
                   12801:         return unless ($env{'request.course.id'});
                   12802:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12803:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12804:     }
                   12805:     my $hashid=$cdom.'_'.$cnum;
                   12806:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12807:     if ((defined($cached)) && ($change ne '')) {
                   12808:         return $change;
                   12809:     } else {
                   12810:         my %crshash;
                   12811:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12812:         if ($crshash{'internal.contentchange'} eq '') {
                   12813:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12814:             if ($change eq '') {
                   12815:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12816:                 $change = $crshash{'internal.created'};
                   12817:             }
                   12818:         } else {
                   12819:             $change = $crshash{'internal.contentchange'};
                   12820:         }
                   12821:         my $cachetime = 600;
                   12822:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12823:     }
                   12824:     return $change;
                   12825: }
                   12826: 
                   12827: sub devalidate_coursechange_cache {
                   12828:     my ($cnum,$cdom)=@_;
                   12829:     my $hashid=$cnum.':'.$cdom;
                   12830:     &devalidate_cache_new('crschange',$hashid);
                   12831: }
                   12832: 
1.31      www      12833: # ------------------------------------------------- Update symbolic store links
                   12834: 
                   12835: sub symblist {
                   12836:     my ($mapname,%newhash)=@_;
1.438     www      12837:     $mapname=&deversion(&declutter($mapname));
1.31      www      12838:     my %hash;
1.620     albertel 12839:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12840:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12841:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12842: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12843: 		next if ($url eq 'last_known'
                   12844: 			 && $env{'form.no_update_last_known'});
                   12845: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12846: 						    $newhash{$url}->[1],
                   12847: 						    $newhash{$url}->[0]);
1.191     harris41 12848:             }
1.31      www      12849:             if (untie(%hash)) {
                   12850: 		return 'ok';
                   12851:             }
                   12852:         }
                   12853:     }
                   12854:     return 'error';
1.212     www      12855: }
                   12856: 
                   12857: # --------------------------------------------------------------- Verify a symb
                   12858: 
                   12859: sub symbverify {
1.1172.2.11  raeburn  12860:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12861:     my $thisfn=$thisurl;
1.439     www      12862:     $thisfn=&declutter($thisfn);
1.215     www      12863: # direct jump to resource in page or to a sequence - will construct own symbs
                   12864:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12865: # check URL part
1.409     www      12866:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12867: 
1.431     www      12868:     unless ($url eq $thisfn) { return 0; }
1.213     www      12869: 
1.216     www      12870:     $symb=&symbclean($symb);
1.510     www      12871:     $thisurl=&deversion($thisurl);
1.439     www      12872:     $thisfn=&deversion($thisfn);
1.213     www      12873: 
                   12874:     my %bighash;
                   12875:     my $okay=0;
1.431     www      12876: 
1.620     albertel 12877:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12878:                             &GDBM_READER(),0640)) {
1.1032    raeburn  12879:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12880:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  12881:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12882:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12883:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12884:             }
                   12885:         }
                   12886:         my $ids;
1.1172.2.122  raeburn  12887:         if ($map =~ m{^uploaded/.+\.page$}) {
                   12888:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13  raeburn  12889:         } else {
                   12890:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12891:         }
1.1102    raeburn  12892:         unless ($ids) {
1.1172.2.13  raeburn  12893:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  12894:             $ids=$bighash{$idkey};
1.216     www      12895:         }
                   12896:         if ($ids) {
                   12897: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  12898:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   12899:                 $symb =~ s/\?.+$//;
                   12900:             }
1.800     albertel 12901: 	    foreach my $id (split(/\,/,$ids)) {
                   12902: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12903:                if (
                   12904:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  12905:    eq $symb) {
1.1172.2.11  raeburn  12906:                    if (ref($encstate)) {
                   12907:                        $$encstate = $bighash{'encrypted_'.$id};
                   12908:                    }
1.1172.2.13  raeburn  12909:                    if (($env{'request.role.adv'}) ||
                   12910:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  12911:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  12912:                        $okay=1;
                   12913:                        last;
                   12914:                    }
                   12915:                }
                   12916:            }
1.216     www      12917:         }
1.213     www      12918: 	untie(%bighash);
                   12919:     }
                   12920:     return $okay;
1.31      www      12921: }
                   12922: 
1.210     www      12923: # --------------------------------------------------------------- Clean-up symb
                   12924: 
                   12925: sub symbclean {
                   12926:     my $symb=shift;
1.568     albertel 12927:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12928: # remove version from map
                   12929:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12930: 
1.210     www      12931: # remove version from URL
                   12932:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12933: 
1.507     www      12934: # remove wrapper
                   12935: 
1.510     www      12936:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12937:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12938:     return $symb;
1.409     www      12939: }
                   12940: 
                   12941: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12942: 
                   12943: sub encode_symb {
                   12944:     my ($map,$resid,$url)=@_;
                   12945:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12946: }
1.409     www      12947: 
                   12948: sub decode_symb {
1.568     albertel 12949:     my $symb=shift;
                   12950:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12951:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12952:     return (&fixversion($map),$resid,&fixversion($url));
                   12953: }
                   12954: 
                   12955: sub fixversion {
                   12956:     my $fn=shift;
1.609     banghart 12957:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12958:     my %bighash;
                   12959:     my $uri=&clutter($fn);
1.620     albertel 12960:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12961: # is this cached?
1.599     albertel 12962:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12963:     if (defined($cached)) { return $result; }
                   12964: # unfortunately not cached, or expired
1.620     albertel 12965:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12966: 	    &GDBM_READER(),0640)) {
                   12967:  	if ($bighash{'version_'.$uri}) {
                   12968:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12969:  	    unless (($version eq 'mostrecent') || 
                   12970: 		    ($version==&getversion($uri))) {
1.440     www      12971:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12972:  	    }
                   12973:  	}
                   12974:  	untie %bighash;
1.413     www      12975:     }
1.599     albertel 12976:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12977: }
                   12978: 
                   12979: sub deversion {
                   12980:     my $url=shift;
                   12981:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12982:     return $url;
1.210     www      12983: }
                   12984: 
1.31      www      12985: # ------------------------------------------------------ Return symb list entry
                   12986: 
                   12987: sub symbread {
1.1172.2.126  raeburn  12988:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128  raeburn  12989:         $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54  raeburn  12990:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128  raeburn  12991:     if (defined($env{$cache_str})) {
1.1172.2.126  raeburn  12992:         unless (ref($possibles) eq 'HASH') {
                   12993:             if ($ignorecachednull) {
                   12994:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12995:             } else {
                   12996:                 return $env{$cache_str};
                   12997:             }
1.1172.2.66  raeburn  12998:         }
                   12999:     }
1.242     www      13000: # no filename provided? try from environment
1.1172.2.54  raeburn  13001:     unless ($thisfn) {
1.620     albertel 13002:         if ($env{'request.symb'}) {
1.1172.2.128  raeburn  13003:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13  raeburn  13004:         }
                   13005:         $thisfn=$env{'request.filename'};
1.44      www      13006:     }
1.569     albertel 13007:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      13008: # is that filename actually a symb? Verify, clean, and return
                   13009:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 13010: 	if (&symbverify($thisfn,$1)) {
1.1172.2.128  raeburn  13011: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 13012: 	}
1.242     www      13013:     }
1.44      www      13014:     $thisfn=declutter($thisfn);
1.31      www      13015:     my %hash;
1.37      www      13016:     my %bighash;
                   13017:     my $syval='';
1.620     albertel 13018:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  13019:         my $targetfn = $thisfn;
1.609     banghart 13020:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  13021:             $targetfn = 'adm/wrapper/'.$thisfn;
                   13022:         }
1.687     albertel 13023: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   13024: 	    $targetfn=$1;
                   13025: 	}
1.1172.2.128  raeburn  13026:         unless ($ignoresymbdb) {
1.1172.2.126  raeburn  13027:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   13028:                           &GDBM_READER(),0640)) {
                   13029: 	        $syval=$hash{$targetfn};
                   13030:                 untie(%hash);
                   13031:             }
1.1172.2.128  raeburn  13032:             if ($syval && $checkforblock) {
                   13033:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126  raeburn  13034:                 if (@blockers) {
                   13035:                     $syval='';
                   13036:                 }
                   13037:             }
1.37      www      13038:         }
                   13039: # ---------------------------------------------------------- There was an entry
                   13040:         if ($syval) {
1.601     albertel 13041: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 13042: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  13043: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13044: 		    #return $env{$cache_str}='';
1.601     albertel 13045: 		#}    
                   13046: 		#$syval.=$1;
                   13047: 	    #}
1.37      www      13048:         } else {
                   13049: # ------------------------------------------------------- Was not in symb table
1.620     albertel 13050:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13051:                             &GDBM_READER(),0640)) {
1.37      www      13052: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      13053:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      13054:               unless ($ids) { 
                   13055:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      13056:               }
                   13057:               unless ($ids) {
                   13058: # alias?
                   13059: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      13060:               }
1.37      www      13061:               if ($ids) {
                   13062: # ------------------------------------------------------------------- Has ID(s)
                   13063:                  my @possibilities=split(/\,/,$ids);
1.39      www      13064:                  if ($#possibilities==0) {
                   13065: # ----------------------------------------------- There is only one possibility
1.37      www      13066: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 13067: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13068: 						    $resid,$thisfn);
1.1172.2.66  raeburn  13069:                      if (ref($possibles) eq 'HASH') {
1.1172.2.126  raeburn  13070:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   13071:                              $possibles->{$syval} = 1;
                   13072:                          }
1.1172.2.66  raeburn  13073:                      }
                   13074:                      if ($checkforblock) {
1.1172.2.126  raeburn  13075:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127  raeburn  13076:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126  raeburn  13077:                              if (@blockers) {
                   13078:                                  $syval = '';
                   13079:                                  untie(%bighash);
                   13080:                                  return $env{$cache_str}='';
                   13081:                              }
1.1172.2.66  raeburn  13082:                          }
                   13083:                      }
                   13084:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      13085: # ------------------------------------------ There is more than one possibility
                   13086:                      my $realpossible=0;
1.800     albertel 13087:                      foreach my $id (@possibilities) {
                   13088: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  13089:                          my $canaccess;
                   13090:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   13091:                              $canaccess = 1;
                   13092:                          } else {
                   13093:                              $canaccess = &allowed('bre',$file);
                   13094:                          }
                   13095:                          if ($canaccess) {
                   13096:          		     my ($mapid,$resid)=split(/\./,$id);
                   13097:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   13098:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13099:                                                              $resid,$thisfn);
1.1172.2.126  raeburn  13100:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127  raeburn  13101:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66  raeburn  13102:                                  if ($checkforblock) {
1.1172.2.127  raeburn  13103:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126  raeburn  13104:                                      if (@blockers > 0) {
                   13105:                                          $syval = '';
                   13106:                                      } else {
1.1172.2.66  raeburn  13107:                                          $syval = $poss_syval;
                   13108:                                          $realpossible++;
                   13109:                                      }
                   13110:                                  } else {
                   13111:                                      $syval = $poss_syval;
                   13112:                                      $realpossible++;
                   13113:                                  }
1.1172.2.126  raeburn  13114:                                  if ($syval) {
                   13115:                                      if (ref($possibles) eq 'HASH') {
                   13116:                                          $possibles->{$syval} = 1;
                   13117:                                      }
                   13118:                                  }
1.1172.2.66  raeburn  13119:                              }
1.39      www      13120: 			 }
1.191     harris41 13121:                      }
1.39      www      13122: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      13123:                  } else {
                   13124:                      $syval='';
1.37      www      13125:                  }
                   13126: 	      }
1.1172.2.66  raeburn  13127:               untie(%bighash);
1.481     raeburn  13128:            }
1.31      www      13129:         }
1.62      www      13130:         if ($syval) {
1.1172.2.128  raeburn  13131: 	    return $env{$cache_str}=$syval;
1.62      www      13132:         }
1.31      www      13133:     }
1.949     raeburn  13134:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13135:     return $env{$cache_str}='';
1.31      www      13136: }
                   13137: 
                   13138: # ---------------------------------------------------------- Return random seed
                   13139: 
1.32      www      13140: sub numval {
                   13141:     my $txt=shift;
                   13142:     $txt=~tr/A-J/0-9/;
                   13143:     $txt=~tr/a-j/0-9/;
                   13144:     $txt=~tr/K-T/0-9/;
                   13145:     $txt=~tr/k-t/0-9/;
                   13146:     $txt=~tr/U-Z/0-5/;
                   13147:     $txt=~tr/u-z/0-5/;
                   13148:     $txt=~s/\D//g;
1.564     albertel 13149:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      13150:     return int($txt);
1.368     albertel 13151: }
                   13152: 
1.484     albertel 13153: sub numval2 {
                   13154:     my $txt=shift;
                   13155:     $txt=~tr/A-J/0-9/;
                   13156:     $txt=~tr/a-j/0-9/;
                   13157:     $txt=~tr/K-T/0-9/;
                   13158:     $txt=~tr/k-t/0-9/;
                   13159:     $txt=~tr/U-Z/0-5/;
                   13160:     $txt=~tr/u-z/0-5/;
                   13161:     $txt=~s/\D//g;
                   13162:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13163:     my $total;
                   13164:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 13165:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 13166:     return int($total);
                   13167: }
                   13168: 
1.575     albertel 13169: sub numval3 {
                   13170:     use integer;
                   13171:     my $txt=shift;
                   13172:     $txt=~tr/A-J/0-9/;
                   13173:     $txt=~tr/a-j/0-9/;
                   13174:     $txt=~tr/K-T/0-9/;
                   13175:     $txt=~tr/k-t/0-9/;
                   13176:     $txt=~tr/U-Z/0-5/;
                   13177:     $txt=~tr/u-z/0-5/;
                   13178:     $txt=~s/\D//g;
                   13179:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13180:     my $total;
                   13181:     foreach my $val (@txts) { $total+=$val; }
                   13182:     if ($_64bit) { $total=(($total<<32)>>32); }
                   13183:     return $total;
                   13184: }
                   13185: 
1.675     albertel 13186: sub digest {
                   13187:     my ($data)=@_;
                   13188:     my $digest=&Digest::MD5::md5($data);
                   13189:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   13190:     my ($e,$f);
                   13191:     {
                   13192:         use integer;
                   13193:         $e=($a+$b);
                   13194:         $f=($c+$d);
                   13195:         if ($_64bit) {
                   13196:             $e=(($e<<32)>>32);
                   13197:             $f=(($f<<32)>>32);
                   13198:         }
                   13199:     }
                   13200:     if (wantarray) {
                   13201: 	return ($e,$f);
                   13202:     } else {
                   13203: 	my $g;
                   13204: 	{
                   13205: 	    use integer;
                   13206: 	    $g=($e+$f);
                   13207: 	    if ($_64bit) {
                   13208: 		$g=(($g<<32)>>32);
                   13209: 	    }
                   13210: 	}
                   13211: 	return $g;
                   13212:     }
                   13213: }
                   13214: 
1.368     albertel 13215: sub latest_rnd_algorithm_id {
1.675     albertel 13216:     return '64bit5';
1.366     albertel 13217: }
1.32      www      13218: 
1.503     albertel 13219: sub get_rand_alg {
                   13220:     my ($courseid)=@_;
1.790     albertel 13221:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 13222:     if ($courseid) {
1.620     albertel 13223: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 13224:     }
                   13225:     return &latest_rnd_algorithm_id();
                   13226: }
                   13227: 
1.562     albertel 13228: sub validCODE {
                   13229:     my ($CODE)=@_;
                   13230:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   13231:     return 0;
                   13232: }
                   13233: 
1.491     albertel 13234: sub getCODE {
1.620     albertel 13235:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 13236:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   13237: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   13238: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 13239: 	return $Apache::lonhomework::history{'resource.CODE'};
                   13240:     }
                   13241:     return undef;
                   13242: }
1.1133    foxr     13243: #
                   13244: #  Determines the random seed for a specific context:
                   13245: #
                   13246: # parameters:
                   13247: #   symb      - in course context the symb for the seed.
                   13248: #   course_id - The course id of the form domain_coursenum.
                   13249: #   domain    - Domain for the user.
                   13250: #   course    - Course for the user.
                   13251: #   cenv      - environment of the course.
                   13252: #
                   13253: # NOTE:
                   13254: #   All parameters are picked out of the environment if missing
                   13255: #   or not defined.
                   13256: #   If a symb cannot be determined the current time is used instead.
                   13257: #
                   13258: #  For a given well defined symb, courside, domain, username,
                   13259: #  and course environment, the seed is reproducible.
                   13260: #
1.31      www      13261: sub rndseed {
1.1133    foxr     13262:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 13263:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 13264:     if (!defined($symb)) {
1.366     albertel 13265: 	unless ($symb=$wsymb) { return time; }
                   13266:     }
1.1146    foxr     13267:     if (!defined $courseid) { 
                   13268: 	$courseid=$wcourseid; 
                   13269:     }
                   13270:     if (!defined $domain) { $domain=$wdomain; }
                   13271:     if (!defined $username) { $username=$wusername }
1.1133    foxr     13272: 
                   13273:     my $which;
                   13274:     if (defined($cenv->{'rndseed'})) {
                   13275: 	$which = $cenv->{'rndseed'};
                   13276:     } else {
                   13277: 	$which =&get_rand_alg($courseid);
                   13278:     }
1.491     albertel 13279:     if (defined(&getCODE())) {
1.675     albertel 13280: 	if ($which eq '64bit5') {
                   13281: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   13282: 	} elsif ($which eq '64bit4') {
1.575     albertel 13283: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   13284: 	} else {
                   13285: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   13286: 	}
1.675     albertel 13287:     } elsif ($which eq '64bit5') {
                   13288: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 13289:     } elsif ($which eq '64bit4') {
                   13290: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 13291:     } elsif ($which eq '64bit3') {
                   13292: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 13293:     } elsif ($which eq '64bit2') {
                   13294: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 13295:     } elsif ($which eq '64bit') {
                   13296: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   13297:     }
                   13298:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   13299: }
                   13300: 
                   13301: sub rndseed_32bit {
                   13302:     my ($symb,$courseid,$domain,$username)=@_;
                   13303:     {
                   13304: 	use integer;
                   13305: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   13306: 	my $symbseed=numval($symb) << 22;
                   13307: 	my $namechck=unpack("%32C*",$username) << 17;
                   13308: 	my $nameseed=numval($username) << 12;
                   13309: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   13310: 	my $courseseed=unpack("%32C*",$courseid);
                   13311: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 13312: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13313: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13314: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 13315: 	return $num;
                   13316:     }
                   13317: }
                   13318: 
                   13319: sub rndseed_64bit {
                   13320:     my ($symb,$courseid,$domain,$username)=@_;
                   13321:     {
                   13322: 	use integer;
                   13323: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   13324: 	my $symbseed=numval($symb) << 10;
                   13325: 	my $namechck=unpack("%32S*",$username);
                   13326: 	
                   13327: 	my $nameseed=numval($username) << 21;
                   13328: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   13329: 	my $courseseed=unpack("%32S*",$courseid);
                   13330: 	
                   13331: 	my $num1=$symbchck+$symbseed+$namechck;
                   13332: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13333: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13334: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13335: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 13336: 	return "$num1,$num2";
1.155     albertel 13337:     }
1.366     albertel 13338: }
                   13339: 
1.443     albertel 13340: sub rndseed_64bit2 {
                   13341:     my ($symb,$courseid,$domain,$username)=@_;
                   13342:     {
                   13343: 	use integer;
                   13344: 	# strings need to be an even # of cahracters long, it it is odd the
                   13345:         # last characters gets thrown away
                   13346: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13347: 	my $symbseed=numval($symb) << 10;
                   13348: 	my $namechck=unpack("%32S*",$username.' ');
                   13349: 	
                   13350: 	my $nameseed=numval($username) << 21;
1.501     albertel 13351: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13352: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13353: 	
                   13354: 	my $num1=$symbchck+$symbseed+$namechck;
                   13355: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13356: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13357: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13358: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13359: 	return "$num1,$num2";
                   13360:     }
                   13361: }
                   13362: 
                   13363: sub rndseed_64bit3 {
                   13364:     my ($symb,$courseid,$domain,$username)=@_;
                   13365:     {
                   13366: 	use integer;
                   13367: 	# strings need to be an even # of cahracters long, it it is odd the
                   13368:         # last characters gets thrown away
                   13369: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13370: 	my $symbseed=numval2($symb) << 10;
                   13371: 	my $namechck=unpack("%32S*",$username.' ');
                   13372: 	
                   13373: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13374: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13375: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13376: 	
                   13377: 	my $num1=$symbchck+$symbseed+$namechck;
                   13378: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13379: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13380: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13381: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13382: 	
1.503     albertel 13383: 	return "$num1:$num2";
1.443     albertel 13384:     }
                   13385: }
                   13386: 
1.575     albertel 13387: sub rndseed_64bit4 {
                   13388:     my ($symb,$courseid,$domain,$username)=@_;
                   13389:     {
                   13390: 	use integer;
                   13391: 	# strings need to be an even # of cahracters long, it it is odd the
                   13392:         # last characters gets thrown away
                   13393: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13394: 	my $symbseed=numval3($symb) << 10;
                   13395: 	my $namechck=unpack("%32S*",$username.' ');
                   13396: 	
                   13397: 	my $nameseed=numval3($username) << 21;
                   13398: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13399: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13400: 	
                   13401: 	my $num1=$symbchck+$symbseed+$namechck;
                   13402: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13403: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13404: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13405: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13406: 	
1.575     albertel 13407: 	return "$num1:$num2";
                   13408:     }
                   13409: }
                   13410: 
1.675     albertel 13411: sub rndseed_64bit5 {
                   13412:     my ($symb,$courseid,$domain,$username)=@_;
                   13413:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13414:     return "$num1:$num2";
                   13415: }
                   13416: 
1.366     albertel 13417: sub rndseed_CODE_64bit {
                   13418:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13419:     {
1.366     albertel 13420: 	use integer;
1.443     albertel 13421: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13422: 	my $symbseed=numval2($symb);
1.491     albertel 13423: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13424: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13425: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13426: 	my $num1=$symbseed+$CODEchck;
                   13427: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13428: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13429: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13430: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13431: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13432: 	return "$num1:$num2";
1.366     albertel 13433:     }
                   13434: }
                   13435: 
1.575     albertel 13436: sub rndseed_CODE_64bit4 {
                   13437:     my ($symb,$courseid,$domain,$username)=@_;
                   13438:     {
                   13439: 	use integer;
                   13440: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13441: 	my $symbseed=numval3($symb);
                   13442: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13443: 	my $CODEseed=numval3(&getCODE());
                   13444: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13445: 	my $num1=$symbseed+$CODEchck;
                   13446: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13447: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13448: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13449: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13450: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13451: 	return "$num1:$num2";
                   13452:     }
                   13453: }
                   13454: 
1.675     albertel 13455: sub rndseed_CODE_64bit5 {
                   13456:     my ($symb,$courseid,$domain,$username)=@_;
                   13457:     my $code = &getCODE();
                   13458:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13459:     return "$num1:$num2";
                   13460: }
                   13461: 
1.366     albertel 13462: sub setup_random_from_rndseed {
                   13463:     my ($rndseed)=@_;
1.503     albertel 13464:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  13465: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13466:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13467:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13468:         } else {
                   13469:             &Math::Random::random_set_seed($num1,$num2);
                   13470:         }
1.366     albertel 13471:     } else {
                   13472: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13473:     }
1.36      albertel 13474: }
                   13475: 
1.474     albertel 13476: sub latest_receipt_algorithm_id {
1.835     albertel 13477:     return 'receipt3';
1.474     albertel 13478: }
                   13479: 
1.480     www      13480: sub recunique {
                   13481:     my $fucourseid=shift;
                   13482:     my $unique;
1.835     albertel 13483:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13484: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13485: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13486:     } else {
                   13487: 	$unique=$perlvar{'lonReceipt'};
                   13488:     }
                   13489:     return unpack("%32C*",$unique);
                   13490: }
                   13491: 
                   13492: sub recprefix {
                   13493:     my $fucourseid=shift;
                   13494:     my $prefix;
1.835     albertel 13495:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13496: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13497: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13498:     } else {
                   13499: 	$prefix=$perlvar{'lonHostID'};
                   13500:     }
                   13501:     return unpack("%32C*",$prefix);
                   13502: }
                   13503: 
1.76      www      13504: sub ireceipt {
1.474     albertel 13505:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13506: 
                   13507:     my $return =&recprefix($fucourseid).'-';
                   13508: 
                   13509:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13510: 	$env{'request.state'} eq 'construct') {
                   13511: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13512: 	return $return;
                   13513:     }
                   13514: 
1.76      www      13515:     my $cuname=unpack("%32C*",$funame);
                   13516:     my $cudom=unpack("%32C*",$fudom);
                   13517:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13518:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13519:     my $cunique=&recunique($fucourseid);
1.474     albertel 13520:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13521:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13522: 
1.790     albertel 13523: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13524: 			       
                   13525: 	$return.= ($cunique%$cuname+
                   13526: 		   $cunique%$cudom+
                   13527: 		   $cusymb%$cuname+
                   13528: 		   $cusymb%$cudom+
                   13529: 		   $cucourseid%$cuname+
                   13530: 		   $cucourseid%$cudom+
                   13531: 		   $cpart%$cuname+
                   13532: 		   $cpart%$cudom);
                   13533:     } else {
                   13534: 	$return.= ($cunique%$cuname+
                   13535: 		   $cunique%$cudom+
                   13536: 		   $cusymb%$cuname+
                   13537: 		   $cusymb%$cudom+
                   13538: 		   $cucourseid%$cuname+
                   13539: 		   $cucourseid%$cudom);
                   13540:     }
                   13541:     return $return;
1.76      www      13542: }
                   13543: 
                   13544: sub receipt {
1.474     albertel 13545:     my ($part)=@_;
1.790     albertel 13546:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13547:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13548: }
1.260     ng       13549: 
1.790     albertel 13550: sub whichuser {
                   13551:     my ($passedsymb)=@_;
                   13552:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13553:     if (defined($env{'form.grade_symb'})) {
                   13554: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13555: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13556: 	if (!$allowed &&
                   13557: 	    exists($env{'request.course.sec'}) &&
                   13558: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13559: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13560: 			      '/'.$env{'request.course.sec'});
                   13561: 	}
                   13562: 	if ($allowed) {
                   13563: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13564: 	    $courseid=$tmp_courseid;
                   13565: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13566: 	    ($name)=&get_env_multiple('form.grade_username');
                   13567: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13568: 	}
                   13569:     }
                   13570:     if (!$passedsymb) {
                   13571: 	$symb=&symbread();
                   13572:     } else {
                   13573: 	$symb=$passedsymb;
                   13574:     }
                   13575:     $courseid=$env{'request.course.id'};
                   13576:     $domain=$env{'user.domain'};
                   13577:     $name=$env{'user.name'};
                   13578:     if ($name eq 'public' && $domain eq 'public') {
                   13579: 	if (!defined($env{'form.username'})) {
                   13580: 	    $env{'form.username'}.=time.rand(10000000);
                   13581: 	}
                   13582: 	$name.=$env{'form.username'};
                   13583:     }
                   13584:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13585: 
                   13586: }
                   13587: 
1.36      albertel 13588: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13589: # returns either the contents of the file or 
                   13590: # -1 if the file doesn't exist
1.481     raeburn  13591: #
                   13592: # if the target is a file that was uploaded via DOCS, 
                   13593: # a check will be made to see if a current copy exists on the local server,
                   13594: # if it does this will be served, otherwise a copy will be retrieved from
                   13595: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13596: # the local server.   
1.472     albertel 13597: 
1.36      albertel 13598: sub getfile {
1.538     albertel 13599:     my ($file) = @_;
1.609     banghart 13600:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13601:     &repcopy($file);
                   13602:     return &readfile($file);
                   13603: }
                   13604: 
                   13605: sub repcopy_userfile {
                   13606:     my ($file)=@_;
1.1142    raeburn  13607:     my $londocroot = $perlvar{'lonDocRoot'};
                   13608:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13609:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13610:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13611: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13612:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13613:     if (-e "$file") {
1.828     www      13614: # we already have a local copy, check it out
1.538     albertel 13615: 	my @fileinfo = stat($file);
1.828     www      13616: 	my $rtncode;
                   13617: 	my $info;
1.538     albertel 13618: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13619: 	if ($lwpresp ne 'ok') {
1.828     www      13620: # there is no such file anymore, even though we had a local copy
1.482     albertel 13621: 	    if ($rtncode eq '404') {
1.538     albertel 13622: 		unlink($file);
1.482     albertel 13623: 	    }
                   13624: 	    return -1;
                   13625: 	}
                   13626: 	if ($info < $fileinfo[9]) {
1.828     www      13627: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13628: 	    return 'ok';
1.828     www      13629: 	} else {
                   13630: # the file is outdated, get rid of it
                   13631: 	    unlink($file);
1.482     albertel 13632: 	}
1.828     www      13633:     }
                   13634: # one way or the other, at this point, we don't have the file
                   13635: # construct the correct path for the file
                   13636:     my @parts = ($cdom,$cnum); 
                   13637:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13638: 	push @parts, split(/\//,$1);
                   13639:     }
                   13640:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13641:     foreach my $part (@parts) {
                   13642: 	$path .= '/'.$part;
                   13643: 	if (!-e $path) {
                   13644: 	    mkdir($path,0770);
1.482     albertel 13645: 	}
                   13646:     }
1.828     www      13647: # now the path exists for sure
                   13648: # get a user agent
                   13649:     my $ua=new LWP::UserAgent;
                   13650:     my $transferfile=$file.'.in.transfer';
                   13651: # FIXME: this should flock
                   13652:     if (-e $transferfile) { return 'ok'; }
                   13653:     my $request;
                   13654:     $uri=~s/^\///;
1.980     raeburn  13655:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13656:     my $hostname = &hostname($homeserver);
1.980     raeburn  13657:     my $protocol = $protocol{$homeserver};
                   13658:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13659:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      13660:     my $response=$ua->request($request,$transferfile);
                   13661: # did it work?
                   13662:     if ($response->is_error()) {
                   13663: 	unlink($transferfile);
                   13664: 	&logthis("Userfile repcopy failed for $uri");
                   13665: 	return -1;
                   13666:     }
                   13667: # worked, rename the transfer file
                   13668:     rename($transferfile,$file);
1.607     raeburn  13669:     return 'ok';
1.481     raeburn  13670: }
                   13671: 
1.517     albertel 13672: sub tokenwrapper {
                   13673:     my $uri=shift;
1.980     raeburn  13674:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13675:     $uri=~s|^/||;
1.620     albertel 13676:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13677:     my $token=$1;
1.552     albertel 13678:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13679:     if ($udom && $uname && $file) {
                   13680: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13681:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13682:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.120  raeburn  13683:         my $hostname = &hostname($homeserver);
1.980     raeburn  13684:         my $protocol = $protocol{$homeserver};
                   13685:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13686:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13687:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13688:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13689:     } else {
                   13690:         return '/adm/notfound.html';
                   13691:     }
                   13692: }
                   13693: 
1.828     www      13694: # call with reqtype HEAD: get last modification time
                   13695: # call with reqtype GET: get the file contents
                   13696: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13697: #
1.481     raeburn  13698: sub getuploaded {
                   13699:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13700:     $uri=~s/^\///;
1.980     raeburn  13701:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13702:     my $hostname = &hostname($homeserver);
1.980     raeburn  13703:     my $protocol = $protocol{$homeserver};
                   13704:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13705:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13706:     my $ua=new LWP::UserAgent;
                   13707:     my $request=new HTTP::Request($reqtype,$uri);
                   13708:     my $response=$ua->request($request);
                   13709:     $$rtncode = $response->code;
1.482     albertel 13710:     if (! $response->is_success()) {
                   13711: 	return 'failed';
                   13712:     }      
                   13713:     if ($reqtype eq 'HEAD') {
1.486     www      13714: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13715:     } elsif ($reqtype eq 'GET') {
                   13716: 	$$info = $response->content;
1.472     albertel 13717:     }
1.482     albertel 13718:     return 'ok';
1.36      albertel 13719: }
                   13720: 
1.481     raeburn  13721: sub readfile {
                   13722:     my $file = shift;
                   13723:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13724:     my $fh;
1.1172.2.96  raeburn  13725:     open($fh,"<",$file);
1.481     raeburn  13726:     my $a='';
1.800     albertel 13727:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13728:     return $a;
                   13729: }
                   13730: 
1.36      albertel 13731: sub filelocation {
1.590     banghart 13732:     my ($dir,$file) = @_;
                   13733:     my $location;
                   13734:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13735: 
                   13736:     if ($file =~ m-^/adm/-) {
                   13737: 	$file=~s-^/adm/wrapper/-/-;
                   13738: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13739:     }
1.882     albertel 13740: 
1.1139    www      13741:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13742:         $location = $file;
1.609     banghart 13743:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13744:         my ($udom,$uname,$filename)=
1.811     albertel 13745:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13746:         my $home=&homeserver($uname,$udom);
                   13747:         my $is_me=0;
                   13748:         my @ids=&current_machine_ids();
                   13749:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13750:         if ($is_me) {
1.1117    foxr     13751:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13752:         } else {
                   13753:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13754:   	      $udom.'/'.$uname.'/'.$filename;
                   13755:         }
1.882     albertel 13756:     } elsif ($file =~ m-^/adm/-) {
                   13757: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13758:     } else {
                   13759:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13760:         $file=~s:^/(res|priv)/:/:;
                   13761:         my $space=$1;
1.590     banghart 13762:         if ( !( $file =~ m:^/:) ) {
                   13763:             $location = $dir. '/'.$file;
                   13764:         } else {
1.1142    raeburn  13765:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13766:         }
1.59      albertel 13767:     }
1.590     banghart 13768:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13769:     while ($location=~m{/\.\./}) {
                   13770: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13771: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13772: 	} else {
                   13773: 	    $location=~ s{/\.\./}{/}g;
                   13774: 	}
                   13775:     } #remove dir/..
1.590     banghart 13776:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13777:     return $location;
1.46      www      13778: }
1.36      albertel 13779: 
1.46      www      13780: sub hreflocation {
                   13781:     my ($dir,$file)=@_;
1.980     raeburn  13782:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13783: 	$file=filelocation($dir,$file);
1.700     albertel 13784:     } elsif ($file=~m-^/adm/-) {
                   13785: 	$file=~s-^/adm/wrapper/-/-;
                   13786: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13787:     }
                   13788:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13789: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13790:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13791: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13792: 	        {/uploaded/$1/$2/}x;
1.46      www      13793:     }
1.913     albertel 13794:     if ($file=~ m{^/userfiles/}) {
                   13795: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13796:     }
1.462     albertel 13797:     return $file;
1.465     albertel 13798: }
                   13799: 
1.1139    www      13800: 
                   13801: 
                   13802: 
                   13803: 
1.465     albertel 13804: sub current_machine_domains {
1.853     albertel 13805:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13806: }
                   13807: 
                   13808: sub machine_domains {
                   13809:     my ($hostname) = @_;
1.465     albertel 13810:     my @domains;
1.838     albertel 13811:     my %hostname = &all_hostnames();
1.465     albertel 13812:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13813: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13814: 	if ($hostname eq $name) {
1.844     albertel 13815: 	    push(@domains,&host_domain($id));
1.465     albertel 13816: 	}
                   13817:     }
                   13818:     return @domains;
                   13819: }
                   13820: 
                   13821: sub current_machine_ids {
1.853     albertel 13822:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13823: }
                   13824: 
                   13825: sub machine_ids {
                   13826:     my ($hostname) = @_;
                   13827:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13828:     my @ids;
1.888     albertel 13829:     my %name_to_host = &all_names();
1.889     albertel 13830:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13831: 	return @{ $name_to_host{$hostname} };
                   13832:     }
                   13833:     return;
1.31      www      13834: }
                   13835: 
1.824     raeburn  13836: sub additional_machine_domains {
                   13837:     my @domains;
1.1172.2.142  raeburn  13838:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
                   13839:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
                   13840:             while( my $line = <$fh>) {
                   13841:                 chomp($line);
                   13842:                 $line =~ s/\s//g;
                   13843:                 push(@domains,$line);
                   13844:             }
                   13845:             close($fh);
                   13846:         }
1.824     raeburn  13847:     }
                   13848:     return @domains;
                   13849: }
                   13850: 
                   13851: sub default_login_domain {
                   13852:     my $domain = $perlvar{'lonDefDomain'};
                   13853:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13854:     foreach my $posdom (&current_machine_domains(),
                   13855:                         &additional_machine_domains()) {
                   13856:         if (lc($posdom) eq lc($testdomain)) {
                   13857:             $domain=$posdom;
                   13858:             last;
                   13859:         }
                   13860:     }
                   13861:     return $domain;
                   13862: }
                   13863: 
1.1172.2.106  raeburn  13864: sub shared_institution {
1.1172.2.136  raeburn  13865:     my ($dom,$lonhost) = @_;
                   13866:     if ($lonhost eq '') {
                   13867:         $lonhost = $perlvar{'lonHostID'};
                   13868:     }
1.1172.2.106  raeburn  13869:     my $same_intdom;
1.1172.2.136  raeburn  13870:     my $hostintdom = &internet_dom($lonhost);
1.1172.2.106  raeburn  13871:     if ($hostintdom ne '') {
                   13872:         my %iphost = &get_iphost();
                   13873:         my $primary_id = &domain($dom,'primary');
                   13874:         my $primary_ip = &get_host_ip($primary_id);
                   13875:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   13876:             foreach my $id (@{$iphost{$primary_ip}}) {
                   13877:                 my $intdom = &internet_dom($id);
                   13878:                 if ($intdom eq $hostintdom) {
                   13879:                     $same_intdom = 1;
                   13880:                     last;
                   13881:                 }
                   13882:             }
                   13883:         }
                   13884:     }
                   13885:     return $same_intdom;
                   13886: }
                   13887: 
1.1172.2.120  raeburn  13888: sub uses_sts {
                   13889:     my ($ignore_cache) = @_;
                   13890:     my $lonhost = $perlvar{'lonHostID'};
                   13891:     my $hostname = &hostname($lonhost);
                   13892:     my $sts_on;
                   13893:     if ($protocol{$lonhost} eq 'https') {
                   13894:         my $cachetime = 12*3600;
                   13895:         if (!$ignore_cache) {
                   13896:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   13897:             if (defined($cached)) {
                   13898:                 return $sts_on;
                   13899:             }
                   13900:         }
1.1172.2.121  raeburn  13901:         my $ua=new LWP::UserAgent;
1.1172.2.120  raeburn  13902:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   13903:         my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121  raeburn  13904:         my $response=$ua->request($request);
1.1172.2.120  raeburn  13905:         if ($response->is_success) {
                   13906:             my $has_sts = $response->header('Strict-Transport-Security');
                   13907:             if ($has_sts eq '') {
                   13908:                 $sts_on = 0;
                   13909:             } else {
                   13910:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   13911:                     my $maxage = $1;
                   13912:                     if ($maxage) {
                   13913:                         $sts_on = 1;
                   13914:                     } else {
                   13915:                         $sts_on = 0;
                   13916:                     }
                   13917:                 } else {
                   13918:                     $sts_on = 0;
                   13919:                 }
                   13920:             }
                   13921:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   13922:         }
                   13923:     }
                   13924:     return;
                   13925: }
                   13926: 
1.1172.2.142  raeburn  13927: sub waf_allssl {
                   13928:     my ($host_name) = @_;
                   13929:     my $alias = &get_proxy_alias();
                   13930:     if ($host_name eq '') {
                   13931:         $host_name = $ENV{'SERVER_NAME'};
                   13932:     }
                   13933:     if (($host_name ne '') && ($alias eq $host_name)) {
                   13934:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
                   13935:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   13936:         if ($defdomdefaults{'waf_sslopt'}) {
                   13937:             return $defdomdefaults{'waf_sslopt'};
                   13938:         }
                   13939:     }
                   13940:     return;
                   13941: }
                   13942: 
1.1172.2.134  raeburn  13943: sub get_requestor_ip {
                   13944:     my ($r,$nolookup,$noproxy) = @_;
                   13945:     my $from_ip;
                   13946:     if (ref($r)) {
1.1172.2.142  raeburn  13947:         if ($r->can('useragent_ip')) {
                   13948:             if ($noproxy && $r->can('client_ip')) {
                   13949:                 $from_ip = $r->client_ip();
                   13950:             } else {
                   13951:                 $from_ip = $r->useragent_ip();
                   13952:             }
                   13953:         } elsif ($r->connection->can('remote_ip')) {
                   13954:             $from_ip = $r->connection->remote_ip();
                   13955:         } else {
                   13956:             $from_ip = $r->get_remote_host($nolookup);
                   13957:         }
1.1172.2.134  raeburn  13958:     } else {
                   13959:         $from_ip = $ENV{'REMOTE_ADDR'};
                   13960:     }
1.1172.2.142  raeburn  13961:     return $from_ip if ($noproxy);
                   13962:    # Who controls proxy settings for server
                   13963:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   13964:     my $proxyinfo = &get_proxy_settings($dom_in_use);
                   13965:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
                   13966:         if ($proxyinfo->{'vpnint'}) {
                   13967:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
                   13968:                 return $from_ip;
                   13969:             }
                   13970:         }
                   13971:         if ($proxyinfo->{'trusted'}) {
                   13972:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
                   13973:                 my $ipheader = $proxyinfo->{'ipheader'};
                   13974:                 my ($ip,$xfor);
                   13975:                 if (ref($r)) {
                   13976:                     if ($ipheader) {
                   13977:                         $ip = $r->headers_in->{$ipheader};
                   13978:                     }
                   13979:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
                   13980:                 } else {
                   13981:                     if ($ipheader) {
                   13982:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
                   13983:                     }
                   13984:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
                   13985:                 }
                   13986:                 if (($ip eq '') && ($xfor ne '')) {
                   13987:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
                   13988:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
                   13989:                             $ip = $poss_ip;
                   13990:                             last;
                   13991:                         }
                   13992:                     }
                   13993:                 }
                   13994:                 if ($ip ne '') {
                   13995:                     return $ip;
                   13996:                 }
                   13997:             }
                   13998:         }
                   13999:     }
1.1172.2.134  raeburn  14000:     return $from_ip;
                   14001: }
                   14002: 
1.1172.2.142  raeburn  14003: sub get_proxy_settings {
                   14004:     my ($dom_in_use) = @_;
                   14005:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   14006:     my $proxyinfo = {
                   14007:                        ipheader => $domdefaults{'waf_ipheader'},
                   14008:                        trusted  => $domdefaults{'waf_trusted'},
                   14009:                        vpnint   => $domdefaults{'waf_vpnint'},
                   14010:                        vpnext   => $domdefaults{'waf_vpnext'},
                   14011:                        sslopt   => $domdefaults{'waf_sslopt'},
                   14012:                     };
                   14013:     return $proxyinfo;
                   14014: }
                   14015: 
                   14016: sub ip_match {
                   14017:     my ($ip,$pattern_str) = @_;
                   14018:     $ip=Net::CIDR::cidrvalidate($ip);
                   14019:     if ($ip) {
                   14020:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
                   14021:     }
                   14022:     return;
                   14023: }
                   14024: 
                   14025: sub get_proxy_alias {
                   14026:     my ($lonid) = @_;
                   14027:     if ($lonid eq '') {
                   14028:         $lonid = $perlvar{'lonHostID'};
                   14029:     }
                   14030:     if (!defined(&hostname($lonid))) {
                   14031:         return;
                   14032:     }
                   14033:     if ($lonid ne '') {
                   14034:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
                   14035:         if ($cached) {
                   14036:             return $alias;
                   14037:         }
                   14038:         my $dom = &Apache::lonnet::host_domain($lonid);
                   14039:         if ($dom ne '') {
                   14040:             my $cachetime = 60*60*24;
                   14041:             my %domconfig =
                   14042:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14043:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14044:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
                   14045:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
                   14046:                 }
                   14047:             }
                   14048:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
                   14049:         }
                   14050:     }
                   14051:     return;
                   14052: }
                   14053: 
                   14054: sub use_proxy_alias {
                   14055:     my ($r,$lonid) = @_;
                   14056:     my $alias = &get_proxy_alias($lonid);
                   14057:     if ($alias) {
                   14058:         my $dom = &host_domain($lonid);
                   14059:         if ($dom ne '') {
                   14060:             my $proxyinfo = &get_proxy_settings($dom);
                   14061:             my ($vpnint,$remote_ip);
                   14062:             if (ref($proxyinfo) eq 'HASH') {
                   14063:                 $vpnint = $proxyinfo->{'vpnint'};
                   14064:                 if ($vpnint) {
                   14065:                     $remote_ip = &get_requestor_ip($r,1,1);
                   14066:                 }
                   14067:             }
                   14068:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
                   14069:                 return $alias;
                   14070:             }
                   14071:         }
                   14072:     }
                   14073:     return;
                   14074: }
                   14075: 
                   14076: sub alias_sso {
                   14077:     my ($lonid) = @_;
                   14078:     if ($lonid eq '') {
                   14079:         $lonid = $perlvar{'lonHostID'};
                   14080:     }
                   14081:     if (!defined(&hostname($lonid))) {
                   14082:         return;
                   14083:     }
                   14084:     if ($lonid ne '') {
                   14085:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
                   14086:         if ($cached) {
                   14087:             return $use_alias;
                   14088:         }
                   14089:         my $dom = &Apache::lonnet::host_domain($lonid);
                   14090:         if ($dom ne '') {
                   14091:             my $cachetime = 60*60*24;
                   14092:             my %domconfig =
                   14093:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14094:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14095:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
                   14096:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
                   14097:                 }
                   14098:             }
                   14099:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
                   14100:         }
                   14101:     }
                   14102:     return;
                   14103: }
                   14104: 
                   14105: sub get_saml_landing {
                   14106:     my ($lonid) = @_;
                   14107:     if ($lonid eq '') {
                   14108:         my $defdom = &default_login_domain();
                   14109:         my @hosts = &current_machine_ids();
                   14110:         if (@hosts > 1) {
                   14111:             foreach my $hostid (@hosts) {
                   14112:                 if (&host_domain($hostid) eq $defdom) {
                   14113:                     $lonid = $hostid;
                   14114:                     last;
                   14115:                 }
                   14116:             }
                   14117:         } else {
                   14118:             $lonid = $perlvar{'lonHostID'};
                   14119:         }
                   14120:         if ($lonid) {
                   14121:             unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
                   14122:                 return;
                   14123:             }
                   14124:         } else {
                   14125:             return;
                   14126:         }
                   14127:     } elsif (!defined(&hostname($lonid))) {
                   14128:         return;
                   14129:     }
                   14130:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
                   14131:     if ($cached) {
                   14132:         return $landing;
                   14133:     }
                   14134:     my $dom = &Apache::lonnet::host_domain($lonid);
                   14135:     if ($dom ne '') {
                   14136:         my $cachetime = 60*60*24;
                   14137:         my %domconfig =
                   14138:             &Apache::lonnet::get_dom('configuration',['login'],$dom);
                   14139:         if (ref($domconfig{'login'}) eq 'HASH') {
                   14140:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
                   14141:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
                   14142:                     $landing = 1;
                   14143:                 }
                   14144:             }
                   14145:         }
                   14146:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
                   14147:     }
                   14148:     return;
                   14149: }
                   14150: 
1.31      www      14151: # ------------------------------------------------------------- Declutters URLs
                   14152: 
                   14153: sub declutter {
                   14154:     my $thisfn=shift;
1.569     albertel 14155:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  14156:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   14157:         $thisfn=~s{^/home/httpd/html}{};
                   14158:     }
1.31      www      14159:     $thisfn=~s/^\///;
1.697     albertel 14160:     $thisfn=~s|^adm/wrapper/||;
                   14161:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      14162:     $thisfn=~s/^res\///;
1.1172    bisitz   14163:     $thisfn=~s/^priv\///;
1.1032    raeburn  14164:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   14165:         $thisfn=~s/\?.+$//;
                   14166:     }
1.268     www      14167:     return $thisfn;
                   14168: }
                   14169: 
                   14170: # ------------------------------------------------------------- Clutter up URLs
                   14171: 
                   14172: sub clutter {
                   14173:     my $thisfn='/'.&declutter(shift);
1.887     albertel 14174:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 14175: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      14176:        $thisfn='/res'.$thisfn; 
                   14177:     }
1.1031    raeburn  14178:     if ($thisfn !~m|^/adm|) {
                   14179: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 14180: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 14181: 	} else {
                   14182: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   14183: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 14184: 	    if ($embstyle eq 'ssi'
                   14185: 		|| ($embstyle eq 'hdn')
                   14186: 		|| ($embstyle eq 'rat')
                   14187: 		|| ($embstyle eq 'prv')
                   14188: 		|| ($embstyle eq 'ign')) {
                   14189: 		#do nothing with these
                   14190: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 14191: 		|| ($embstyle eq 'emb')
                   14192: 		|| ($embstyle eq 'wrp')) {
                   14193: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 14194: 	    } elsif ($embstyle eq 'unk'
                   14195: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 14196: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 14197: 	    } else {
1.718     www      14198: #		&logthis("Got a blank emb style");
1.695     albertel 14199: 	    }
1.694     albertel 14200: 	}
1.1172.2.146.  .1(raebu 14201:22):     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
                   14202:22):         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 14203:     }
1.31      www      14204:     return $thisfn;
1.12      www      14205: }
                   14206: 
1.787     albertel 14207: sub clutter_with_no_wrapper {
                   14208:     my $uri = &clutter(shift);
                   14209:     if ($uri =~ m-^/adm/-) {
                   14210: 	$uri =~ s-^/adm/wrapper/-/-;
                   14211: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   14212:     }
                   14213:     return $uri;
                   14214: }
                   14215: 
1.557     albertel 14216: sub freeze_escape {
                   14217:     my ($value)=@_;
                   14218:     if (ref($value)) {
                   14219: 	$value=&nfreeze($value);
                   14220: 	return '__FROZEN__'.&escape($value);
                   14221:     }
                   14222:     return &escape($value);
                   14223: }
                   14224: 
1.11      www      14225: 
1.557     albertel 14226: sub thaw_unescape {
                   14227:     my ($value)=@_;
                   14228:     if ($value =~ /^__FROZEN__/) {
                   14229: 	substr($value,0,10,undef);
                   14230: 	$value=&unescape($value);
                   14231: 	return &thaw($value);
                   14232:     }
                   14233:     return &unescape($value);
                   14234: }
                   14235: 
1.436     albertel 14236: sub correct_line_ends {
                   14237:     my ($result)=@_;
                   14238:     $$result =~s/\r\n/\n/mg;
                   14239:     $$result =~s/\r/\n/mg;
1.415     albertel 14240: }
1.1       albertel 14241: # ================================================================ Main Program
                   14242: 
1.184     www      14243: sub goodbye {
1.204     albertel 14244:    &logthis("Starting Shut down");
1.443     albertel 14245: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 14246:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 14247: #converted
1.599     albertel 14248: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 14249:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   14250: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   14251: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 14252: #1.1 only
1.870     albertel 14253: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   14254: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   14255: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   14256: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   14257:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 14258:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   14259:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      14260:    &flushcourselogs();
                   14261:    &logthis("Shutting down");
                   14262: }
                   14263: 
1.852     albertel 14264: sub get_dns {
1.1172.2.17  raeburn  14265:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 14266:     if (!$ignore_cache) {
                   14267: 	my ($content,$cached)=
                   14268: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   14269: 	if ($cached) {
1.1172.2.17  raeburn  14270: 	    &$func($content,$hashref);
1.869     albertel 14271: 	    return;
                   14272: 	}
                   14273:     }
                   14274: 
                   14275:     my %alldns;
1.1172.2.96  raeburn  14276:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   14277:         foreach my $dns (<$config>) {
                   14278: 	    next if ($dns !~ /^\^(\S*)/x);
                   14279:             my $line = $1;
                   14280:             my ($host,$protocol) = split(/:/,$line);
                   14281:             if ($protocol ne 'https') {
                   14282:                 $protocol = 'http';
                   14283:             }
                   14284: 	    $alldns{$host} = $protocol;
1.979     raeburn  14285:         }
1.1172.2.96  raeburn  14286:         close($config);
1.869     albertel 14287:     }
                   14288:     while (%alldns) {
1.1172.2.52  raeburn  14289: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1172.2.142  raeburn  14290:         my @content;
                   14291:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
                   14292:             my $command = (split('/',$url))[3];
                   14293:             my ($dir,$file) = &parse_getdns_url($command,$url);
                   14294:             delete($alldns{$dns});
                   14295:             next if (($dir eq '') || ($file eq ''));
                   14296:             if (open(my $config,'<',"$dir/$file")) {
                   14297:                 @content = <$config>;
                   14298:                 close($config);
                   14299:             }
                   14300:         } else {
                   14301: 	    my $ua=new LWP::UserAgent;
                   14302:             $ua->timeout(30);
                   14303: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
                   14304: 	    my $response=$ua->request($request);
                   14305:             delete($alldns{$dns});
                   14306: 	    next if ($response->is_error());
                   14307: 	    @content = split("\n",$response->content);
                   14308:         }
1.1172.2.17  raeburn  14309:         unless ($nocache) {
1.1172.2.23  raeburn  14310: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  14311:         }
                   14312: 	&$func(\@content,$hashref);
1.869     albertel 14313: 	return;
1.852     albertel 14314:     }
1.871     albertel 14315:     my $which = (split('/',$url))[3];
                   14316:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  14317:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   14318:         my @content = <$config>;
                   14319:         &$func(\@content,$hashref);
                   14320:     }
1.1172.2.17  raeburn  14321:     return;
                   14322: }
                   14323: 
                   14324: # ------------------------------------------------------Get DNS checksums file
                   14325: sub parse_dns_checksums_tab {
                   14326:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  14327:     my $lonhost = $perlvar{'lonHostID'};
                   14328:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  14329:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  14330:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   14331:     my $webconfdir = '/etc/httpd/conf';
                   14332:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   14333:         $webconfdir = '/etc/apache2';
                   14334:     } elsif ($distro =~ /^sles(\d+)$/) {
                   14335:         if ($1 >= 10) {
                   14336:             $webconfdir = '/etc/apache2';
                   14337:         }
                   14338:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   14339:         if ($1 >= 10.0) {
                   14340:             $webconfdir = '/etc/apache2';
                   14341:         }
                   14342:     }
1.1172.2.17  raeburn  14343:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14344:     my (%chksum,%revnum);
                   14345:     if (ref($lines) eq 'ARRAY') {
                   14346:         chomp(@{$lines});
1.1172.2.34  raeburn  14347:         my $version = shift(@{$lines});
                   14348:         if ($version eq $release) {
1.1172.2.17  raeburn  14349:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  14350:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  14351:                 if ($file =~ m{^/etc/httpd/conf}) {
                   14352:                     if ($webconfdir eq '/etc/apache2') {
                   14353:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   14354:                     }
                   14355:                 }
1.1172.2.34  raeburn  14356:                 $chksum{$file} = $shasum;
                   14357:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  14358:             }
                   14359:             if (ref($hashref) eq 'HASH') {
                   14360:                 %{$hashref} = (
                   14361:                                 sums     => \%chksum,
                   14362:                                 versions => \%revnum,
                   14363:                               );
                   14364:             }
                   14365:         }
                   14366:     }
1.869     albertel 14367:     return;
1.852     albertel 14368: }
1.1172.2.17  raeburn  14369: 
                   14370: sub fetch_dns_checksums {
                   14371:     my %checksums;
1.1172.2.34  raeburn  14372:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  14373:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  14374:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14375:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  14376:              \%checksums);
                   14377:     return \%checksums;
                   14378: }
                   14379: 
1.1172.2.142  raeburn  14380: sub parse_getdns_url {
                   14381:     my ($command,$url) = @_;
                   14382:     my $dir = $perlvar{'lonTabDir'};
                   14383:     my $file;
                   14384:     if ($command eq 'hosts') {
                   14385:         $file = 'dns_hosts.tab';
                   14386:     } elsif ($command eq 'domain') {
                   14387:         $file = 'dns_domain.tab';
                   14388:     } elsif ($command eq 'checksums') {
                   14389:         my $version = (split('/',$url))[4];
                   14390:         $file = "dns_checksums/$version.tab",
                   14391:     }
                   14392:     return ($dir,$file);
                   14393: }
                   14394: 
1.327     albertel 14395: # ------------------------------------------------------------ Read domain file
                   14396: {
1.852     albertel 14397:     my $loaded;
1.846     albertel 14398:     my %domain;
                   14399: 
1.852     albertel 14400:     sub parse_domain_tab {
                   14401: 	my ($lines) = @_;
                   14402: 	foreach my $line (@$lines) {
                   14403: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      14404: 
1.846     albertel 14405: 	    chomp($line);
1.852     albertel 14406: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 14407: 	    my %this_domain;
                   14408: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   14409: 			       'lang_def', 'city', 'longi', 'lati',
                   14410: 			       'primary') {
                   14411: 		$this_domain{$field} = shift(@elements);
                   14412: 	    }
                   14413: 	    $domain{$name} = \%this_domain;
1.852     albertel 14414: 	}
                   14415:     }
1.864     albertel 14416: 
                   14417:     sub reset_domain_info {
                   14418: 	undef($loaded);
                   14419: 	undef(%domain);
                   14420:     }
                   14421: 
1.852     albertel 14422:     sub load_domain_tab {
1.1172.2.70  raeburn  14423: 	my ($ignore_cache,$nocache) = @_;
                   14424: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 14425: 	my $fh;
1.1172.2.96  raeburn  14426: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 14427: 	    my @lines = <$fh>;
                   14428: 	    &parse_domain_tab(\@lines);
1.448     albertel 14429: 	}
1.852     albertel 14430: 	close($fh);
                   14431: 	$loaded = 1;
1.327     albertel 14432:     }
1.846     albertel 14433: 
                   14434:     sub domain {
1.852     albertel 14435: 	&load_domain_tab() if (!$loaded);
                   14436: 
1.846     albertel 14437: 	my ($name,$what) = @_;
                   14438: 	return if ( !exists($domain{$name}) );
                   14439: 
                   14440: 	if (!$what) {
                   14441: 	    return $domain{$name}{'description'};
                   14442: 	}
                   14443: 	return $domain{$name}{$what};
                   14444:     }
1.974     raeburn  14445: 
                   14446:     sub domain_info {
                   14447:         &load_domain_tab() if (!$loaded);
                   14448:         return %domain;
                   14449:     }
                   14450: 
1.327     albertel 14451: }
                   14452: 
                   14453: 
1.1       albertel 14454: # ------------------------------------------------------------- Read hosts file
                   14455: {
1.838     albertel 14456:     my %hostname;
1.844     albertel 14457:     my %hostdom;
1.845     albertel 14458:     my %libserv;
1.852     albertel 14459:     my $loaded;
1.888     albertel 14460:     my %name_to_host;
1.1074    raeburn  14461:     my %internetdom;
1.1107    raeburn  14462:     my %LC_dns_serv;
1.852     albertel 14463: 
                   14464:     sub parse_hosts_tab {
                   14465: 	my ($file) = @_;
                   14466: 	foreach my $configline (@$file) {
                   14467: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  14468:             chomp($configline);
                   14469: 	    if ($configline =~ /^\^/) {
                   14470:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   14471:                     $LC_dns_serv{$1} = 1;
                   14472:                 }
                   14473:                 next;
                   14474:             }
1.1074    raeburn  14475: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 14476: 	    $name=~s/\s//g;
                   14477: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  14478:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   14479:                     my $curr = $hostname{$id};
                   14480:                     my $skip;
                   14481:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   14482:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   14483:                             $skip = 1;
                   14484:                         } else {
                   14485:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   14486:                         }
                   14487:                     }
                   14488:                     unless ($skip) {
                   14489:                         push(@{$name_to_host{$name}},$id);
                   14490:                     }
                   14491:                 } else {
                   14492:                     push(@{$name_to_host{$name}},$id);
                   14493:                 }
1.852     albertel 14494: 		$hostname{$id}=$name;
                   14495: 		$hostdom{$id}=$domain;
                   14496: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  14497:                 if (defined($protocol)) {
                   14498:                     if ($protocol eq 'https') {
                   14499:                         $protocol{$id} = $protocol;
                   14500:                     } else {
                   14501:                         $protocol{$id} = 'http'; 
                   14502:                     }
1.968     raeburn  14503:                 } else {
1.969     raeburn  14504:                     $protocol{$id} = 'http';
1.968     raeburn  14505:                 }
1.1074    raeburn  14506:                 if (defined($intdom)) {
                   14507:                     $internetdom{$id} = $intdom;
                   14508:                 }
1.852     albertel 14509: 	    }
                   14510: 	}
                   14511:     }
1.864     albertel 14512:     
                   14513:     sub reset_hosts_info {
1.897     albertel 14514: 	&purge_remembered();
1.864     albertel 14515: 	&reset_domain_info();
                   14516: 	&reset_hosts_ip_info();
1.892     albertel 14517: 	undef(%name_to_host);
1.864     albertel 14518: 	undef(%hostname);
                   14519: 	undef(%hostdom);
                   14520: 	undef(%libserv);
                   14521: 	undef($loaded);
                   14522:     }
1.1       albertel 14523: 
1.852     albertel 14524:     sub load_hosts_tab {
1.1172.2.70  raeburn  14525: 	my ($ignore_cache,$nocache) = @_;
                   14526: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  14527: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 14528: 	my @config = <$config>;
                   14529: 	&parse_hosts_tab(\@config);
                   14530: 	close($config);
                   14531: 	$loaded=1;
1.1       albertel 14532:     }
1.852     albertel 14533: 
1.838     albertel 14534:     sub hostname {
1.852     albertel 14535: 	&load_hosts_tab() if (!$loaded);
                   14536: 
1.838     albertel 14537: 	my ($lonid) = @_;
                   14538: 	return $hostname{$lonid};
                   14539:     }
1.845     albertel 14540: 
1.838     albertel 14541:     sub all_hostnames {
1.852     albertel 14542: 	&load_hosts_tab() if (!$loaded);
                   14543: 
1.838     albertel 14544: 	return %hostname;
                   14545:     }
1.845     albertel 14546: 
1.888     albertel 14547:     sub all_names {
1.1172.2.70  raeburn  14548:         my ($ignore_cache,$nocache) = @_;
                   14549: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 14550: 
                   14551: 	return %name_to_host;
                   14552:     }
                   14553: 
1.974     raeburn  14554:     sub all_host_domain {
                   14555:         &load_hosts_tab() if (!$loaded);
                   14556:         return %hostdom;
                   14557:     }
                   14558: 
1.845     albertel 14559:     sub is_library {
1.852     albertel 14560: 	&load_hosts_tab() if (!$loaded);
                   14561: 
1.845     albertel 14562: 	return exists($libserv{$_[0]});
                   14563:     }
                   14564: 
                   14565:     sub all_library {
1.852     albertel 14566: 	&load_hosts_tab() if (!$loaded);
                   14567: 
1.845     albertel 14568: 	return %libserv;
                   14569:     }
                   14570: 
1.1062    droeschl 14571:     sub unique_library {
                   14572: 	#2x reverse removes all hostnames that appear more than once
                   14573:         my %unique = reverse &all_library();
                   14574:         return reverse %unique;
                   14575:     }
                   14576: 
1.841     albertel 14577:     sub get_servers {
1.852     albertel 14578: 	&load_hosts_tab() if (!$loaded);
                   14579: 
1.841     albertel 14580: 	my ($domain,$type) = @_;
                   14581: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   14582: 	                                          : %hostname;
                   14583: 	my %result;
1.842     albertel 14584: 	if (ref($domain) eq 'ARRAY') {
                   14585: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 14586: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 14587: 		    $result{$host} = $hostname;
                   14588: 		}
                   14589: 	    }
                   14590: 	} else {
                   14591: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   14592: 		if ($hostdom{$host} eq $domain) {
                   14593: 		    $result{$host} = $hostname;
                   14594: 		}
1.841     albertel 14595: 	    }
                   14596: 	}
                   14597: 	return %result;
                   14598:     }
1.845     albertel 14599: 
1.1062    droeschl 14600:     sub get_unique_servers {
                   14601:         my %unique = reverse &get_servers(@_);
                   14602: 	return reverse %unique;
                   14603:     }
                   14604: 
1.844     albertel 14605:     sub host_domain {
1.852     albertel 14606: 	&load_hosts_tab() if (!$loaded);
                   14607: 
1.844     albertel 14608: 	my ($lonid) = @_;
                   14609: 	return $hostdom{$lonid};
                   14610:     }
                   14611: 
1.841     albertel 14612:     sub all_domains {
1.852     albertel 14613: 	&load_hosts_tab() if (!$loaded);
                   14614: 
1.841     albertel 14615: 	my %seen;
                   14616: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   14617: 	return @uniq;
                   14618:     }
1.1074    raeburn  14619: 
                   14620:     sub internet_dom {
                   14621:         &load_hosts_tab() if (!$loaded);
                   14622: 
                   14623:         my ($lonid) = @_;
                   14624:         return $internetdom{$lonid};
                   14625:     }
1.1107    raeburn  14626: 
                   14627:     sub is_LC_dns {
                   14628:         &load_hosts_tab() if (!$loaded);
                   14629: 
                   14630:         my ($hostname) = @_;
                   14631:         return exists($LC_dns_serv{$hostname});
                   14632:     }
                   14633: 
1.1       albertel 14634: }
                   14635: 
1.847     albertel 14636: { 
                   14637:     my %iphost;
1.856     albertel 14638:     my %name_to_ip;
                   14639:     my %lonid_to_ip;
1.869     albertel 14640: 
1.847     albertel 14641:     sub get_hosts_from_ip {
                   14642: 	my ($ip) = @_;
                   14643: 	my %iphosts = &get_iphost();
                   14644: 	if (ref($iphosts{$ip})) {
                   14645: 	    return @{$iphosts{$ip}};
                   14646: 	}
                   14647: 	return;
1.839     albertel 14648:     }
1.864     albertel 14649:     
                   14650:     sub reset_hosts_ip_info {
                   14651: 	undef(%iphost);
                   14652: 	undef(%name_to_ip);
                   14653: 	undef(%lonid_to_ip);
                   14654:     }
1.856     albertel 14655: 
                   14656:     sub get_host_ip {
                   14657: 	my ($lonid) = @_;
                   14658: 	if (exists($lonid_to_ip{$lonid})) {
                   14659: 	    return $lonid_to_ip{$lonid};
                   14660: 	}
                   14661: 	my $name=&hostname($lonid);
                   14662:    	my $ip = gethostbyname($name);
                   14663: 	return if (!$ip || length($ip) ne 4);
                   14664: 	$ip=inet_ntoa($ip);
                   14665: 	$name_to_ip{$name}   = $ip;
                   14666: 	$lonid_to_ip{$lonid} = $ip;
                   14667: 	return $ip;
                   14668:     }
1.847     albertel 14669:     
                   14670:     sub get_iphost {
1.1172.2.70  raeburn  14671: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14672: 
1.869     albertel 14673: 	if (!$ignore_cache) {
                   14674: 	    if (%iphost) {
                   14675: 		return %iphost;
                   14676: 	    }
                   14677: 	    my ($ip_info,$cached)=
                   14678: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14679: 	    if ($cached) {
                   14680: 		%iphost      = %{$ip_info->[0]};
                   14681: 		%name_to_ip  = %{$ip_info->[1]};
                   14682: 		%lonid_to_ip = %{$ip_info->[2]};
                   14683: 		return %iphost;
                   14684: 	    }
                   14685: 	}
1.894     albertel 14686: 
                   14687: 	# get yesterday's info for fallback
                   14688: 	my %old_name_to_ip;
                   14689: 	my ($ip_info,$cached)=
                   14690: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14691: 	if ($cached) {
                   14692: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14693: 	}
                   14694: 
1.1172.2.70  raeburn  14695: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14696: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14697: 	    my $ip;
                   14698: 	    if (!exists($name_to_ip{$name})) {
                   14699: 		$ip = gethostbyname($name);
                   14700: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14701: 		    if (defined($old_name_to_ip{$name})) {
                   14702: 			$ip = $old_name_to_ip{$name};
                   14703: 			&logthis("Can't find $name defaulting to old $ip");
                   14704: 		    } else {
                   14705: 			&logthis("Name $name no IP found");
                   14706: 			next;
                   14707: 		    }
                   14708: 		} else {
                   14709: 		    $ip=inet_ntoa($ip);
1.847     albertel 14710: 		}
                   14711: 		$name_to_ip{$name} = $ip;
                   14712: 	    } else {
                   14713: 		$ip = $name_to_ip{$name};
1.653     albertel 14714: 	    }
1.888     albertel 14715: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14716: 		$lonid_to_ip{$id} = $ip;
                   14717: 	    }
                   14718: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14719: 	}
1.1172.2.70  raeburn  14720:         unless ($nocache) {
                   14721: 	    &do_cache_new('iphost','iphost',
                   14722: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14723: 		          48*60*60);
                   14724:         }
1.869     albertel 14725: 
1.847     albertel 14726: 	return %iphost;
1.598     albertel 14727:     }
                   14728: 
1.992     raeburn  14729:     #
                   14730:     #  Given a DNS returns the loncapa host name for that DNS 
                   14731:     # 
                   14732:     sub host_from_dns {
                   14733:         my ($dns) = @_;
                   14734:         my @hosts;
                   14735:         my $ip;
                   14736: 
1.993     raeburn  14737:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14738:             $ip = $name_to_ip{$dns};
                   14739:         }
                   14740:         if (!$ip) {
                   14741:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14742:             if (length($ip) == 4) { 
                   14743: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14744:             }
                   14745:         }
                   14746:         if ($ip) {
                   14747: 	    @hosts = get_hosts_from_ip($ip);
                   14748: 	    return $hosts[0];
                   14749:         }
                   14750:         return undef;
1.986     foxr     14751:     }
1.992     raeburn  14752: 
1.1074    raeburn  14753:     sub get_internet_names {
                   14754:         my ($lonid) = @_;
                   14755:         return if ($lonid eq '');
                   14756:         my ($idnref,$cached)=
                   14757:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14758:         if ($cached) {
                   14759:             return $idnref;
                   14760:         }
                   14761:         my $ip = &get_host_ip($lonid);
                   14762:         my @hosts = &get_hosts_from_ip($ip);
                   14763:         my %iphost = &get_iphost();
                   14764:         my (@idns,%seen);
                   14765:         foreach my $id (@hosts) {
                   14766:             my $dom = &host_domain($id);
                   14767:             my $prim_id = &domain($dom,'primary');
                   14768:             my $prim_ip = &get_host_ip($prim_id);
                   14769:             next if ($seen{$prim_ip});
                   14770:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14771:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14772:                     my $intdom = &internet_dom($id);
                   14773:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14774:                         push(@idns,$intdom);
                   14775:                     }
                   14776:                 }
                   14777:             }
                   14778:             $seen{$prim_ip} = 1;
                   14779:         }
1.1172.2.23  raeburn  14780:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14781:     }
                   14782: 
1.986     foxr     14783: }
                   14784: 
1.1079    raeburn  14785: sub all_loncaparevs {
1.1172.2.39  raeburn  14786:     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  14787: }
                   14788: 
1.1172.2.27  raeburn  14789: # ------------------------------------------------------- Read loncaparev table
                   14790: {
                   14791:     sub load_loncaparevs {
                   14792:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  14793:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  14794:                 while (my $configline=<$config>) {
                   14795:                     chomp($configline);
                   14796:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14797:                     $loncaparevs{$hostid}=$loncaparev;
                   14798:                 }
                   14799:                 close($config);
                   14800:             }
                   14801:         }
                   14802:     }
                   14803: }
                   14804: 
                   14805: # ----------------------------------------------------- Read serverhostID table
                   14806: {
                   14807:     sub load_serverhomeIDs {
                   14808:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  14809:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  14810:                 while (my $configline=<$config>) {
                   14811:                     chomp($configline);
                   14812:                     my ($name,$id)=split(/:/,$configline);
                   14813:                     $serverhomeIDs{$name}=$id;
                   14814:                 }
                   14815:                 close($config);
                   14816:             }
                   14817:         }
                   14818:     }
                   14819: }
                   14820: 
                   14821: 
1.862     albertel 14822: BEGIN {
                   14823: 
                   14824: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14825:     unless ($readit) {
                   14826: {
                   14827:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14828:     %perlvar = (%perlvar,%{$configvars});
                   14829: }
                   14830: 
                   14831: 
1.1       albertel 14832: # ------------------------------------------------------ Read spare server file
                   14833: {
1.1172.2.96  raeburn  14834:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14835: 
                   14836:     while (my $configline=<$config>) {
                   14837:        chomp($configline);
1.284     matthew  14838:        if ($configline) {
1.784     albertel 14839: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14840: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14841: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14842:        }
                   14843:     }
1.448     albertel 14844:     close($config);
1.1       albertel 14845: }
1.11      www      14846: # ------------------------------------------------------------ Read permissions
                   14847: {
1.1172.2.96  raeburn  14848:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14849: 
                   14850:     while (my $configline=<$config>) {
1.448     albertel 14851: 	chomp($configline);
                   14852: 	if ($configline) {
                   14853: 	    my ($role,$perm)=split(/ /,$configline);
                   14854: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14855: 	}
1.11      www      14856:     }
1.448     albertel 14857:     close($config);
1.11      www      14858: }
                   14859: 
                   14860: # -------------------------------------------- Read plain texts for permissions
                   14861: {
1.1172.2.96  raeburn  14862:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14863: 
                   14864:     while (my $configline=<$config>) {
1.448     albertel 14865: 	chomp($configline);
                   14866: 	if ($configline) {
1.742     raeburn  14867: 	    my ($short,@plain)=split(/:/,$configline);
                   14868:             %{$prp{$short}} = ();
                   14869: 	    if (@plain > 0) {
                   14870:                 $prp{$short}{'std'} = $plain[0];
                   14871:                 for (my $i=1; $i<@plain; $i++) {
                   14872:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14873:                 }
                   14874:             }
1.448     albertel 14875: 	}
1.135     www      14876:     }
1.448     albertel 14877:     close($config);
1.135     www      14878: }
                   14879: 
                   14880: # ---------------------------------------------------------- Read package table
                   14881: {
1.1172.2.96  raeburn  14882:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14883: 
                   14884:     while (my $configline=<$config>) {
1.483     albertel 14885: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14886: 	chomp($configline);
                   14887: 	my ($short,$plain)=split(/:/,$configline);
                   14888: 	my ($pack,$name)=split(/\&/,$short);
                   14889: 	if ($plain ne '') {
                   14890: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14891: 	    $packagetab{$short}=$plain; 
                   14892: 	}
1.11      www      14893:     }
1.448     albertel 14894:     close($config);
1.329     matthew  14895: }
                   14896: 
1.1172.2.27  raeburn  14897: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  14898: 
1.1172.2.27  raeburn  14899: &load_loncaparevs();
                   14900: 
                   14901: # ------------------------------------------------------- Read serverhostID table
                   14902: 
                   14903: &load_serverhomeIDs();
1.1074    raeburn  14904: 
1.1172.2.27  raeburn  14905: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14906: {
                   14907:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14908:     if (-e $file) {
                   14909:         my $parser = HTML::LCParser->new($file);
                   14910:         while (my $token = $parser->get_token()) {
                   14911:             if ($token->[0] eq 'S') {
                   14912:                 my $item = $token->[1];
                   14913:                 my $name = $token->[2]{'name'};
                   14914:                 my $value = $token->[2]{'value'};
                   14915:                 if ($item ne '' && $name ne '' && $value ne '') {
                   14916:                     my $release = $parser->get_text();
                   14917:                     $release =~ s/(^\s*|\s*$ )//gx;
                   14918:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   14919:                 }
                   14920:             }
                   14921:         }
                   14922:     }
1.1073    raeburn  14923: }
                   14924: 
1.1138    raeburn  14925: # ---------------------------------------------------------- Read managers table
                   14926: {
                   14927:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  14928:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14929:             while (my $configline=<$config>) {
                   14930:                 chomp($configline);
                   14931:                 next if ($configline =~ /^\#/);
                   14932:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14933:                     $managerstab{$configline} = 1;
                   14934:                 }
                   14935:             }
                   14936:             close($config);
                   14937:         }
                   14938:     }
                   14939: }
                   14940: 
1.329     matthew  14941: # ------------- set up temporary directory
                   14942: {
1.1117    foxr     14943:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14944: 
1.11      www      14945: }
                   14946: 
1.1172.2.104  raeburn  14947: # ------------- set default texengine (domain default overrides this)
                   14948: {
                   14949:     $deftex = LONCAPA::texengine();
                   14950: }
                   14951: 
1.1172.2.114  raeburn  14952: # ------------- set default minimum length for passwords for internal auth users
                   14953: {
                   14954:     $passwdmin = LONCAPA::passwd_min();
                   14955: }
                   14956: 
1.794     albertel 14957: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14958: 				'compress_threshold'=> 20_000,
                   14959:  			        });
1.185     www      14960: 
1.281     www      14961: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14962: $dumpcount=0;
1.958     www      14963: $locknum=0;
1.22      www      14964: 
1.163     harris41 14965: &logtouch();
1.672     albertel 14966: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14967: $readit=1;
1.564     albertel 14968:     {
                   14969: 	use integer;
                   14970: 	my $test=(2**32)+1;
1.568     albertel 14971: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14972: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14973:     }
1.195     www      14974: }
1.1       albertel 14975: }
1.179     www      14976: 
1.1       albertel 14977: 1;
1.191     harris41 14978: __END__
                   14979: 
1.243     albertel 14980: =pod
                   14981: 
1.191     harris41 14982: =head1 NAME
                   14983: 
1.243     albertel 14984: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14985: 
                   14986: =head1 SYNOPSIS
                   14987: 
1.243     albertel 14988: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14989: 
                   14990:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14991: 
1.243     albertel 14992: Common parameters:
                   14993: 
                   14994: =over 4
                   14995: 
                   14996: =item *
                   14997: 
                   14998: $uname : an internal username (if $cname expecting a course Id specifically)
                   14999: 
                   15000: =item *
                   15001: 
                   15002: $udom : a domain (if $cdom expecting a course's domain specifically)
                   15003: 
                   15004: =item *
                   15005: 
                   15006: $symb : a resource instance identifier
                   15007: 
                   15008: =item *
                   15009: 
                   15010: $namespace : the name of a .db file that contains the data needed or
                   15011: being set.
                   15012: 
                   15013: =back
                   15014: 
1.394     bowersj2 15015: =head1 OVERVIEW
1.191     harris41 15016: 
1.394     bowersj2 15017: lonnet provides subroutines which interact with the
                   15018: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   15019: about classes, users, and resources.
1.243     albertel 15020: 
                   15021: For many of these objects you can also use this to store data about
                   15022: them or modify them in various ways.
1.191     harris41 15023: 
1.394     bowersj2 15024: =head2 Symbs
1.191     harris41 15025: 
1.394     bowersj2 15026: To identify a specific instance of a resource, LON-CAPA uses symbols
                   15027: or "symbs"X<symb>. These identifiers are built from the URL of the
                   15028: map, the resource number of the resource in the map, and the URL of
                   15029: the resource itself. The latter is somewhat redundant, but might help
                   15030: if maps change.
                   15031: 
                   15032: An example is
                   15033: 
                   15034:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   15035: 
                   15036: The respective map entry is
                   15037: 
                   15038:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   15039:   title="Problem 2">
                   15040:  </resource>
                   15041: 
                   15042: Symbs are used by the random number generator, as well as to store and
                   15043: restore data specific to a certain instance of for example a problem.
                   15044: 
                   15045: =head2 Storing And Retrieving Data
                   15046: 
                   15047: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   15048: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   15049: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   15050: is is the non-critical message twin of cstore. These functions are for
                   15051: handlers to store a perl hash to a user's permanent data space in an
                   15052: easy manner, and to retrieve it again on another call. It is expected
                   15053: that a handler would use this once at the beginning to retrieve data,
                   15054: and then again once at the end to send only the new data back.
                   15055: 
                   15056: The data is stored in the user's data directory on the user's
                   15057: homeserver under the ID of the course.
                   15058: 
                   15059: The hash that is returned by restore will have all of the previous
                   15060: value for all of the elements of the hash.
                   15061: 
                   15062: Example:
                   15063: 
                   15064:  #creating a hash
                   15065:  my %hash;
                   15066:  $hash{'foo'}='bar';
                   15067: 
                   15068:  #storing it
                   15069:  &Apache::lonnet::cstore(\%hash);
                   15070: 
                   15071:  #changing a value
                   15072:  $hash{'foo'}='notbar';
                   15073: 
                   15074:  #adding a new value
                   15075:  $hash{'bar'}='foo';
                   15076:  &Apache::lonnet::cstore(\%hash);
                   15077: 
                   15078:  #retrieving the hash
                   15079:  my %history=&Apache::lonnet::restore();
                   15080: 
                   15081:  #print the hash
                   15082:  foreach my $key (sort(keys(%history))) {
                   15083:    print("\%history{$key} = $history{$key}");
                   15084:  }
                   15085: 
                   15086: Will print out:
1.191     harris41 15087: 
1.394     bowersj2 15088:  %history{1:foo} = bar
                   15089:  %history{1:keys} = foo:timestamp
                   15090:  %history{1:timestamp} = 990455579
                   15091:  %history{2:bar} = foo
                   15092:  %history{2:foo} = notbar
                   15093:  %history{2:keys} = foo:bar:timestamp
                   15094:  %history{2:timestamp} = 990455580
                   15095:  %history{bar} = foo
                   15096:  %history{foo} = notbar
                   15097:  %history{timestamp} = 990455580
                   15098:  %history{version} = 2
                   15099: 
                   15100: Note that the special hash entries C<keys>, C<version> and
                   15101: C<timestamp> were added to the hash. C<version> will be equal to the
                   15102: total number of versions of the data that have been stored. The
                   15103: C<timestamp> attribute will be the UNIX time the hash was
                   15104: stored. C<keys> is available in every historical section to list which
                   15105: keys were added or changed at a specific historical revision of a
                   15106: hash.
                   15107: 
                   15108: B<Warning>: do not store the hash that restore returns directly. This
                   15109: will cause a mess since it will restore the historical keys as if the
                   15110: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 15111: 
1.394     bowersj2 15112: Calling convention:
1.191     harris41 15113: 
1.1172.2.27  raeburn  15114:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  15115:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 15116: 
1.394     bowersj2 15117: For more detailed information, see lonnet specific documentation.
1.191     harris41 15118: 
1.394     bowersj2 15119: =head1 RETURN MESSAGES
1.191     harris41 15120: 
1.394     bowersj2 15121: =over 4
1.191     harris41 15122: 
1.394     bowersj2 15123: =item * B<con_lost>: unable to contact remote host
1.191     harris41 15124: 
1.394     bowersj2 15125: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   15126: when the connection is brought back up
1.191     harris41 15127: 
1.394     bowersj2 15128: =item * B<con_failed>: unable to contact remote host and unable to save message
                   15129: for later delivery
1.191     harris41 15130: 
1.967     bisitz   15131: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 15132: 
1.394     bowersj2 15133: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 15134: that was requested
1.191     harris41 15135: 
1.243     albertel 15136: =back
1.191     harris41 15137: 
1.243     albertel 15138: =head1 PUBLIC SUBROUTINES
1.191     harris41 15139: 
1.243     albertel 15140: =head2 Session Environment Functions
1.191     harris41 15141: 
1.243     albertel 15142: =over 4
1.191     harris41 15143: 
1.394     bowersj2 15144: =item * 
                   15145: X<appenv()>
1.949     raeburn  15146: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 15147: the user envirnoment file, and will be restored for each access this
1.620     albertel 15148: user makes during this session, also modifies the %env for the current
1.949     raeburn  15149: process. Optional rolesarrayref - if defined contains a reference to an array
                   15150: of roles which are exempt from the restriction on modifying user.role entries 
                   15151: in the user's environment.db and in %env.    
1.191     harris41 15152: 
                   15153: =item *
1.394     bowersj2 15154: X<delenv()>
1.987     raeburn  15155: B<delenv($delthis,$regexp)>: removes all items from the session
                   15156: environment file that begin with $delthis. If the 
                   15157: optional second arg - $regexp - is true, $delthis is treated as a 
                   15158: regular expression, otherwise \Q$delthis\E is used. 
                   15159: The values are also deleted from the current processes %env.
1.191     harris41 15160: 
1.795     albertel 15161: =item * get_env_multiple($name) 
                   15162: 
                   15163: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   15164: values may be defined and end up as an array ref.
                   15165: 
                   15166: returns an array of values
                   15167: 
1.243     albertel 15168: =back
                   15169: 
                   15170: =head2 User Information
1.191     harris41 15171: 
1.243     albertel 15172: =over 4
1.191     harris41 15173: 
                   15174: =item *
1.394     bowersj2 15175: X<queryauthenticate()>
                   15176: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 15177: authentication scheme
                   15178: 
                   15179: =item *
1.394     bowersj2 15180: X<authenticate()>
1.1073    raeburn  15181: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 15182: authenticate user from domain's lib servers (first use the current
                   15183: one). C<$upass> should be the users password.
1.1073    raeburn  15184: $checkdefauth is optional (value is 1 if a check should be made to
                   15185:    authenticate user using default authentication method, and allow
                   15186:    account creation if username does not have account in the domain).
                   15187: $clientcancheckhost is optional (value is 1 if checking whether the
                   15188:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 15189: 
                   15190: =item *
1.394     bowersj2 15191: X<homeserver()>
                   15192: B<homeserver($uname,$udom)>: find the server which has
                   15193: the user's directory and files (there must be only one), this caches
                   15194: the answer, and also caches if there is a borken connection.
1.191     harris41 15195: 
                   15196: =item *
1.394     bowersj2 15197: X<idget()>
                   15198: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   15199: (IDs are a unique resource in a domain, there must be only 1 ID per
                   15200: username, and only 1 username per ID in a specific domain) (returns
                   15201: hash: id=>name,id=>name)
1.191     harris41 15202: 
                   15203: =item *
1.394     bowersj2 15204: X<idrget()>
                   15205: B<idrget($udom,@unames)>: find the IDs behind a list of
                   15206: usernames (returns hash: name=>id,name=>id)
1.191     harris41 15207: 
                   15208: =item *
1.394     bowersj2 15209: X<idput()>
                   15210: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 15211: 
                   15212: =item *
1.394     bowersj2 15213: X<rolesinit()>
1.1169    droeschl 15214: B<rolesinit($udom,$username)>: get user privileges.
                   15215: returns user role, first access and timer interval hashes
1.243     albertel 15216: 
                   15217: =item *
1.1171    droeschl 15218: X<privileged()>
                   15219: B<privileged($username,$domain)>: returns a true if user has a
                   15220: privileged and active role (i.e. su or dc), false otherwise.
                   15221: 
                   15222: =item *
1.551     albertel 15223: X<getsection()>
                   15224: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 15225: course $cname, return section name/number or '' for "not in course"
                   15226: and '-1' for "no section"
                   15227: 
                   15228: =item *
1.394     bowersj2 15229: X<userenvironment()>
                   15230: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 15231: passed in @what from the requested user's environment, returns a hash
                   15232: 
1.858     raeburn  15233: =item * 
                   15234: X<userlog_query()>
1.859     albertel 15235: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   15236: activity.log file. %filters defines filters applied when parsing the
                   15237: log file. These can be start or end timestamps, or the type of action
                   15238: - log to look for Login or Logout events, check for Checkin or
                   15239: Checkout, role for role selection. The response is in the form
                   15240: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   15241: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  15242: 
1.243     albertel 15243: =back
                   15244: 
                   15245: =head2 User Roles
                   15246: 
                   15247: =over 4
                   15248: 
                   15249: =item *
                   15250: 
1.1172.2.65  raeburn  15251: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   15252: returns codes for allowed actions.
                   15253: 
                   15254: The first argument is required, all others are optional.
                   15255: 
                   15256: $priv is the privilege being checked.
                   15257: $uri contains additional information about what is being checked for access (e.g.,
                   15258: URL, course ID etc.).
                   15259: $symb is the unique resource instance identifier in a course; if needed,
                   15260: but not provided, it will be retrieved via a call to &symbread().
                   15261: $role is the role for which a priv is being checked (only used if priv is evb).
                   15262: $clientip is the user's IP address (only used when checking for access to portfolio
                   15263: files).
                   15264: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   15265: prevents recursive calls to &allowed.
                   15266: 
1.243     albertel 15267:  F: full access
                   15268:  U,I,K: authentication modes (cxx only)
                   15269:  '': forbidden
                   15270:  1: user needs to choose course
                   15271:  2: browse allowed
1.766     albertel 15272:  A: passphrase authentication needed
1.1172.2.65  raeburn  15273:  B: access temporarily blocked because of a blocking event in a course.
1.1172.2.146.  .1(raebu 15274:22):  D: access blocked because access is required via session initiated via deep-link
1.243     albertel 15275: 
                   15276: =item *
                   15277: 
1.1172.2.13  raeburn  15278: constructaccess($url,$setpriv) : check for access to construction space URL
                   15279: 
                   15280: See if the owner domain and name in the URL match those in the
                   15281: expected environment.  If so, return three element list
                   15282: ($ownername,$ownerdomain,$ownerhome).
                   15283: 
                   15284: Otherwise return the null string.
                   15285: 
                   15286: If second argument 'setpriv' is true, it assigns the privileges,
                   15287: and returns the same three element list, unless the owner has
                   15288: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   15289: in which case the null string is returned.
                   15290: 
                   15291: =item *
                   15292: 
1.1172.2.84  raeburn  15293: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   15294: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   15295: for system, domain, and course level. $uname and $udom are optional (current
                   15296: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 15297: 
                   15298: =item *
                   15299: 
1.988     raeburn  15300: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   15301: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  15302: $type is Course (default) or Community.
1.988     raeburn  15303: If $forcedefault evaluates to true, text returned will be default 
                   15304: text for $type. Otherwise, if this is a course, the text returned 
                   15305: will be a custom name for the role (if defined in the course's 
                   15306: environment).  If no custom name is defined the default is returned.
                   15307:    
1.832     raeburn  15308: =item *
                   15309: 
1.1172.2.23  raeburn  15310: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  15311: All arguments are optional. Returns a hash of a roles, either for
                   15312: co-author/assistant author roles for a user's Construction Space
1.906     albertel 15313: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  15314: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   15315: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   15316: For each key, value is set to colon-separated start and end times for
                   15317: the role.  If no username and domain are specified, will default to
1.934     raeburn  15318: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  15319: of role statuses (active, future or previous), roles 
                   15320: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   15321: to restrict the list of roles reported. If no array ref is 
                   15322: provided for types, will default to return only active roles.
1.834     albertel 15323: 
1.1172.2.13  raeburn  15324: =item *
                   15325: 
                   15326: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   15327: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   15328: 
                   15329: Additional optional arguments are: $type (if role checking is to be restricted
                   15330: to certain user status types -- previous (expired roles), active (currently
                   15331: available roles) or future (roles available in the future), and
                   15332: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  15333: have active Domain Coordinator role in course's domain or in additional
                   15334: domains (specified in 'Domains to check for privileged users' in course
                   15335: environment -- set via:  Course Settings -> Classlists and staff listing).
                   15336: 
                   15337: =item *
                   15338: 
                   15339: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   15340: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   15341: $possdomains and $possroles are optional array refs -- to domains to check and
                   15342: roles to check.  If $possdomains is not specified, a dump will be done of the
                   15343: users' roles.db to check for a dc or su role in any domain. This can be
                   15344: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   15345: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   15346: this then allows &privileged_by_domain() to be used, which caches the identity
                   15347: of privileged users, eliminating the need for repeated calls to &dump().
                   15348: 
                   15349: =item *
                   15350: 
                   15351: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   15352: where the outer hash keys are domains specified in the $possdomains array ref,
                   15353: next inner hash keys are privileged roles specified in the $roles array ref,
                   15354: and the innermost hash contains key = value pairs for username:domain = end:start
                   15355: for active or future "privileged" users with that role in that domain. To avoid
                   15356: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   15357: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  15358: 
1.243     albertel 15359: =back
                   15360: 
                   15361: =head2 User Modification
                   15362: 
                   15363: =over 4
                   15364: 
                   15365: =item *
                   15366: 
1.957     raeburn  15367: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 15368: user for the level given by URL.  Optional start and end dates (leave empty
                   15369: string or zero for "no date")
1.191     harris41 15370: 
                   15371: =item *
                   15372: 
1.243     albertel 15373: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   15374: change a users, password, possible return values are: ok,
                   15375: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   15376: refused
1.191     harris41 15377: 
                   15378: =item *
                   15379: 
1.243     albertel 15380: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 15381: 
                   15382: =item *
                   15383: 
1.1058    raeburn  15384: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   15385:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   15386: 
                   15387: will update user information (firstname,middlename,lastname,generation,
                   15388: permanentemail), and if forceid is true, student/employee ID also.
                   15389: A user's institutional affiliation(s) can also be updated.
                   15390: User information fields will not be overwritten with empty entries 
                   15391: unless the field is included in the $candelete array reference.
                   15392: This array is included when a single user is modified via "Manage Users",
                   15393: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 15394: 
                   15395: =item *
                   15396: 
1.286     matthew  15397: modifystudent
                   15398: 
1.957     raeburn  15399: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  15400: The course id is resolved based on the current user's environment.  
                   15401: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  15402: associated with a course.
                   15403: 
1.297     matthew  15404: This call is essentially a wrapper for lonnet::modifyuser and
                   15405: lonnet::modify_student_enrollment
1.286     matthew  15406: 
                   15407: Inputs: 
                   15408: 
                   15409: =over 4
                   15410: 
1.957     raeburn  15411: =item B<$udom> Student's loncapa domain
1.286     matthew  15412: 
1.957     raeburn  15413: =item B<$uname> Student's loncapa login name
1.286     matthew  15414: 
1.964     bisitz   15415: =item B<$uid> Student/Employee ID
1.286     matthew  15416: 
1.957     raeburn  15417: =item B<$umode> Student's authentication mode
1.286     matthew  15418: 
1.957     raeburn  15419: =item B<$upass> Student's password
1.286     matthew  15420: 
1.957     raeburn  15421: =item B<$first> Student's first name
1.286     matthew  15422: 
1.957     raeburn  15423: =item B<$middle> Student's middle name
1.286     matthew  15424: 
1.957     raeburn  15425: =item B<$last> Student's last name
1.286     matthew  15426: 
1.957     raeburn  15427: =item B<$gene> Student's generation
1.286     matthew  15428: 
1.957     raeburn  15429: =item B<$usec> Student's section in course
1.286     matthew  15430: 
                   15431: =item B<$end> Unix time of the roles expiration
                   15432: 
                   15433: =item B<$start> Unix time of the roles start date
                   15434: 
                   15435: =item B<$forceid> If defined, allow $uid to be changed
                   15436: 
                   15437: =item B<$desiredhome> server to use as home server for student
                   15438: 
1.957     raeburn  15439: =item B<$email> Student's permanent e-mail address
                   15440: 
                   15441: =item B<$type> Type of enrollment (auto or manual)
                   15442: 
1.963     raeburn  15443: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   15444: 
                   15445: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  15446: 
1.963     raeburn  15447: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  15448: 
1.963     raeburn  15449: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  15450: 
1.1172.2.19  raeburn  15451: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   15452: 
                   15453: =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  15454: 
1.286     matthew  15455: =back
1.297     matthew  15456: 
                   15457: =item *
                   15458: 
                   15459: modify_student_enrollment
                   15460: 
1.1172.2.31  raeburn  15461: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  15462: 'role.request.course' must be defined for this function to proceed.
                   15463: 
                   15464: Inputs:
                   15465: 
                   15466: =over 4
                   15467: 
1.1172.2.31  raeburn  15468: =item $udom, student's domain
1.297     matthew  15469: 
1.1172.2.31  raeburn  15470: =item $uname, student's name
1.297     matthew  15471: 
1.1172.2.31  raeburn  15472: =item $uid, student's user id
1.297     matthew  15473: 
1.1172.2.31  raeburn  15474: =item $first, student's first name
1.297     matthew  15475: 
                   15476: =item $middle
                   15477: 
                   15478: =item $last
                   15479: 
                   15480: =item $gene
                   15481: 
                   15482: =item $usec
                   15483: 
                   15484: =item $end
                   15485: 
                   15486: =item $start
                   15487: 
1.957     raeburn  15488: =item $type
                   15489: 
                   15490: =item $locktype
                   15491: 
                   15492: =item $cid
                   15493: 
                   15494: =item $selfenroll
                   15495: 
                   15496: =item $context
                   15497: 
1.1172.2.19  raeburn  15498: =item $credits, number of credits student will earn from this class
                   15499: 
1.1172.2.76  raeburn  15500: =item $instsec, institutional course section code for student
                   15501: 
1.297     matthew  15502: =back
                   15503: 
1.191     harris41 15504: 
                   15505: =item *
                   15506: 
1.243     albertel 15507: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   15508: custom role; give a custom role to a user for the level given by URL.  Specify
                   15509: name and domain of role author, and role name
1.191     harris41 15510: 
                   15511: =item *
                   15512: 
1.243     albertel 15513: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 15514: 
                   15515: =item *
                   15516: 
1.243     albertel 15517: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   15518: 
                   15519: =back
                   15520: 
                   15521: =head2 Course Infomation
                   15522: 
                   15523: =over 4
1.191     harris41 15524: 
                   15525: =item *
                   15526: 
1.1118    foxr     15527: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 15528: specified course id, including all environment settings for the
                   15529: course, the description of the course will be in the hash under the
                   15530: key 'description'
1.191     harris41 15531: 
1.1118    foxr     15532: $options is an optional parameter that if supplied is a hash reference that controls
                   15533: what how this function works.  It has the following key/values:
                   15534: 
                   15535: =over 4
                   15536: 
                   15537: =item freshen_cache
                   15538: 
                   15539: If defined, and the environment cache for the course is valid, it is 
                   15540: returned in the returned hash.
                   15541: 
                   15542: =item one_time
                   15543: 
                   15544: If defined, the last cache time is set to _now_
                   15545: 
                   15546: =item user
                   15547: 
                   15548: If defined, the supplied username is used instead of the current user.
                   15549: 
                   15550: 
                   15551: =back
                   15552: 
1.191     harris41 15553: =item *
                   15554: 
1.624     albertel 15555: resdata($name,$domain,$type,@which) : request for current parameter
                   15556: setting for a specific $type, where $type is either 'course' or 'user',
                   15557: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  15558: answers for 10 minutes.
1.243     albertel 15559: 
1.877     foxr     15560: =item *
                   15561: 
                   15562: get_courseresdata($courseid, $domain) : dump the entire course resource
                   15563: data base, returning a hash that is keyed by the resource name and has
                   15564: values that are the resource value.  I believe that the timestamps and
                   15565: versions are also returned.
                   15566: 
1.1172.2.31  raeburn  15567: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   15568: supplemental content area. This routine caches the number of files for
                   15569: 10 minutes.
                   15570: 
1.243     albertel 15571: =back
                   15572: 
                   15573: =head2 Course Modification
                   15574: 
                   15575: =over 4
1.191     harris41 15576: 
                   15577: =item *
                   15578: 
1.243     albertel 15579: writecoursepref($courseid,%prefs) : write preferences (environment
                   15580: database) for a course
1.191     harris41 15581: 
                   15582: =item *
                   15583: 
1.1011    raeburn  15584: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   15585: 
                   15586: =item *
                   15587: 
1.1038    raeburn  15588: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 15589: 
1.1167    droeschl 15590: =item *
                   15591: 
                   15592: is_course($courseid), is_course($cdom, $cnum)
                   15593: 
                   15594: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   15595: two component version $cdom, $cnum. It checks if the specified course exists.
                   15596: 
                   15597: Returns:
                   15598:     undef if the course doesn't exist, otherwise
                   15599:     in scalar context the combined courseid.
                   15600:     in list context the two components of the course identifier, domain and 
                   15601:     courseid.    
                   15602: 
1.243     albertel 15603: =back
                   15604: 
1.1172.2.109  raeburn  15605: =head2 Bubblesheet Configuration
                   15606: 
                   15607: =over 4
                   15608: 
                   15609: =item *
                   15610: 
                   15611: get_scantron_config($which)
                   15612: 
                   15613: $which - the name of the configuration to parse from the file.
                   15614: 
                   15615: Parses and returns the bubblesheet configuration line selected as a
                   15616: hash of configuration file fields.
                   15617: 
                   15618: 
                   15619: Returns:
                   15620:     If the named configuration is not in the file, an empty
                   15621:     hash is returned.
                   15622: 
                   15623:     a hash with the fields
                   15624:       name         - internal name for the this configuration setup
                   15625:       description  - text to display to operator that describes this config
                   15626:       CODElocation - if 0 or the string 'none'
                   15627:                           - no CODE exists for this config
                   15628:                      if -1 || the string 'letter'
                   15629:                           - a CODE exists for this config and is
                   15630:                             a string of letters
                   15631:                      Unsupported value (but planned for future support)
                   15632:                           if a positive integer
                   15633:                                - The CODE exists as the first n items from
                   15634:                                  the question section of the form
                   15635:                           if the string 'number'
                   15636:                                - The CODE exists for this config and is
                   15637:                                  a string of numbers
                   15638:       CODEstart   - (only matter if a CODE exists) column in the line where
                   15639:                      the CODE starts
                   15640:       CODElength  - length of the CODE
                   15641:       IDstart     - column where the student/employee ID starts
                   15642:       IDlength    - length of the student/employee ID info
                   15643:       Qstart      - column where the information from the bubbled
                   15644:                     'questions' start
                   15645:       Qlength     - number of columns comprising a single bubble line from
                   15646:                     the sheet. (usually either 1 or 10)
                   15647:       Qon         - either a single character representing the character used
                   15648:                     to signal a bubble was chosen in the positional setup, or
                   15649:                     the string 'letter' if the letter of the chosen bubble is
                   15650:                     in the final, or 'number' if a number representing the
                   15651:                     chosen bubble is in the file (1->A 0->J)
                   15652:       Qoff        - the character used to represent that a bubble was
                   15653:                     left blank
                   15654:       PaperID     - if the scanning process generates a unique number for each
                   15655:                     sheet scanned the column that this ID number starts in
                   15656:       PaperIDlength - number of columns that comprise the unique ID number
                   15657:                       for the sheet of paper
                   15658:       FirstName   - column that the first name starts in
                   15659:       FirstNameLength - number of columns that the first name spans
                   15660:       LastName    - column that the last name starts in
                   15661:       LastNameLength - number of columns that the last name spans
                   15662:       BubblesPerRow - number of bubbles available in each row used to
                   15663:                       bubble an answer. (If not specified, 10 assumed).
                   15664: 
                   15665: 
                   15666: =item *
                   15667: 
                   15668: get_scantronformat_file($cdom)
                   15669: 
                   15670: $cdom - the course's domain (optional); if not supplied, uses
                   15671: domain for current $env{'request.course.id'}.
                   15672: 
                   15673: Returns an array containing lines from the scantron format file for
                   15674: the domain of the course.
                   15675: 
                   15676: If a url for a custom.tab file is listed in domain's configuration.db,
                   15677: lines are from this file.
                   15678: 
                   15679: Otherwise, if a default.tab has been published in RES space by the
                   15680: domainconfig user, lines are from this file.
                   15681: 
                   15682: Otherwise, fall back to getting lines from the legacy file on the
                   15683: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   15684: 
                   15685: =back
                   15686: 
1.243     albertel 15687: =head2 Resource Subroutines
                   15688: 
                   15689: =over 4
1.191     harris41 15690: 
                   15691: =item *
                   15692: 
1.243     albertel 15693: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 15694: 
                   15695: =item *
                   15696: 
1.243     albertel 15697: repcopy($filename) : subscribes to the requested file, and attempts to
                   15698: replicate from the owning library server, Might return
1.607     raeburn  15699: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   15700: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 15701: resource. Expects the local filesystem pathname
                   15702: (/home/httpd/html/res/....)
                   15703: 
                   15704: =back
                   15705: 
                   15706: =head2 Resource Information
                   15707: 
                   15708: =over 4
1.191     harris41 15709: 
                   15710: =item *
                   15711: 
1.1172.2.28  raeburn  15712: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   15713: and returns the value of a variety of different possible values,
                   15714: $varname should be a request string, and the other parameters can be
                   15715: used to specify who and what one is asking about. Ordinarily, $cid 
                   15716: does not need to be specified, as it is retrived from 
                   15717: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   15718: within lonuserstate::loadmap() when initializing a course, before
                   15719: $env{'request.course.id'} has been set, so it needs to be provided
                   15720: in that one case.
1.243     albertel 15721: 
                   15722: Possible values for $varname are environment.lastname (or other item
                   15723: from the envirnment hash), user.name (or someother aspect about the
                   15724: user), resource.0.maxtries (or some other part and parameter of a
                   15725: resource)
1.204     albertel 15726: 
                   15727: =item *
                   15728: 
1.243     albertel 15729: directcondval($number) : get current value of a condition; reads from a state
                   15730: string
1.204     albertel 15731: 
                   15732: =item *
                   15733: 
1.243     albertel 15734: condval($condidx) : value of condition index based on state
1.204     albertel 15735: 
                   15736: =item *
                   15737: 
1.243     albertel 15738: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   15739: resource's metadata, $what should be either a specific key, or either
                   15740: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   15741: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   15742: 
                   15743: this function automatically caches all requests
1.191     harris41 15744: 
                   15745: =item *
                   15746: 
1.243     albertel 15747: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15748: network of library servers; returns file handle of where SQL and regex results
                   15749: will be stored for query
1.191     harris41 15750: 
                   15751: =item *
                   15752: 
1.1172.2.66  raeburn  15753: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   15754: return symbolic list entry (all arguments optional).
                   15755: 
                   15756: Args: filename is the filename (including path) for the file for which a symb
                   15757: is required; donotrecurse, if true will prevent calls to allowed() being made
                   15758: to check access status if more than one resource was found in the bighash
                   15759: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   15760: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   15761: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15762: cause possible symbs to be checked to determine if they are subject to content
                   15763: blocking, if so they will not be included as possible symbs; possibles is a
                   15764: ref to a hash, which, as a side effect, will be populated with all possible
                   15765: symbs (content blocking not tested).
                   15766: 
1.243     albertel 15767: returns the data handle
1.191     harris41 15768: 
                   15769: =item *
                   15770: 
1.1172.2.17  raeburn  15771: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  15772: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15773: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  15774: on failure, user must be in a course, as it assumes the existence of
                   15775: the course initial hash, and uses $env('request.course.id'}.  The third
                   15776: arg is an optional reference to a scalar.  If this arg is passed in the
                   15777: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15778: encrypted; otherwise it will be null.
1.243     albertel 15779: 
1.191     harris41 15780: =item *
                   15781: 
1.243     albertel 15782: symbclean($symb) : removes versions numbers from a symb, returns the
                   15783: cleaned symb
1.191     harris41 15784: 
                   15785: =item *
                   15786: 
1.243     albertel 15787: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15788: course map, user must be in a course for it to work.
1.191     harris41 15789: 
                   15790: =item *
                   15791: 
1.243     albertel 15792: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15793: 
                   15794: =item *
                   15795: 
1.243     albertel 15796: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15797: a random seed, all arguments are optional, if they aren't sent it uses the
                   15798: environment to derive them. Note: if symb isn't sent and it can't get one
                   15799: from &symbread it will use the current time as its return value
1.191     harris41 15800: 
                   15801: =item *
                   15802: 
1.243     albertel 15803: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15804: unfakeable, receipt
1.191     harris41 15805: 
                   15806: =item *
                   15807: 
1.620     albertel 15808: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15809: 
                   15810: =item *
                   15811: 
1.243     albertel 15812: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15813: 
                   15814: =item *
                   15815: 
1.243     albertel 15816: 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 15817: 
                   15818: =item *
                   15819: 
1.243     albertel 15820: 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 15821: 
                   15822: =item *
                   15823: 
1.243     albertel 15824: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15825: 
                   15826: =item *
                   15827: 
1.243     albertel 15828: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15829: forcing spreadsheet to reevaluate the resource scores next time.
                   15830: 
1.1172.2.13  raeburn  15831: =item *
                   15832: 
                   15833: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15834: when viewing in course context.
                   15835: 
                   15836:  input: six args -- filename (decluttered), course number, course domain,
                   15837:                     url, symb (if registered) and group (if this is a
                   15838:                     group item -- e.g., bulletin board, group page etc.).
                   15839: 
                   15840:  output: array of five scalars --
                   15841:          $cfile -- url for file editing if editable on current server
                   15842:          $home -- homeserver of resource (i.e., for author if published,
                   15843:                                           or course if uploaded.).
                   15844:          $switchserver --  1 if server switch will be needed.
                   15845:          $forceedit -- 1 if icon/link should be to go to edit mode
                   15846:          $forceview -- 1 if icon/link should be to go to view mode
                   15847: 
                   15848: =item *
                   15849: 
                   15850: is_course_upload($file,$cnum,$cdom)
                   15851: 
                   15852: Used in course context to determine if current file was uploaded to
                   15853: the course (i.e., would be found in /userfiles/docs on the course's
                   15854: homeserver.
                   15855: 
                   15856:   input: 3 args -- filename (decluttered), course number and course domain.
                   15857:   output: boolean -- 1 if file was uploaded.
                   15858: 
1.243     albertel 15859: =back
                   15860: 
                   15861: =head2 Storing/Retreiving Data
                   15862: 
                   15863: =over 4
1.191     harris41 15864: 
                   15865: =item *
                   15866: 
1.1172.2.64  raeburn  15867: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   15868: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15869: the remaining args aren't required and if they aren't passed or are '' they will
                   15870: be derived from the env (with the exception of $laststore, which is an
                   15871: optional arg used when a user's submission is stored in grading).
                   15872: $laststore is $version=$timestamp, where $version is the most recent version
                   15873: number retrieved for the corresponding $symb in the $namespace db file, and
                   15874: $timestamp is the timestamp for that transaction (UNIX time).
                   15875: $laststore is currently only passed when cstore() is called by
                   15876: structuretags::finalize_storage().
1.191     harris41 15877: 
                   15878: =item *
                   15879: 
1.1172.2.64  raeburn  15880: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   15881: but uses critical subroutine
1.191     harris41 15882: 
                   15883: =item *
                   15884: 
1.243     albertel 15885: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15886: all args are optional
1.191     harris41 15887: 
                   15888: =item *
                   15889: 
1.717     albertel 15890: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15891: dumps the complete (or key matching regexp) namespace into a hash
                   15892: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15893: normally &store()ed into
                   15894: 
                   15895: $range should be either an integer '100' (give me the first 100
                   15896:                                            matching records)
                   15897:               or be  two integers sperated by a - with no spaces
                   15898:                  '30-50' (give me the 30th through the 50th matching
                   15899:                           records)
                   15900: 
                   15901: 
                   15902: =item *
                   15903: 
1.1172.2.59  raeburn  15904: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15905: replaces a &store() version of data with a replacement set of data
                   15906: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  15907: reference. If $tolog is true, the transaction is logged in the courselog
                   15908: with an action=PUTSTORE.
1.717     albertel 15909: 
                   15910: =item *
                   15911: 
1.243     albertel 15912: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15913: works very similar to store/cstore, but all data is stored in a
                   15914: temporary location and can be reset using tmpreset, $storehash should
                   15915: be a hash reference, returns nothing on success
1.191     harris41 15916: 
                   15917: =item *
                   15918: 
1.243     albertel 15919: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15920: similar to restore, but all data is stored in a temporary location and
                   15921: can be reset using tmpreset. Returns a hash of values on success,
                   15922: error string otherwise.
1.191     harris41 15923: 
                   15924: =item *
                   15925: 
1.243     albertel 15926: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15927: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15928: 
                   15929: =item *
                   15930: 
1.243     albertel 15931: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15932: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15933: 
                   15934: =item *
                   15935: 
1.243     albertel 15936: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15937: namesp ($udom and $uname are optional)
1.191     harris41 15938: 
                   15939: =item *
                   15940: 
1.702     albertel 15941: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15942: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15943: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15944: 
1.702     albertel 15945: $range should be either an integer '100' (give me the first 100
                   15946:                                            matching records)
                   15947:               or be  two integers sperated by a - with no spaces
                   15948:                  '30-50' (give me the 30th through the 50th matching
                   15949:                           records)
1.449     matthew  15950: =item *
                   15951: 
                   15952: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15953: $store can be a scalar, an array reference, or if the amount to be 
                   15954: incremented is > 1, a hash reference.
                   15955: 
                   15956: ($udom and $uname are optional)
1.191     harris41 15957: 
                   15958: =item *
                   15959: 
1.243     albertel 15960: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15961: ($udom and $uname are optional)
1.191     harris41 15962: 
                   15963: =item *
                   15964: 
1.243     albertel 15965: cput($namespace,$storehash,$udom,$uname) : critical put
                   15966: ($udom and $uname are optional)
1.191     harris41 15967: 
                   15968: =item *
                   15969: 
1.748     albertel 15970: newput($namespace,$storehash,$udom,$uname) :
                   15971: 
                   15972: Attempts to store the items in the $storehash, but only if they don't
                   15973: currently exist, if this succeeds you can be certain that you have 
                   15974: successfully created a new key value pair in the $namespace db.
                   15975: 
                   15976: 
                   15977: Args:
                   15978:  $namespace: name of database to store values to
                   15979:  $storehash: hashref to store to the db
                   15980:  $udom: (optional) domain of user containing the db
                   15981:  $uname: (optional) name of user caontaining the db
                   15982: 
                   15983: Returns:
                   15984:  'ok' -> succeeded in storing all keys of $storehash
                   15985:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15986:                         least <key> already existed in the db (other
                   15987:                         requested keys may also already exist)
1.967     bisitz   15988:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15989:  'con_lost' -> unable to contact request server
                   15990:  'refused' -> action was not allowed by remote machine
                   15991: 
                   15992: 
                   15993: =item *
                   15994: 
1.243     albertel 15995: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15996: reference filled in from namesp (encrypts the return communication)
                   15997: ($udom and $uname are optional)
1.191     harris41 15998: 
                   15999: =item *
                   16000: 
1.243     albertel 16001: log($udom,$name,$home,$message) : write to permanent log for user; use
                   16002: critical subroutine
                   16003: 
1.806     raeburn  16004: =item *
                   16005: 
1.860     raeburn  16006: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   16007: array reference filled in from namespace found in domain level on either
                   16008: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  16009: 
                   16010: =item *
                   16011: 
1.860     raeburn  16012: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   16013: domain level either on specified domain server ($uhome) or primary domain 
                   16014: server ($udom and $uhome are optional)
1.806     raeburn  16015: 
1.943     raeburn  16016: =item * 
                   16017: 
1.1172.2.35  raeburn  16018: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   16019: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   16020: the target domain.
                   16021: 
                   16022: May also include additional key => value pairs for the following groups:
                   16023: 
                   16024: =over
                   16025: 
                   16026: =item
                   16027: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   16028: 
                   16029: =over
                   16030: 
                   16031: =item defaultquota, authorquota
                   16032: 
                   16033: =back
                   16034: 
                   16035: =item
                   16036: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   16037: portfolio for users).
                   16038: 
                   16039: =over
                   16040: 
                   16041: =item
                   16042: aboutme, blog, webdav, portfolio
                   16043: 
                   16044: =back
                   16045: 
                   16046: =item
                   16047: requestcourses: ability to request courses, and how requests are processed.
                   16048: 
                   16049: =over
                   16050: 
                   16051: =item
1.1172.2.37  raeburn  16052: official, unofficial, community, textbook
1.1172.2.35  raeburn  16053: 
                   16054: =back
                   16055: 
                   16056: =item
                   16057: inststatus: types of institutional affiliation, and order in which they are displayed.
                   16058: 
                   16059: =over
                   16060: 
                   16061: =item
1.1172.2.44  raeburn  16062: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  16063: 
                   16064: =back
                   16065: 
                   16066: =item
                   16067: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   16068: for course's uploaded content.
                   16069: 
                   16070: =over
                   16071: 
                   16072: =item
1.1172.2.68  raeburn  16073: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   16074: communityquota, textbookquota
1.1172.2.35  raeburn  16075: 
                   16076: =back
                   16077: 
                   16078: =item
                   16079: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   16080: on your servers.
                   16081: 
                   16082: =over
                   16083: 
                   16084: =item
                   16085: remotesessions, hostedsessions
                   16086: 
                   16087: =back
                   16088: 
                   16089: =back
                   16090: 
                   16091: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   16092: utility to create a configuration.db file on a domain's primary library server
                   16093: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   16094: -- corresponding values are authentication type (internal, krb4, krb5,
                   16095: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   16096: will be available. Values are retrieved from cache (if current), unless the
                   16097: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   16098: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   16099: 
                   16100: Typical usage:
1.943     raeburn  16101: 
1.1172.2.35  raeburn  16102: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  16103: 
1.243     albertel 16104: =back
                   16105: 
                   16106: =head2 Network Status Functions
                   16107: 
                   16108: =over 4
1.191     harris41 16109: 
                   16110: =item *
                   16111: 
1.1137    raeburn  16112: dirlist() : return directory list based on URI (first arg).
                   16113: 
                   16114: Inputs: 1 required, 5 optional.
                   16115: 
                   16116: =over
                   16117: 
                   16118: =item 
                   16119: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   16120: 
                   16121: =item
                   16122: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   16123: 
                   16124: =item
                   16125: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   16126: 
                   16127: =item
                   16128: $getpropath - boolean: 1 if prepend path using &propath(). 
                   16129: 
                   16130: =item
                   16131: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   16132: 
                   16133: =item 
                   16134: $alternateRoot - path to prepend in place of path from $uri.
                   16135: 
                   16136: =back
                   16137: 
                   16138: Returns: Array of up to two items.
                   16139: 
                   16140: =over
                   16141: 
                   16142: a reference to an array of files/subdirectories
                   16143: 
                   16144: =over
                   16145: 
                   16146: Each element in the array of files/subdirectories is a & separated list of
                   16147: item name and the result of running stat on the item.  If dirlist was requested
                   16148: for a file instead of a directory, the item name will be ''. For a directory 
                   16149: listing, if the item is a metadata file, the element will end &N&M 
                   16150: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   16151: default copyright set (1).  
                   16152: 
                   16153: =back
                   16154: 
                   16155: a scalar containing error condition (if encountered).
                   16156: 
                   16157: =over
                   16158: 
                   16159: =item 
                   16160: no_host (no homeserver identified for $username:$domain).
                   16161: 
                   16162: =item 
                   16163: no_such_host (server contacted for listing not identified as valid host).
                   16164: 
                   16165: =item 
                   16166: con_lost (connection to remote server failed).
                   16167: 
                   16168: =item 
                   16169: refused (invalid $username:$domain received on lond side).
                   16170: 
                   16171: =item 
                   16172: no_such_dir (directory at specified path on lond side does not exist). 
                   16173: 
                   16174: =item 
                   16175: empty (directory at specified path on lond side is empty).
                   16176: 
                   16177: =over
                   16178: 
                   16179: This is currently not encountered because the &ls3, &ls2, 
                   16180: &ls (_handler) routines on the lond side do not filter out
                   16181: . and .. from a directory listing. 
                   16182: 
                   16183: =back
                   16184: 
                   16185: =back
                   16186: 
                   16187: =back
1.191     harris41 16188: 
                   16189: =item *
                   16190: 
1.243     albertel 16191: spareserver() : find server with least workload from spare.tab
                   16192: 
1.986     foxr     16193: 
                   16194: =item *
                   16195: 
                   16196: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   16197: if there is no corresponding loncapa host.
                   16198: 
1.243     albertel 16199: =back
                   16200: 
1.986     foxr     16201: 
1.243     albertel 16202: =head2 Apache Request
                   16203: 
                   16204: =over 4
1.191     harris41 16205: 
                   16206: =item *
                   16207: 
1.243     albertel 16208: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   16209: localhost, posts hash
                   16210: 
                   16211: =back
                   16212: 
                   16213: =head2 Data to String to Data
                   16214: 
                   16215: =over 4
1.191     harris41 16216: 
                   16217: =item *
                   16218: 
1.243     albertel 16219: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   16220: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 16221: 
                   16222: =item *
                   16223: 
1.243     albertel 16224: hashref2str($hashref) : convert a hashref into a string complete with
                   16225: escaping and '=' and '&' separators, supports elements that are
                   16226: arrayrefs and hashrefs
1.191     harris41 16227: 
                   16228: =item *
                   16229: 
1.243     albertel 16230: arrayref2str($arrayref) : convert an arrayref into a string complete
                   16231: with escaping and '&' separators, supports elements that are arrayrefs
                   16232: and hashrefs
1.191     harris41 16233: 
                   16234: =item *
                   16235: 
1.243     albertel 16236: str2hash($string) : convert string to hash using unescaping and
                   16237: splitting on '=' and '&', supports elements that are arrayrefs and
                   16238: hashrefs
1.191     harris41 16239: 
                   16240: =item *
                   16241: 
1.243     albertel 16242: str2array($string) : convert string to hash using unescaping and
                   16243: splitting on '&', supports elements that are arrayrefs and hashrefs
                   16244: 
                   16245: =back
                   16246: 
                   16247: =head2 Logging Routines
                   16248: 
                   16249: 
                   16250: These routines allow one to make log messages in the lonnet.log and
                   16251: lonnet.perm logfiles.
1.191     harris41 16252: 
1.1119    foxr     16253: =over 4
                   16254: 
1.191     harris41 16255: =item *
                   16256: 
1.243     albertel 16257: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 16258: 
                   16259: =item *
                   16260: 
1.243     albertel 16261: logthis() : append message to the normal lonnet.log file, it gets
                   16262: preiodically rolled over and deleted.
1.191     harris41 16263: 
                   16264: =item *
                   16265: 
1.243     albertel 16266: logperm() : append a permanent message to lonnet.perm.log, this log
                   16267: file never gets deleted by any automated portion of the system, only
                   16268: messages of critical importance should go in here.
                   16269: 
1.1119    foxr     16270: 
1.243     albertel 16271: =back
                   16272: 
                   16273: =head2 General File Helper Routines
                   16274: 
                   16275: =over 4
1.191     harris41 16276: 
                   16277: =item *
                   16278: 
1.481     raeburn  16279: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   16280: (a) files in /uploaded
                   16281:   (i) If a local copy of the file exists - 
                   16282:       compares modification date of local copy with last-modified date for 
                   16283:       definitive version stored on home server for course. If local copy is 
                   16284:       stale, requests a new version from the home server and stores it. 
                   16285:       If the original has been removed from the home server, then local copy 
                   16286:       is unlinked.
                   16287:   (ii) If local copy does not exist -
                   16288:       requests the file from the home server and stores it. 
                   16289:   
                   16290:   If $caller is 'uploadrep':  
                   16291:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   16292:     for request for files originally uploaded via DOCS. 
                   16293:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   16294:   
                   16295:   Otherwise:
                   16296:      This indicates a call from the content generation phase of the request.
                   16297:      -  returns the entire contents of the file or -1.
                   16298:      
                   16299: (b) files in /res
                   16300:    - returns the entire contents of a file or -1; 
                   16301:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 16302: 
1.712     albertel 16303: 
                   16304: =item *
                   16305: 
                   16306: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   16307:                   reference
                   16308: 
                   16309: returns either a stat() list of data about the file or an empty list
                   16310: if the file doesn't exist or couldn't find out about it (connection
                   16311: problems or user unknown)
                   16312: 
1.191     harris41 16313: =item *
                   16314: 
1.243     albertel 16315: filelocation($dir,$file) : returns file system location of a file
                   16316: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   16317: directory that relative $file lookups are to looked in ($dir of /a/dir
                   16318: and a file of ../bob will become /a/bob)
1.191     harris41 16319: 
                   16320: =item *
                   16321: 
                   16322: hreflocation($dir,$file) : returns file system location or a URL; same as
                   16323: filelocation except for hrefs
                   16324: 
                   16325: =item *
                   16326: 
1.1172.2.49  raeburn  16327: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   16328: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 16329: 
1.243     albertel 16330: =back
                   16331: 
1.608     albertel 16332: =head2 Usererfile file routines (/uploaded*)
                   16333: 
                   16334: =over 4
                   16335: 
                   16336: =item *
                   16337: 
                   16338: userfileupload(): main rotine for putting a file in a user or course's
                   16339:                   filespace, arguments are,
                   16340: 
1.620     albertel 16341:  formname - required - this is the name of the element in $env where the
1.608     albertel 16342:            filename, and the contents of the file to create/modifed exist
1.620     albertel 16343:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   16344:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  16345:  context - if coursedoc, store the file in the course of the active role
                   16346:              of the current user; 
                   16347:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   16348:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 16349:  subdir - required - subdirectory to put the file in under ../userfiles/
                   16350:          if undefined, it will be placed in "unknown"
                   16351: 
                   16352:  (This routine calls clean_filename() to remove any dangerous
                   16353:  characters from the filename, and then calls finuserfileupload() to
                   16354:  complete the transaction)
                   16355: 
                   16356:  returns either the url of the uploaded file (/uploaded/....) if successful
                   16357:  and /adm/notfound.html if unsuccessful
                   16358: 
                   16359: =item *
                   16360: 
                   16361: clean_filename(): routine for cleaing a filename up for storage in
                   16362:                  userfile space, argument is:
                   16363: 
                   16364:  filename - proposed filename
                   16365: 
                   16366: returns: the new clean filename
                   16367: 
                   16368: =item *
                   16369: 
1.1090    raeburn  16370: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 16371: userspace, probably shouldn't be called directly
                   16372: 
                   16373:   docuname: username or courseid of destination for the file
                   16374:   docudom: domain of user/course of destination for the file
                   16375:   formname: same as for userfileupload()
1.1090    raeburn  16376:   fname: filename (including subdirectories) for the file
                   16377:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  16378:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  16379:   allfiles: reference to hash used to store objects found by parser
                   16380:   codebase: reference to hash used for codebases of java objects found by parser
                   16381:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   16382:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   16383:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   16384:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   16385:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   16386:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  16387:   mimetype: reference to scalar to accommodate mime type determined
                   16388:             from File::MMagic if $parser = parse.
1.608     albertel 16389: 
                   16390:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  16391:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   16392:  was 'overwrite').
                   16393:  
1.608     albertel 16394: 
                   16395: =item *
                   16396: 
                   16397: renameuserfile(): renames an existing userfile to a new name
                   16398: 
                   16399:   Args:
                   16400:    docuname: username or courseid of destination for the file
                   16401:    docudom: domain of user/course of destination for the file
                   16402:    old: current file name (including any subdirs under userfiles)
                   16403:    new: desired file name (including any subdirs under userfiles)
                   16404: 
                   16405: =item *
                   16406: 
                   16407: mkdiruserfile(): creates a directory is a userfiles dir
                   16408: 
                   16409:   Args:
                   16410:    docuname: username or courseid of destination for the file
                   16411:    docudom: domain of user/course of destination for the file
                   16412:    dir: dir to create (including any subdirs under userfiles)
                   16413: 
                   16414: =item *
                   16415: 
                   16416: removeuserfile(): removes a file that exists in userfiles
                   16417: 
                   16418:   Args:
                   16419:    docuname: username or courseid of destination for the file
                   16420:    docudom: domain of user/course of destination for the file
                   16421:    fname: filname to delete (including any subdirs under userfiles)
                   16422: 
                   16423: =item *
                   16424: 
                   16425: removeuploadedurl(): convience function for removeuserfile()
                   16426: 
                   16427:   Args:
                   16428:    url:  a full /uploaded/... url to delete
                   16429: 
1.747     albertel 16430: =item * 
                   16431: 
                   16432: get_portfile_permissions():
                   16433:   Args:
                   16434:     domain: domain of user or course contain the portfolio files
                   16435:     user: name of user or num of course contain the portfolio files
                   16436:   Returns:
                   16437:     hashref of a dump of the proper file_permissions.db
                   16438:    
                   16439: 
                   16440: =item * 
                   16441: 
                   16442: get_access_controls():
                   16443: 
                   16444: Args:
                   16445:   current_permissions: the hash ref returned from get_portfile_permissions()
                   16446:   group: (optional) the group you want the files associated with
                   16447:   file: (optional) the file you want access info on
                   16448: 
                   16449: Returns:
1.749     raeburn  16450:     a hash (keys are file names) of hashes containing
                   16451:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   16452:         values are XML containing access control settings (see below) 
1.747     albertel 16453: 
                   16454: Internal notes:
                   16455: 
1.749     raeburn  16456:  access controls are stored in file_permissions.db as key=value pairs.
                   16457:     key -> path to file/file_name\0uniqueID:scope_end_start
                   16458:         where scope -> public,guest,course,group,domains or users.
                   16459:               end -> UNIX time for end of access (0 -> no end date)
                   16460:               start -> UNIX time for start of access
                   16461: 
                   16462:     value -> XML description of access control
                   16463:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   16464:             <start></start>
                   16465:             <end></end>
                   16466: 
                   16467:             <password></password>  for scope type = guest
                   16468: 
                   16469:             <domain></domain>     for scope type = course or group
                   16470:             <number></number>
                   16471:             <roles id="">
                   16472:              <role></role>
                   16473:              <access></access>
                   16474:              <section></section>
                   16475:              <group></group>
                   16476:             </roles>
                   16477: 
                   16478:             <dom></dom>         for scope type = domains
                   16479: 
                   16480:             <users>             for scope type = users
                   16481:              <user>
                   16482:               <uname></uname>
                   16483:               <udom></udom>
                   16484:              </user>
                   16485:             </users>
                   16486:            </scope> 
                   16487:               
                   16488:  Access data is also aggregated for each file in an additional key=value pair:
                   16489:  key -> path to file/file_name\0accesscontrol 
                   16490:  value -> reference to hash
                   16491:           hash contains key = value pairs
                   16492:           where key = uniqueID:scope_end_start
                   16493:                 value = UNIX time record was last updated
                   16494: 
                   16495:           Used to improve speed of look-ups of access controls for each file.  
                   16496:  
                   16497:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   16498: 
1.1172.2.13  raeburn  16499: =item *
                   16500: 
1.749     raeburn  16501: modify_access_controls():
                   16502: 
                   16503: Modifies access controls for a portfolio file
                   16504: Args
                   16505: 1. file name
                   16506: 2. reference to hash of required changes,
                   16507: 3. domain
                   16508: 4. username
                   16509:   where domain,username are the domain of the portfolio owner 
                   16510:   (either a user or a course) 
                   16511: 
                   16512: Returns:
                   16513: 1. result of additions or updates ('ok' or 'error', with error message). 
                   16514: 2. result of deletions ('ok' or 'error', with error message).
                   16515: 3. reference to hash of any new or updated access controls.
                   16516: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   16517:    key = integer (inbound ID)
1.1172.2.13  raeburn  16518:    value = uniqueID
                   16519: 
                   16520: =item *
                   16521: 
                   16522: get_timebased_id():
                   16523: 
                   16524: Attempts to get a unique timestamp-based suffix for use with items added to a
                   16525: course via the Course Editor (e.g., folders, composite pages,
                   16526: group bulletin boards).
                   16527: 
                   16528: Args: (first three required; six others optional)
                   16529: 
                   16530: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   16531:    docssequence, or name of group
                   16532: 
                   16533: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   16534:    e.g., num, boardids
                   16535: 
                   16536: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   16537:    file will be named nohist_namespace.db
                   16538: 
                   16539: 4. cdom: domain of course; default is current course domain from %env
                   16540: 
                   16541: 5. cnum: course number; default is current course number from %env
                   16542: 
                   16543: 6. idtype: set to concat if an additional digit is to be appended to the
                   16544:    unix timestamp to form the suffix, if the plain timestamp is already
                   16545:    in use.  Default is to not do this, but simply increment the unix
                   16546:    timestamp by 1 until a unique key is obtained.
                   16547: 
                   16548: 7. who: holder of locking key; defaults to user:domain for user.
                   16549: 
                   16550: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   16551:    retrying); default is 3.
                   16552: 
                   16553: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   16554: 
                   16555: Returns:
                   16556: 
                   16557: 1. suffix obtained (numeric)
                   16558: 
                   16559: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   16560: 
                   16561: 3. error: contains (localized) error message if an error occurred.
                   16562: 
1.747     albertel 16563: 
1.608     albertel 16564: =back
                   16565: 
1.243     albertel 16566: =head2 HTTP Helper Routines
                   16567: 
                   16568: =over 4
                   16569: 
1.191     harris41 16570: =item *
                   16571: 
                   16572: escape() : unpack non-word characters into CGI-compatible hex codes
                   16573: 
                   16574: =item *
                   16575: 
                   16576: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   16577: 
1.243     albertel 16578: =back
                   16579: 
                   16580: =head1 PRIVATE SUBROUTINES
                   16581: 
                   16582: =head2 Underlying communication routines (Shouldn't call)
                   16583: 
                   16584: =over 4
                   16585: 
                   16586: =item *
                   16587: 
                   16588: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   16589: 
                   16590: =item *
                   16591: 
                   16592: reply() : uses subreply to send a message to remote machine, logs all failures
                   16593: 
                   16594: =item *
                   16595: 
                   16596: critical() : passes a critical message to another server; if cannot
                   16597: get through then place message in connection buffer directory and
                   16598: returns con_delayed, if incapable of saving message, returns
                   16599: con_failed
                   16600: 
                   16601: =item *
                   16602: 
                   16603: reconlonc() : tries to reconnect lonc client processes.
                   16604: 
                   16605: =back
                   16606: 
                   16607: =head2 Resource Access Logging
                   16608: 
                   16609: =over 4
                   16610: 
                   16611: =item *
                   16612: 
                   16613: flushcourselogs() : flush (save) buffer logs and access logs
                   16614: 
                   16615: =item *
                   16616: 
                   16617: courselog($what) : save message for course in hash
                   16618: 
                   16619: =item *
                   16620: 
                   16621: courseacclog($what) : save message for course using &courselog().  Perform
                   16622: special processing for specific resource types (problems, exams, quizzes, etc).
                   16623: 
1.191     harris41 16624: =item *
                   16625: 
                   16626: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   16627: as a PerlChildExitHandler
1.243     albertel 16628: 
                   16629: =back
                   16630: 
                   16631: =head2 Other
                   16632: 
                   16633: =over 4
                   16634: 
                   16635: =item *
                   16636: 
                   16637: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 16638: 
                   16639: =back
                   16640: 
                   16641: =cut
1.877     foxr     16642: 

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