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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.146.  .4(raebu    4:22): # $Id: lonnet.pm,v 1.1172.2.146.2.3 2022/02/07 12:09:33 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.1172.2.146.  .4(raebu 2000:22): sub store_dom {
                   2001:22):     my ($storehash,$id,$namespace,$dom,$home,$encrypt) = @_;
                   2002:22):     $$storehash{'ip'}=&get_requestor_ip();
                   2003:22):     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2004:22):     my $namevalue='';
                   2005:22):     foreach my $key (keys(%{$storehash})) {
                   2006:22):         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   2007:22):     }
                   2008:22):     $namevalue=~s/\&$//;
                   2009:22):     if (grep { $_ eq $home } current_machine_ids()) {
                   2010:22):         return LONCAPA::Lond::store_dom("storedom:$dom:$namespace:$id:$namevalue");
                   2011:22):     } else {
                   2012:22):         if ($namespace eq 'private') {
                   2013:22):             return 'refused';
                   2014:22):         } elsif ($encrypt) {
                   2015:22):             return reply("encrypt:storedom:$dom:$namespace:$id:$namevalue",$home);
                   2016:22):         } else {
                   2017:22):             return reply("storedom:$dom:$namespace:$id:$namevalue",$home);
                   2018:22):         }
                   2019:22):     }
                   2020:22): }
                   2021:22): 
                   2022:22): sub restore_dom {
                   2023:22):     my ($id,$namespace,$dom,$home,$encrypt) = @_;
                   2024:22):     my $answer;
                   2025:22):     if (grep { $_ eq $home } current_machine_ids()) {
                   2026:22):         $answer = LONCAPA::Lond::restore_dom("restoredom:$dom:$namespace:$id");
                   2027:22):     } elsif ($namespace ne 'private') {
                   2028:22):         if ($encrypt) {
                   2029:22):             $answer=&reply("encrypt:restoredom:$dom:$namespace:$id",$home);
                   2030:22):         } else {
                   2031:22):             $answer=&reply("restoredom:$dom:$namespace:$id",$home);
                   2032:22):         }
                   2033:22):     }
                   2034:22):     my %returnhash=();
                   2035:22):     unless (($answer eq '') || ($answer eq 'con_lost') || ($answer eq 'refused') ||
                   2036:22):             ($answer eq 'unknown_cmd') || ($answer eq 'rejected')) {
                   2037:22):         foreach my $line (split(/\&/,$answer)) {
                   2038:22):             my ($name,$value)=split(/\=/,$line);
                   2039:22):             $returnhash{&unescape($name)}=&thaw_unescape($value);
                   2040:22):         }
                   2041:22):         my $version;
                   2042:22):         for ($version=1;$version<=$returnhash{'version'};$version++) {
                   2043:22):             foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2044:22):                 $returnhash{$item}=$returnhash{$version.':'.$item};
                   2045:22):             }
                   2046:22):         }
                   2047:22):     }
                   2048:22):     return %returnhash;
                   2049:22): }
                   2050:22): 
1.1023    raeburn  2051: # ----------------------------------construct domainconfig user for a domain 
                   2052: sub get_domainconfiguser {
                   2053:     my ($udom) = @_;
                   2054:     return $udom.'-domainconfig';
                   2055: }
                   2056: 
1.837     raeburn  2057: sub retrieve_inst_usertypes {
                   2058:     my ($udom) = @_;
                   2059:     my (%returnhash,@order);
1.989     raeburn  2060:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2061:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2062:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  2063:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2064:     } else {
                   2065:         if (defined(&domain($udom,'primary'))) {
                   2066:             my $uhome=&domain($udom,'primary');
                   2067:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2068:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  2069:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2070:                 return (\%returnhash,\@order);
                   2071:             }
                   2072:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2073:             my @pairs=split(/\&/,$hashitems);
                   2074:             foreach my $item (@pairs) {
                   2075:                 my ($key,$value)=split(/=/,$item,2);
                   2076:                 $key = &unescape($key);
                   2077:                 next if ($key =~ /^error: 2 /);
                   2078:                 $returnhash{$key}=&thaw_unescape($value);
                   2079:             }
                   2080:             my @esc_order = split(/\&/,$orderitems);
                   2081:             foreach my $item (@esc_order) {
                   2082:                 push(@order,&unescape($item));
                   2083:             }
                   2084:         } else {
1.1172.2.44  raeburn  2085:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2086:         }
1.1172.2.44  raeburn  2087:         return (\%returnhash,\@order);
1.837     raeburn  2088:     }
                   2089: }
                   2090: 
1.868     raeburn  2091: sub is_domainimage {
                   2092:     my ($url) = @_;
1.1172.2.142  raeburn  2093:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
1.868     raeburn  2094:         if (&domain($1) ne '') {
                   2095:             return '1';
                   2096:         }
                   2097:     }
                   2098:     return;
                   2099: }
                   2100: 
1.899     raeburn  2101: sub inst_directory_query {
                   2102:     my ($srch) = @_;
                   2103:     my $udom = $srch->{'srchdomain'};
                   2104:     my %results;
                   2105:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2106:     my $outcome;
1.899     raeburn  2107:     if ($homeserver ne '') {
1.1172.2.116  raeburn  2108:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2109:             if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2110:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116  raeburn  2111:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
                   2112:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2113:                     (($major == 2) && ($minor < 11)) ||
                   2114:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
                   2115:                     return;
                   2116:                 }
                   2117:             }
                   2118:         }
1.904     albertel 2119: 	my $queryid=&reply("querysend:instdirsearch:".
                   2120: 			   &escape($srch->{'srchby'}).':'.
                   2121: 			   &escape($srch->{'srchterm'}).':'.
                   2122: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2123: 	my $host=&hostname($homeserver);
                   2124: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  2125: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2126: 	    return;
                   2127: 	}
                   2128: 	my $response = &get_query_reply($queryid);
                   2129: 	my $maxtries = 5;
                   2130: 	my $tries = 1;
                   2131: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2132: 	    $response = &get_query_reply($queryid);
                   2133: 	    $tries ++;
                   2134: 	}
                   2135: 
                   2136:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2137:             if ($response eq 'unavailable') {
                   2138:                 $outcome = $response;
                   2139:             } else {
                   2140:                 $outcome = 'ok';
                   2141:                 my @matches = split(/\n/,$response);
                   2142:                 foreach my $match (@matches) {
                   2143:                     my ($key,$value) = split(/=/,$match);
                   2144:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2145:                 }
1.899     raeburn  2146:             }
                   2147:         }
                   2148:     }
1.909     raeburn  2149:     return ($outcome,%results);
1.899     raeburn  2150: }
                   2151: 
                   2152: sub usersearch {
                   2153:     my ($srch) = @_;
                   2154:     my $dom = $srch->{'srchdomain'};
                   2155:     my %results;
                   2156:     my %libserv = &all_library();
                   2157:     my $query = 'usersearch';
                   2158:     foreach my $tryserver (keys(%libserv)) {
                   2159:         if (&host_domain($tryserver) eq $dom) {
1.1172.2.116  raeburn  2160:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2161:                 if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2162:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.119  raeburn  2163:                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116  raeburn  2164:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2165:                              (($major == 2) && ($minor < 11)) ||
                   2166:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
                   2167:                 }
                   2168:             }
1.899     raeburn  2169:             my $host=&hostname($tryserver);
                   2170:             my $queryid=
1.911     raeburn  2171:                 &reply("querysend:".&escape($query).':'.
                   2172:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2173:                        &escape($srch->{'srchtype'}).':'.
                   2174:                        &escape($srch->{'srchterm'}),$tryserver);
                   2175:             if ($queryid !~/^\Q$host\E\_/) {
                   2176:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2177:                 next;
1.899     raeburn  2178:             }
                   2179:             my $reply = &get_query_reply($queryid);
                   2180:             my $maxtries = 1;
                   2181:             my $tries = 1;
                   2182:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2183:                 $reply = &get_query_reply($queryid);
                   2184:                 $tries ++;
                   2185:             }
                   2186:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2187:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2188:             } else {
1.911     raeburn  2189:                 my @matches;
                   2190:                 if ($reply =~ /\n/) {
                   2191:                     @matches = split(/\n/,$reply);
                   2192:                 } else {
                   2193:                     @matches = split(/\&/,$reply);
                   2194:                 }
1.899     raeburn  2195:                 foreach my $match (@matches) {
                   2196:                     my ($uname,$udom,%userhash);
1.911     raeburn  2197:                     foreach my $entry (split(/:/,$match)) {
                   2198:                         my ($key,$value) =
                   2199:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2200:                         $userhash{$key} = $value;
                   2201:                         if ($key eq 'username') {
                   2202:                             $uname = $value;
                   2203:                         } elsif ($key eq 'domain') {
                   2204:                             $udom = $value;
1.911     raeburn  2205:                         }
1.899     raeburn  2206:                     }
                   2207:                     $results{$uname.':'.$udom} = \%userhash;
                   2208:                 }
                   2209:             }
                   2210:         }
                   2211:     }
                   2212:     return %results;
                   2213: }
                   2214: 
1.912     raeburn  2215: sub get_instuser {
                   2216:     my ($udom,$uname,$id) = @_;
                   2217:     my $homeserver = &domain($udom,'primary');
                   2218:     my ($outcome,%results);
                   2219:     if ($homeserver ne '') {
                   2220:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2221:                            &escape($id).':'.&escape($udom),$homeserver);
                   2222:         my $host=&hostname($homeserver);
                   2223:         if ($queryid !~/^\Q$host\E\_/) {
                   2224:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2225:             return;
                   2226:         }
                   2227:         my $response = &get_query_reply($queryid);
                   2228:         my $maxtries = 5;
                   2229:         my $tries = 1;
                   2230:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2231:             $response = &get_query_reply($queryid);
                   2232:             $tries ++;
                   2233:         }
                   2234:         if (!&error($response) && $response ne 'refused') {
                   2235:             if ($response eq 'unavailable') {
                   2236:                 $outcome = $response;
                   2237:             } else {
                   2238:                 $outcome = 'ok';
                   2239:                 my @matches = split(/\n/,$response);
                   2240:                 foreach my $match (@matches) {
                   2241:                     my ($key,$value) = split(/=/,$match);
                   2242:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2243:                 }
                   2244:             }
                   2245:         }
                   2246:     }
                   2247:     my %userinfo;
                   2248:     if (ref($results{$uname}) eq 'HASH') {
                   2249:         %userinfo = %{$results{$uname}};
                   2250:     } 
                   2251:     return ($outcome,%userinfo);
                   2252: }
                   2253: 
1.1172.2.69  raeburn  2254: sub get_multiple_instusers {
                   2255:     my ($udom,$users,$caller) = @_;
                   2256:     my ($outcome,$results);
                   2257:     if (ref($users) eq 'HASH') {
                   2258:         my $count = keys(%{$users});
                   2259:         my $requested = &freeze_escape($users);
                   2260:         my $homeserver = &domain($udom,'primary');
                   2261:         if ($homeserver ne '') {
                   2262:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2263:             my $host=&hostname($homeserver);
                   2264:             if ($queryid !~/^\Q$host\E\_/) {
                   2265:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2266:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2267:                 return ($outcome,$results);
                   2268:             }
                   2269:             my $response = &get_query_reply($queryid);
                   2270:             my $maxtries = 5;
                   2271:             if ($count > 100) {
                   2272:                 $maxtries = 1+int($count/20);
                   2273:             }
                   2274:             my $tries = 1;
                   2275:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2276:                 $response = &get_query_reply($queryid);
                   2277:                 $tries ++;
                   2278:             }
                   2279:             if ($response eq '') {
                   2280:                 $results = {};
                   2281:                 foreach my $key (keys(%{$users})) {
                   2282:                     my ($uname,$id);
                   2283:                     if ($caller eq 'id') {
                   2284:                         $id = $key;
                   2285:                     } else {
                   2286:                         $uname = $key;
                   2287:                     }
                   2288:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2289:                     $outcome = $resp;
                   2290:                     if ($resp eq 'ok') {
                   2291:                         %{$results} = (%{$results}, %info);
                   2292:                     } else {
                   2293:                         last;
                   2294:                     }
                   2295:                 }
                   2296:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2297:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2298:                     $outcome = $response;
                   2299:                 } else {
                   2300:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2301:                     if ($outcome eq 'ok') {
                   2302:                         $results = &thaw_unescape($userdata);
                   2303:                     }
                   2304:                 }
                   2305:             }
                   2306:         }
                   2307:     }
                   2308:     return ($outcome,$results);
                   2309: }
                   2310: 
1.912     raeburn  2311: sub inst_rulecheck {
1.923     raeburn  2312:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2313:     my %returnhash;
                   2314:     if ($udom ne '') {
                   2315:         if (ref($rules) eq 'ARRAY') {
                   2316:             @{$rules} = map {&escape($_);} (@{$rules});
                   2317:             my $rulestr = join(':',@{$rules});
                   2318:             my $homeserver=&domain($udom,'primary');
                   2319:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2320:                 my $response;
                   2321:                 if ($item eq 'username') {                
                   2322:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2323:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2324:                                               $homeserver));
1.923     raeburn  2325:                 } elsif ($item eq 'id') {
                   2326:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2327:                                               ':'.&escape($id).':'.$rulestr,
                   2328:                                               $homeserver));
1.945     raeburn  2329:                 } elsif ($item eq 'selfcreate') {
                   2330:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2331:                                                &escape($udom).':'.&escape($uname).
                   2332:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2333:                 }
1.912     raeburn  2334:                 if ($response ne 'refused') {
                   2335:                     my @pairs=split(/\&/,$response);
                   2336:                     foreach my $item (@pairs) {
                   2337:                         my ($key,$value)=split(/=/,$item,2);
                   2338:                         $key = &unescape($key);
                   2339:                         next if ($key =~ /^error: 2 /);
                   2340:                         $returnhash{$key}=&thaw_unescape($value);
                   2341:                     }
                   2342:                 }
                   2343:             }
                   2344:         }
                   2345:     }
                   2346:     return %returnhash;
                   2347: }
                   2348: 
                   2349: sub inst_userrules {
1.923     raeburn  2350:     my ($udom,$check) = @_;
1.912     raeburn  2351:     my (%ruleshash,@ruleorder);
                   2352:     if ($udom ne '') {
                   2353:         my $homeserver=&domain($udom,'primary');
                   2354:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2355:             my $response;
                   2356:             if ($check eq 'id') {
                   2357:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2358:                                  $homeserver);
1.943     raeburn  2359:             } elsif ($check eq 'email') {
                   2360:                 $response=&reply('instemailrules:'.&escape($udom),
                   2361:                                  $homeserver);
1.923     raeburn  2362:             } else {
                   2363:                 $response=&reply('instuserrules:'.&escape($udom),
                   2364:                                  $homeserver);
                   2365:             }
1.912     raeburn  2366:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2367:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2368:                 ($response ne 'no_such_host')) {
                   2369:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2370:                 my @pairs=split(/\&/,$hashitems);
                   2371:                 foreach my $item (@pairs) {
                   2372:                     my ($key,$value)=split(/=/,$item,2);
                   2373:                     $key = &unescape($key);
                   2374:                     next if ($key =~ /^error: 2 /);
                   2375:                     $ruleshash{$key}=&thaw_unescape($value);
                   2376:                 }
                   2377:                 my @esc_order = split(/\&/,$orderitems);
                   2378:                 foreach my $item (@esc_order) {
                   2379:                     push(@ruleorder,&unescape($item));
                   2380:                 }
                   2381:             }
                   2382:         }
                   2383:     }
                   2384:     return (\%ruleshash,\@ruleorder);
                   2385: }
                   2386: 
1.976     raeburn  2387: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2388: 
                   2389: sub get_domain_defaults {
1.1172.2.35  raeburn  2390:     my ($domain,$ignore_cache) = @_;
                   2391:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2392:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2393:     unless ($ignore_cache) {
                   2394:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2395:         if (defined($cached)) {
                   2396:             if (ref($result) eq 'HASH') {
                   2397:                 return %{$result};
                   2398:             }
1.943     raeburn  2399:         }
                   2400:     }
                   2401:     my %domdefaults;
                   2402:     my %domconfig =
1.989     raeburn  2403:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2404:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2405:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2406:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2407:                                   'coursecategories','autoenroll',
1.1172.2.146.  .4(raebu 2408:22):                                   'helpsettings','wafproxy','ltisec'],$domain);
1.1172.2.41  raeburn  2409:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2410:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2411:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2412:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2413:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2414:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2415:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2416:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.91  raeburn  2417:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2418:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2419:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2420:     } else {
                   2421:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2422:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2423:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2424:     }
1.976     raeburn  2425:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2426:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2427:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2428:         } else {
                   2429:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2430:         }
1.1172.2.6  raeburn  2431:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2432:         foreach my $item (@usertools) {
                   2433:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2434:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2435:             }
                   2436:         }
1.1172.2.29  raeburn  2437:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2438:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2439:         }
1.976     raeburn  2440:     }
1.985     raeburn  2441:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2442:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2443:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2444:         }
                   2445:     }
1.1172.2.9  raeburn  2446:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2447:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2448:     }
1.989     raeburn  2449:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2450:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2451:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2452:         }
                   2453:     }
1.1047    raeburn  2454:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2455:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
1.1172.2.144  raeburn  2456:         $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
1.1172.2.60  raeburn  2457:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2458:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2459:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2460:         }
1.1172.2.41  raeburn  2461:         foreach my $type (@coursetypes) {
                   2462:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2463:                 unless ($type eq 'community') {
                   2464:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2465:                 }
                   2466:             }
                   2467:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2468:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2469:             }
1.1172.2.60  raeburn  2470:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2471:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2472:                     $domdefaults{$type.'postsubtimeout'} =
                   2473:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2474:                 }
                   2475:             }
1.1172.2.30  raeburn  2476:         }
1.1172.2.67  raeburn  2477:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2478:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2479:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2480:                 if (@clonecodes) {
                   2481:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2482:                 }
                   2483:             }
                   2484:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2485:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2486:         }
1.1172.2.103  raeburn  2487:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2488:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2489:         }
1.1172.2.146.  .3(raebu 2490:22):         if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
                   2491:22):             $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
                   2492:22):         }
1.1047    raeburn  2493:     }
1.1073    raeburn  2494:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2495:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2496:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2497:         }
                   2498:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2499:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2500:         }
1.1172.2.62  raeburn  2501:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2502:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2503:         }
1.1172.2.137  raeburn  2504:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1172.2.136  raeburn  2505:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
                   2506:         }
1.1073    raeburn  2507:     }
1.1172.2.41  raeburn  2508:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2509:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2510:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2511:                             'approval','limit');
                   2512:             foreach my $type (@coursetypes) {
                   2513:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2514:                     my @mgrdc = ();
                   2515:                     foreach my $item (@settings) {
                   2516:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2517:                             push(@mgrdc,$item);
                   2518:                         }
                   2519:                     }
                   2520:                     if (@mgrdc) {
                   2521:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2522:                     }
                   2523:                 }
                   2524:             }
                   2525:         }
                   2526:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2527:             foreach my $type (@coursetypes) {
                   2528:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2529:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2530:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2531:                     }
                   2532:                 }
                   2533:             }
                   2534:         }
                   2535:     }
1.1172.2.46  raeburn  2536:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2537:         $domdefaults{'catauth'} = 'std';
                   2538:         $domdefaults{'catunauth'} = 'std';
                   2539:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2540:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2541:         }
                   2542:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2543:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2544:         }
                   2545:     }
1.1172.2.76  raeburn  2546:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2547:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
1.1172.2.146  raeburn  2548:         $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
1.1172.2.76  raeburn  2549:     }
1.1172.2.89  raeburn  2550:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2551:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2552:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2553:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2554:         }
                   2555:     }
1.1172.2.142  raeburn  2556:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   2557:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
                   2558:             if ($domconfig{'wafproxy'}{$item}) {
                   2559:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
                   2560:             }
                   2561:         }
                   2562:     }
1.1172.2.146.  .4(raebu 2563:22):     if (ref($domconfig{'ltisec'}) eq 'HASH') {
                   2564:22):         if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
                   2565:22):             $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
                   2566:22):             $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
                   2567:22):             $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
                   2568:22):         }
                   2569:22):         if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
                   2570:22):             if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
                   2571:22):                 $domdefaults{'privhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
                   2572:22):             }
                   2573:22):         }
                   2574:22):     }
1.1172.2.23  raeburn  2575:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2576:     return %domdefaults;
                   2577: }
                   2578: 
1.1172.2.106  raeburn  2579: sub get_dom_cats {
                   2580:     my ($dom) = @_;
                   2581:     return unless (&domain($dom));
                   2582:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2583:     unless (defined($cached)) {
                   2584:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2585:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2586:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2587:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2588:             } else {
                   2589:                 $cats = {};
                   2590:             }
                   2591:         } else {
                   2592:             $cats = {};
                   2593:         }
                   2594:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2595:     }
                   2596:     return $cats;
                   2597: }
                   2598: 
                   2599: sub get_dom_instcats {
                   2600:     my ($dom) = @_;
                   2601:     return unless (&domain($dom));
                   2602:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2603:     unless (defined($cached)) {
                   2604:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2605:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2606:         if ($totcodes > 0) {
                   2607:             my $caller = 'global';
                   2608:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2609:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2610:                 $instcats = {
                   2611:                                 codes => \%codes,
                   2612:                                 codetitles => \@codetitles,
                   2613:                                 cat_titles => \%cat_titles,
                   2614:                                 cat_order => \%cat_order,
                   2615:                             };
                   2616:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2617:             }
                   2618:         }
                   2619:     }
                   2620:     return $instcats;
                   2621: }
                   2622: 
                   2623: sub retrieve_instcodes {
                   2624:     my ($coursecodes,$dom) = @_;
                   2625:     my $totcodes;
                   2626:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2627:     foreach my $course (keys(%courses)) {
                   2628:         if (ref($courses{$course}) eq 'HASH') {
                   2629:             if ($courses{$course}{'inst_code'} ne '') {
                   2630:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2631:                 $totcodes ++;
                   2632:             }
                   2633:         }
                   2634:     }
                   2635:     return $totcodes;
                   2636: }
                   2637: 
1.1172.2.113  raeburn  2638: # --------------------------------------------- Get domain config for passwords
                   2639: 
                   2640: sub get_passwdconf {
                   2641:     my ($dom) = @_;
                   2642:     my (%passwdconf,$gotconf,$lookup);
                   2643:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2644:     if (defined($cached)) {
                   2645:         if (ref($result) eq 'HASH') {
                   2646:             %passwdconf = %{$result};
                   2647:             $gotconf = 1;
                   2648:         }
                   2649:     }
                   2650:     unless ($gotconf) {
                   2651:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2652:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2653:             %passwdconf = %{$domconfig{'passwords'}};
                   2654:         }
                   2655:         my $cachetime = 24*60*60;
                   2656:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2657:     }
                   2658:     return %passwdconf;
                   2659: }
                   2660: 
1.1172.2.146.  .1(raebu 2661:22): sub course_portal_url {
                   2662:22):     my ($cnum,$cdom,$r) = @_;
                   2663:22):     my $chome = &homeserver($cnum,$cdom);
                   2664:22):     my $hostname = &hostname($chome);
                   2665:22):     my $protocol = $protocol{$chome};
                   2666:22):     $protocol = 'http' if ($protocol ne 'https');
                   2667:22):     my %domdefaults = &get_domain_defaults($cdom);
                   2668:22):     my $firsturl;
                   2669:22):     if ($domdefaults{'portal_def'}) {
                   2670:22):         $firsturl = $domdefaults{'portal_def'};
                   2671:22):     } else {
                   2672:22):         my $alias = &Apache::lonnet::use_proxy_alias($r,$chome);
                   2673:22):         $hostname = $alias if ($alias ne '');
                   2674:22):         $firsturl = $protocol.'://'.$hostname;
                   2675:22):     }
                   2676:22):     return $firsturl;
                   2677:22): }
                   2678:22): 
1.344     www      2679: # --------------------------------------------------- Assign a key to a student
                   2680: 
                   2681: sub assign_access_key {
1.364     www      2682: #
                   2683: # a valid key looks like uname:udom#comments
                   2684: # comments are being appended
                   2685: #
1.498     www      2686:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2687:     $kdom=
1.620     albertel 2688:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2689:     $knum=
1.620     albertel 2690:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2691:     $cdom=
1.620     albertel 2692:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2693:     $cnum=
1.620     albertel 2694:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2695:     $udom=$env{'user.name'} unless (defined($udom));
                   2696:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2697:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2698:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2699:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2700:                                                   # assigned to this person
                   2701:                                                   # - this should not happen,
1.345     www      2702:                                                   # unless something went wrong
                   2703:                                                   # the first time around
                   2704: # ready to assign
1.364     www      2705:         $logentry=$1.'; '.$logentry;
1.496     www      2706:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2707:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2708: # key now belongs to user
1.346     www      2709: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2710:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2711:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2712:                 return 'ok';
                   2713:             } else {
                   2714:                 return 
                   2715:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2716: 	    }
                   2717:         } else {
                   2718:             return 'error: Could not assign key, try again later.';
                   2719:         }
1.364     www      2720:     } elsif (!$existing{$ckey}) {
1.345     www      2721: # the key does not exist
                   2722: 	return 'error: The key does not exist';
                   2723:     } else {
                   2724: # the key is somebody else's
                   2725: 	return 'error: The key is already in use';
                   2726:     }
1.344     www      2727: }
                   2728: 
1.364     www      2729: # ------------------------------------------ put an additional comment on a key
                   2730: 
                   2731: sub comment_access_key {
                   2732: #
                   2733: # a valid key looks like uname:udom#comments
                   2734: # comments are being appended
                   2735: #
                   2736:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2737:     $cdom=
1.620     albertel 2738:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2739:     $cnum=
1.620     albertel 2740:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2741:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2742:     if ($existing{$ckey}) {
                   2743:         $existing{$ckey}.='; '.$logentry;
                   2744: # ready to assign
1.367     www      2745:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2746:                                                  $cdom,$cnum) eq 'ok') {
                   2747: 	    return 'ok';
                   2748:         } else {
                   2749: 	    return 'error: Count not store comment.';
                   2750:         }
                   2751:     } else {
                   2752: # the key does not exist
                   2753: 	return 'error: The key does not exist';
                   2754:     }
                   2755: }
                   2756: 
1.344     www      2757: # ------------------------------------------------------ Generate a set of keys
                   2758: 
                   2759: sub generate_access_keys {
1.364     www      2760:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2761:     $cdom=
1.620     albertel 2762:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2763:     $cnum=
1.620     albertel 2764:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2765:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2766:     unless (($cdom) && ($cnum)) { return 0; }
                   2767:     if ($number>10000) { return 0; }
                   2768:     sleep(2); # make sure don't get same seed twice
                   2769:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2770:     my $total=0;
                   2771:     for (my $i=1;$i<=$number;$i++) {
                   2772:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2773:                   sprintf("%lx",int(100000*rand)).'-'.
                   2774:                   sprintf("%lx",int(100000*rand));
                   2775:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2776:        $newkey=~s/0/h/g; # and also 0 and O
                   2777:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2778:        if ($existing{$newkey}) {
                   2779:            $i--;
                   2780:        } else {
1.364     www      2781: 	  if (&put('accesskeys',
                   2782:               { $newkey => '# generated '.localtime().
1.620     albertel 2783:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2784:                            '; '.$logentry },
                   2785: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2786:               $total++;
                   2787: 	  }
                   2788:        }
                   2789:     }
1.620     albertel 2790:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2791:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2792:     return $total;
                   2793: }
                   2794: 
                   2795: # ------------------------------------------------------- Validate an accesskey
                   2796: 
                   2797: sub validate_access_key {
                   2798:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2799:     $cdom=
1.620     albertel 2800:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2801:     $cnum=
1.620     albertel 2802:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2803:     $udom=$env{'user.domain'} unless (defined($udom));
                   2804:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2805:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2806:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2807: }
                   2808: 
                   2809: # ------------------------------------- Find the section of student in a course
1.652     albertel 2810: sub devalidate_getsection_cache {
                   2811:     my ($udom,$unam,$courseid)=@_;
                   2812:     my $hashid="$udom:$unam:$courseid";
                   2813:     &devalidate_cache_new('getsection',$hashid);
                   2814: }
1.298     matthew  2815: 
1.815     albertel 2816: sub courseid_to_courseurl {
                   2817:     my ($courseid) = @_;
                   2818:     #already url style courseid
                   2819:     return $courseid if ($courseid =~ m{^/});
                   2820: 
                   2821:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2822: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2823: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2824: 	return "/$cdom/$cnum";
                   2825:     }
                   2826: 
                   2827:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2828:     if (exists($courseinfo{'num'})) {
                   2829: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2830:     }
                   2831: 
                   2832:     return undef;
                   2833: }
                   2834: 
1.298     matthew  2835: sub getsection {
                   2836:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2837:     my $cachetime=1800;
1.551     albertel 2838: 
                   2839:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2840:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2841:     if (defined($cached)) { return $result; }
                   2842: 
1.298     matthew  2843:     my %Pending; 
                   2844:     my %Expired;
                   2845:     #
                   2846:     # Each role can either have not started yet (pending), be active, 
                   2847:     #    or have expired.
                   2848:     #
                   2849:     # If there is an active role, we are done.
                   2850:     #
                   2851:     # If there is more than one role which has not started yet, 
                   2852:     #     choose the one which will start sooner
                   2853:     # If there is one role which has not started yet, return it.
                   2854:     #
                   2855:     # If there is more than one expired role, choose the one which ended last.
                   2856:     # If there is a role which has expired, return it.
                   2857:     #
1.815     albertel 2858:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2859:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2860:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2861:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2862:         my $section=$1;
                   2863:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2864:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2865:         my $now=time;
1.548     albertel 2866:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2867:             $Expired{$end}=$section;
                   2868:             next;
                   2869:         }
1.548     albertel 2870:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2871:             $Pending{$start}=$section;
                   2872:             next;
                   2873:         }
1.599     albertel 2874:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2875:     }
                   2876:     #
                   2877:     # Presumedly there will be few matching roles from the above
                   2878:     # loop and the sorting time will be negligible.
                   2879:     if (scalar(keys(%Pending))) {
                   2880:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2881:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2882:     } 
                   2883:     if (scalar(keys(%Expired))) {
                   2884:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2885:         my $time = pop(@sorted);
1.599     albertel 2886:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2887:     }
1.599     albertel 2888:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2889: }
1.70      www      2890: 
1.599     albertel 2891: sub save_cache {
                   2892:     &purge_remembered();
1.722     albertel 2893:     #&Apache::loncommon::validate_page();
1.620     albertel 2894:     undef(%env);
1.780     albertel 2895:     undef($env_loaded);
1.599     albertel 2896: }
1.452     albertel 2897: 
1.599     albertel 2898: my $to_remember=-1;
                   2899: my %remembered;
                   2900: my %accessed;
                   2901: my $kicks=0;
                   2902: my $hits=0;
1.849     albertel 2903: sub make_key {
                   2904:     my ($name,$id) = @_;
1.872     albertel 2905:     if (length($id) > 65 
                   2906: 	&& length(&escape($id)) > 200) {
                   2907: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2908:     }
1.849     albertel 2909:     return &escape($name.':'.$id);
                   2910: }
                   2911: 
1.599     albertel 2912: sub devalidate_cache_new {
                   2913:     my ($name,$id,$debug) = @_;
                   2914:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2915:     my $remembered_id=$name.':'.$id;
1.849     albertel 2916:     $id=&make_key($name,$id);
1.599     albertel 2917:     $memcache->delete($id);
1.1172.2.81  raeburn  2918:     delete($remembered{$remembered_id});
                   2919:     delete($accessed{$remembered_id});
1.599     albertel 2920: }
                   2921: 
                   2922: sub is_cached_new {
                   2923:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2924:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2925:                                      # keys in %remembered hash, which persists for
                   2926:                                      # duration of request (no restriction on key length).
                   2927:     if (exists($remembered{$remembered_id})) {
                   2928: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2929: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2930: 	$hits++;
1.1172.2.81  raeburn  2931: 	return ($remembered{$remembered_id},1);
1.599     albertel 2932:     }
1.1172.2.81  raeburn  2933:     $id=&make_key($name,$id);
1.599     albertel 2934:     my $value = $memcache->get($id);
                   2935:     if (!(defined($value))) {
                   2936: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2937: 	return (undef,undef);
1.416     albertel 2938:     }
1.599     albertel 2939:     if ($value eq '__undef__') {
                   2940: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2941: 	$value=undef;
                   2942:     }
1.1172.2.81  raeburn  2943:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2944:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2945:     return ($value,1);
                   2946: }
                   2947: 
                   2948: sub do_cache_new {
                   2949:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  2950:     my $remembered_id=$name.':'.$id;
1.849     albertel 2951:     $id=&make_key($name,$id);
1.599     albertel 2952:     my $setvalue=$value;
                   2953:     if (!defined($setvalue)) {
                   2954: 	$setvalue='__undef__';
                   2955:     }
1.623     albertel 2956:     if (!defined($time) ) {
                   2957: 	$time=600;
                   2958:     }
1.599     albertel 2959:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2960:     my $result = $memcache->set($id,$setvalue,$time);
                   2961:     if (! $result) {
1.872     albertel 2962: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2963: 	$memcache->disconnect_all();
1.872     albertel 2964:     }
1.600     albertel 2965:     # need to make a copy of $value
1.1172.2.81  raeburn  2966:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2967:     return $value;
                   2968: }
                   2969: 
                   2970: sub make_room {
1.1172.2.81  raeburn  2971:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2972: 
1.1172.2.81  raeburn  2973:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2974:                                     : $value;
1.599     albertel 2975:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  2976:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2977:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2978:     my $to_kick;
                   2979:     my $max_time=0;
                   2980:     foreach my $other (keys(%accessed)) {
                   2981: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2982: 	    $to_kick=$other;
                   2983: 	    $max_time=&tv_interval($accessed{$other});
                   2984: 	}
                   2985:     }
                   2986:     delete($remembered{$to_kick});
                   2987:     delete($accessed{$to_kick});
                   2988:     $kicks++;
                   2989:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2990:     return;
                   2991: }
                   2992: 
1.599     albertel 2993: sub purge_remembered {
1.604     albertel 2994:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2995:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2996:     undef(%remembered);
                   2997:     undef(%accessed);
1.428     albertel 2998: }
1.70      www      2999: # ------------------------------------- Read an entry from a user's environment
                   3000: 
                   3001: sub userenvironment {
                   3002:     my ($udom,$unam,@what)=@_;
1.976     raeburn  3003:     my $items;
                   3004:     foreach my $item (@what) {
                   3005:         $items.=&escape($item).'&';
                   3006:     }
                   3007:     $items=~s/\&$//;
1.70      www      3008:     my %returnhash=();
1.1009    raeburn  3009:     my $uhome = &homeserver($unam,$udom);
                   3010:     unless ($uhome eq 'no_host') {
                   3011:         my @answer=split(/\&/, 
                   3012:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  3013:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   3014:             return %returnhash;
                   3015:         }
1.1009    raeburn  3016:         my $i;
                   3017:         for ($i=0;$i<=$#what;$i++) {
                   3018: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3019:         }
1.70      www      3020:     }
                   3021:     return %returnhash;
1.1       albertel 3022: }
                   3023: 
1.617     albertel 3024: # ---------------------------------------------------------- Get a studentphoto
                   3025: sub studentphoto {
                   3026:     my ($udom,$unam,$ext) = @_;
                   3027:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  3028:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3029:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3030:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3031:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3032:             } else {
                   3033:                 my ($result,$perm_reqd)=
1.707     albertel 3034: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3035:                 if ($result eq 'ok') {
                   3036:                     if (!($perm_reqd eq 'yes')) {
                   3037:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3038:                     }
                   3039:                 }
                   3040:             }
                   3041:         }
                   3042:     } else {
                   3043:         my ($result,$perm_reqd) = 
1.707     albertel 3044: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3045:         if ($result eq 'ok') {
                   3046:             if (!($perm_reqd eq 'yes')) {
                   3047:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3048:             }
                   3049:         }
                   3050:     }
                   3051:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3052: }
                   3053: 
                   3054: sub retrievestudentphoto {
                   3055:     my ($udom,$unam,$ext,$type) = @_;
                   3056:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   3057:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   3058:     if ($ret eq 'ok') {
                   3059:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3060:         if ($type eq 'thumbnail') {
                   3061:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3062:         }
                   3063:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   3064:         return $tokenurl;
                   3065:     } else {
                   3066:         if ($type eq 'thumbnail') {
                   3067:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3068:         } else { 
                   3069:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3070:         }
1.617     albertel 3071:     }
                   3072: }
                   3073: 
1.263     www      3074: # -------------------------------------------------------------------- New chat
                   3075: 
                   3076: sub chatsend {
1.724     raeburn  3077:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3078:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3079:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3080:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3081:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3082: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3083: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3084: }
                   3085: 
                   3086: # ------------------------------------------ Find current version of a resource
                   3087: 
                   3088: sub getversion {
                   3089:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  3090:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3091:     return &currentversion(&filelocation('',$fname));
                   3092: }
                   3093: 
                   3094: sub currentversion {
                   3095:     my $fname=shift;
                   3096:     my $author=$fname;
                   3097:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3098:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3099:     my $home=&homeserver($uname,$udom);
1.292     www      3100:     if ($home eq 'no_host') { 
                   3101:         return -1; 
                   3102:     }
1.1112    www      3103:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3104:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3105: 	return -1;
                   3106:     }
1.1112    www      3107:     return $answer;
1.263     www      3108: }
                   3109: 
1.1111    www      3110: #
                   3111: # Return special version number of resource if set by override, empty otherwise
                   3112: #
                   3113: sub usedversion {
                   3114:     my $fname=shift;
                   3115:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3116:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3117:     if ($urlversion) { return $urlversion; }
                   3118:     return '';
                   3119: }
                   3120: 
1.1       albertel 3121: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3122: 
1.1       albertel 3123: sub subscribe {
                   3124:     my $fname=shift;
1.761     raeburn  3125:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3126:     $fname=~s/[\n\r]//g;
1.1       albertel 3127:     my $author=$fname;
                   3128:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3129:     my ($udom,$uname)=split(/\//,$author);
                   3130:     my $home=homeserver($uname,$udom);
1.335     albertel 3131:     if ($home eq 'no_host') {
                   3132:         return 'not_found';
1.1       albertel 3133:     }
                   3134:     my $answer=reply("sub:$fname",$home);
1.64      www      3135:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3136: 	$answer.=' by '.$home;
                   3137:     }
1.1       albertel 3138:     return $answer;
                   3139: }
                   3140:     
1.8       www      3141: # -------------------------------------------------------------- Replicate file
                   3142: 
                   3143: sub repcopy {
                   3144:     my $filename=shift;
1.23      www      3145:     $filename=~s/\/+/\//g;
1.1142    raeburn  3146:     my $londocroot = $perlvar{'lonDocRoot'};
                   3147:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3148:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3149:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3150: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3151: 	return &repcopy_userfile($filename);
                   3152:     }
1.532     albertel 3153:     $filename=~s/[\n\r]//g;
1.8       www      3154:     my $transname="$filename.in.transfer";
1.828     www      3155: # FIXME: this should flock
1.607     raeburn  3156:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3157:     my $remoteurl=subscribe($filename);
1.64      www      3158:     if ($remoteurl =~ /^con_lost by/) {
                   3159: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3160:            return 'unavailable';
1.8       www      3161:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3162: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3163: 	   return 'not_found';
1.64      www      3164:     } elsif ($remoteurl =~ /^rejected by/) {
                   3165: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3166:            return 'forbidden';
1.20      www      3167:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3168:            return 'ok';
1.8       www      3169:     } else {
1.290     www      3170:         my $author=$filename;
                   3171:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3172:         my ($udom,$uname)=split(/\//,$author);
                   3173:         my $home=homeserver($uname,$udom);
                   3174:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3175:            my @parts=split(/\//,$filename);
                   3176:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3177:            if ($path ne "$londocroot/res") {
1.8       www      3178:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3179: 	       return 'bad_request';
1.8       www      3180:            }
                   3181:            my $count;
                   3182:            for ($count=5;$count<$#parts;$count++) {
                   3183:                $path.="/$parts[$count]";
                   3184:                if ((-e $path)!=1) {
                   3185: 		   mkdir($path,0777);
                   3186:                }
                   3187:            }
                   3188:            my $ua=new LWP::UserAgent;
                   3189:            my $request=new HTTP::Request('GET',"$remoteurl");
                   3190:            my $response=$ua->request($request,$transname);
                   3191:            if ($response->is_error()) {
                   3192: 	       unlink($transname);
                   3193:                my $message=$response->status_line;
1.672     albertel 3194:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3195:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3196:                return 'unavailable';
1.8       www      3197:            } else {
1.16      www      3198: 	       if ($remoteurl!~/\.meta$/) {
                   3199:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   3200:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   3201:                   if ($mresponse->is_error()) {
                   3202: 		      unlink($filename.'.meta');
                   3203:                       &logthis(
1.672     albertel 3204:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3205:                   }
                   3206: 	       }
1.8       www      3207:                rename($transname,$filename);
1.607     raeburn  3208:                return 'ok';
1.8       www      3209:            }
1.290     www      3210:        }
1.8       www      3211:     }
1.330     www      3212: }
                   3213: 
1.1172.2.124  raeburn  3214: # ------------------------------------------------- Unsubscribe from a resource
                   3215: 
                   3216: sub unsubscribe {
                   3217:     my ($fname) = @_;
                   3218:     my $answer;
                   3219:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3220:     $fname=~s/[\n\r]//g;
                   3221:     my $author=$fname;
                   3222:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3223:     my ($udom,$uname)=split(/\//,$author);
                   3224:     my $home=homeserver($uname,$udom);
                   3225:     if ($home eq 'no_host') {
                   3226:         $answer = 'no_host';
                   3227:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3228:         $answer = 'home';
                   3229:     } else {
1.1172.2.125  raeburn  3230:         $answer = reply("unsub:$fname",$home);
1.1172.2.124  raeburn  3231:     }
                   3232:     return $answer;
                   3233: }
                   3234: 
1.330     www      3235: # ------------------------------------------------ Get server side include body
                   3236: sub ssi_body {
1.381     albertel 3237:     my ($filelink,%form)=@_;
1.606     matthew  3238:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3239:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3240:     }
1.953     www      3241:     my $output='';
                   3242:     my $response;
1.980     raeburn  3243:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3244:        ($output,$response)=&externalssi($filelink);
1.953     www      3245:     } else {
1.1004    droeschl 3246:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3247:        $filelink .= 'inhibitmenu=yes';
1.953     www      3248:        ($output,$response)=&ssi($filelink,%form);
                   3249:     }
1.778     albertel 3250:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3251:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3252:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3253:     if (wantarray) {
                   3254:         return ($output, $response);
                   3255:     } else {
                   3256:         return $output;
                   3257:     }
1.8       www      3258: }
                   3259: 
1.15      www      3260: # --------------------------------------------------------- Server Side Include
                   3261: 
1.782     albertel 3262: sub absolute_url {
1.1172.2.145  raeburn  3263:     my ($host_name,$unalias,$keep_proto) = @_;
1.782     albertel 3264:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3265:     if ($host_name eq '') {
                   3266: 	$host_name = $ENV{'SERVER_NAME'};
                   3267:     }
1.1172.2.145  raeburn  3268:     if ($unalias) {
                   3269:         my $alias = &get_proxy_alias();
                   3270:         if ($alias eq $host_name) {
                   3271:             my $lonhost = $perlvar{'lonHostID'};
                   3272:             my $hostname = &hostname($lonhost);
                   3273:             my $lcproto;
                   3274:             if (($keep_proto) || ($hostname eq '')) {
                   3275:                 $lcproto = $protocol;
                   3276:             } else {
                   3277:                 $lcproto = $protocol{$lonhost};
                   3278:                 $lcproto = 'http' if ($lcproto ne 'https');
                   3279:                 $lcproto .= '://';
                   3280:             }
                   3281:             unless ($hostname eq '') {
                   3282:                 return $lcproto.$hostname;
                   3283:             }
                   3284:         }
                   3285:     } 
1.782     albertel 3286:     return $protocol.$host_name;
                   3287: }
                   3288: 
1.942     foxr     3289: #
                   3290: #   Server side include.
                   3291: # Parameters:
                   3292: #  fn     Possibly encrypted resource name/id.
                   3293: #  form   Hash that describes how the rendering should be done
                   3294: #         and other things.
1.944     foxr     3295: # Returns:
1.950     raeburn  3296: #   Scalar context: The content of the response.
                   3297: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3298: #     
1.15      www      3299: sub ssi {
                   3300: 
1.944     foxr     3301:     my ($fn,%form)=@_;
1.1172.2.145  raeburn  3302:     my ($host,$request,$response);
                   3303:     $host = &absolute_url('',1);
1.711     albertel 3304: 
                   3305:     $form{'no_update_last_known'}=1;
1.895     albertel 3306:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3307:     if (%form) {
1.1172.2.145  raeburn  3308:       $request=new HTTP::Request('POST',$host.$fn);
1.1172.2.58  raeburn  3309:       $request->content(join('&',map {
                   3310:             my $name = escape($_);
                   3311:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3312:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3313:             : &escape($form{$_}) );
                   3314:         } keys(%form)));
1.23      www      3315:     } else {
1.1172.2.145  raeburn  3316:       $request=new HTTP::Request('GET',$host.$fn);
1.23      www      3317:     }
                   3318: 
1.15      www      3319:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3320: 
1.1172.2.101  raeburn  3321:     if (($env{'request.course.id'}) &&
                   3322:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3323:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3324:         ($form{'grade_symb'} ne '') &&
                   3325:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3326:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3327:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3328:             my $ua=new LWP::UserAgent;
                   3329:             $ua->local_address('127.0.0.1');
                   3330:             $response = $ua->request($request);
                   3331:         } else {
                   3332:             {
                   3333:                 require LWP::Protocol::http;
                   3334:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3335:                 my $ua=new LWP::UserAgent;
                   3336:                 $response = $ua->request($request);
                   3337:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3338:             }
                   3339:         }
                   3340:     } else {
                   3341:         my $ua=new LWP::UserAgent;
                   3342:         $response = $ua->request($request);
                   3343:     }
1.944     foxr     3344:     if (wantarray) {
1.1172.2.3  raeburn  3345: 	return ($response->content, $response);
1.944     foxr     3346:     } else {
1.1172.2.3  raeburn  3347: 	return $response->content;
1.942     foxr     3348:     }
1.324     www      3349: }
                   3350: 
                   3351: sub externalssi {
                   3352:     my ($url)=@_;
                   3353:     my $ua=new LWP::UserAgent;
                   3354:     my $request=new HTTP::Request('GET',$url);
                   3355:     my $response=$ua->request($request);
1.954     raeburn  3356:     if (wantarray) {
                   3357:         return ($response->content, $response);
                   3358:     } else {
                   3359:         return $response->content;
                   3360:     }
1.15      www      3361: }
1.254     www      3362: 
1.1172.2.98  raeburn  3363: # If the local copy of a replicated resource is outdated, trigger a
                   3364: # connection from the homeserver to flush the delayed queue. If no update
                   3365: # happens, remove local copies of outdated resource (and corresponding
                   3366: # metadata file).
                   3367: 
                   3368: sub remove_stale_resfile {
                   3369:     my ($url) = @_;
                   3370:     my $removed;
                   3371:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3372:         my $audom = $1;
                   3373:         my $auname = $2;
                   3374:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3375:             my $homeserver = &homeserver($auname,$audom);
                   3376:             unless (($homeserver eq 'no_host') ||
                   3377:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3378:                 my $fname = &filelocation('',$url);
                   3379:                 if (-e $fname) {
                   3380:                     my $hostname = &hostname($homeserver);
                   3381:                     if ($hostname) {
1.1172.2.120  raeburn  3382:                         my $protocol = $protocol{$homeserver};
                   3383:                         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98  raeburn  3384:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.120  raeburn  3385:                         my $ua=new LWP::UserAgent;
                   3386:                         $ua->timeout(5);
1.1172.2.98  raeburn  3387:                         my $request=new HTTP::Request('HEAD',$uri);
                   3388:                         my $response=$ua->request($request);
                   3389:                         if ($response->is_success()) {
                   3390:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3391:                             my $locmodtime = (stat($fname))[9];
                   3392:                             if ($locmodtime < $remmodtime) {
                   3393:                                 my $stale;
                   3394:                                 my $answer = &reply('pong',$homeserver);
                   3395:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3396:                                     sleep(0.2);
                   3397:                                     $locmodtime = (stat($fname))[9];
                   3398:                                     if ($locmodtime < $remmodtime) {
                   3399:                                         my $posstransfer = $fname.'.in.transfer';
                   3400:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3401:                                             $removed = 1;
                   3402:                                         } else {
                   3403:                                             $stale = 1;
                   3404:                                         }
                   3405:                                     } else {
                   3406:                                         $removed = 1;
                   3407:                                     }
                   3408:                                 } else {
                   3409:                                     $stale = 1;
                   3410:                                 }
                   3411:                                 if ($stale) {
1.1172.2.124  raeburn  3412:                                     if (unlink($fname)) {
                   3413:                                         if ($uri!~/\.meta$/) {
                   3414:                                             if (-e $fname.'.meta') {
                   3415:                                                 unlink($fname.'.meta');
                   3416:                                             }
                   3417:                                         }
                   3418:                                         my $unsubresult = &unsubscribe($fname);
                   3419:                                         unless ($unsubresult eq 'ok') {
                   3420:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3421:                                         }
                   3422:                                         $removed = 1;
1.1172.2.98  raeburn  3423:                                     }
                   3424:                                 }
                   3425:                             }
                   3426:                         }
                   3427:                     }
                   3428:                 }
                   3429:             }
                   3430:         }
                   3431:     }
                   3432:     return $removed;
                   3433: }
                   3434: 
1.492     albertel 3435: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3436: 
                   3437: sub allowuploaded {
                   3438:     my ($srcurl,$url)=@_;
                   3439:     $url=&clutter(&declutter($url));
                   3440:     my $dir=$url;
                   3441:     $dir=~s/\/[^\/]+$//;
                   3442:     my %httpref=();
                   3443:     my $httpurl=&hreflocation('',$url);
                   3444:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3445:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3446: }
1.477     raeburn  3447: 
1.1172.2.13  raeburn  3448: #
                   3449: # Determine if the current user should be able to edit a particular resource,
                   3450: # when viewing in course context.
                   3451: # (a) When viewing resource used to determine if "Edit" item is included in
                   3452: #     Functions.
                   3453: # (b) When displaying folder contents in course editor, used to determine if
                   3454: #     "Edit" link will be displayed alongside resource.
                   3455: #
                   3456: #  input: six args -- filename (decluttered), course number, course domain,
                   3457: #                   url, symb (if registered) and group (if this is a group
                   3458: #                   item -- e.g., bulletin board, group page etc.).
                   3459: #  output: array of five scalars --
                   3460: #          $cfile -- url for file editing if editable on current server
                   3461: #          $home -- homeserver of resource (i.e., for author if published,
                   3462: #                                           or course if uploaded.).
                   3463: #          $switchserver --  1 if server switch will be needed.
                   3464: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3465: #          $forceview -- 1 if icon/link should be to go to view mode
                   3466: #
                   3467: 
                   3468: sub can_edit_resource {
                   3469:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3470:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3471: #
                   3472: # For aboutme pages user can only edit his/her own.
                   3473: #
                   3474:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3475:         my ($sdom,$sname) = ($1,$2);
                   3476:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3477:             $home = $env{'user.home'};
                   3478:             $cfile = $resurl;
                   3479:             if ($env{'form.forceedit'}) {
                   3480:                 $forceview = 1;
                   3481:             } else {
                   3482:                 $forceedit = 1;
                   3483:             }
                   3484:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3485:         } else {
                   3486:             return;
                   3487:         }
                   3488:     }
                   3489: 
                   3490:     if ($env{'request.course.id'}) {
                   3491:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3492:         if ($group ne '') {
                   3493: # if this is a group homepage or group bulletin board, check group privs
                   3494:             my $allowed = 0;
                   3495:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3496:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3497:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3498:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3499:                     $allowed = 1;
                   3500:                 }
                   3501:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3502:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3503:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3504:                     $allowed = 1;
                   3505:                 }
                   3506:             }
                   3507:             if ($allowed) {
                   3508:                 $home=&homeserver($cnum,$cdom);
                   3509:                 if ($env{'form.forceedit'}) {
                   3510:                     $forceview = 1;
                   3511:                 } else {
                   3512:                     $forceedit = 1;
                   3513:                 }
                   3514:                 $cfile = $resurl;
                   3515:             } else {
                   3516:                 return;
                   3517:             }
                   3518:         } else {
1.1172.2.15  raeburn  3519:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3520:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3521:                     return;
                   3522:                 }
                   3523:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3524: #
                   3525: # No edit allowed where CC has switched to student role.
                   3526: #
                   3527:                 return;
                   3528:             }
                   3529:         }
                   3530:     }
                   3531: 
                   3532:     if ($file ne '') {
                   3533:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3534:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3535:                 $uploaded = 1;
                   3536:                 $incourse = 1;
                   3537:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3538:                     $cfile = &hreflocation('',$file);
                   3539:                     if ($env{'form.forceedit'}) {
                   3540:                         $forceview = 1;
                   3541:                     } else {
                   3542:                         $forceedit = 1;
                   3543:                     }
                   3544:                 }
                   3545:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3546:                 $incourse = 1;
                   3547:                 if ($env{'form.forceedit'}) {
                   3548:                     $forceview = 1;
                   3549:                 } else {
                   3550:                     $forceedit = 1;
                   3551:                 }
                   3552:                 $cfile = $resurl;
                   3553:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3554:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3555:                     $incourse = 1;
                   3556:                     if ($env{'form.forceedit'}) {
                   3557:                         $forceview = 1;
                   3558:                     } else {
                   3559:                         $forceedit = 1;
                   3560:                     }
                   3561:                     $cfile = $resurl;
                   3562:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3563:                     $incourse = 1;
                   3564:                     $cfile = $resurl.'/smpedit';
                   3565:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3566:                     $incourse = 1;
                   3567:                     if ($env{'form.forceedit'}) {
                   3568:                         $forceview = 1;
                   3569:                     } else {
                   3570:                         $forceedit = 1;
                   3571:                     }
                   3572:                     $cfile = $resurl;
1.1172.2.122  raeburn  3573:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3574:                     my ($map,$id,$res) = &decode_symb($symb);
                   3575:                     if ($map =~ /\.page$/) {
                   3576:                         $incourse = 1;
                   3577:                         if ($env{'form.forceedit'}) {
                   3578:                             $forceview = 1;
                   3579:                             $cfile = $map;
                   3580:                         } else {
                   3581:                             $forceedit = 1;
                   3582:                             $cfile =  '/adm/wrapper'.$resurl;
                   3583:                         }
                   3584:                     }
1.1172.2.146.  .1(raebu 3585:22):                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3586:22):                     $incourse = 1;
                   3587:22):                     if ($env{'form.forceedit'}) {
                   3588:22):                         $forceview = 1;
                   3589:22):                     } else {
                   3590:22):                         $forceedit = 1;
                   3591:22):                     }
                   3592:22):                     $cfile = $resurl;
1.1172.2.15  raeburn  3593:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3594:                     $incourse = 1;
                   3595:                     if ($env{'form.forceedit'}) {
                   3596:                         $forceview = 1;
                   3597:                     } else {
                   3598:                         $forceedit = 1;
                   3599:                     }
                   3600:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3601:                 }
                   3602:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3603:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3604:                 if (&is_on_map($template)) {
                   3605:                     $incourse = 1;
                   3606:                     $forceview = 1;
                   3607:                     $cfile = $template;
                   3608:                 }
                   3609:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118  raeburn  3610:                 $incourse = 1;
                   3611:                 if ($env{'form.forceedit'}) {
                   3612:                     $forceview = 1;
                   3613:                 } else {
                   3614:                     $forceedit = 1;
                   3615:                 }
                   3616:                 $cfile = $resurl;
1.1172.2.146.  .1(raebu 3617:22):             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3618:22):                 $incourse = 1;
                   3619:22):                 if ($env{'form.forceedit'}) {
                   3620:22):                     $forceview = 1;
                   3621:22):                 } else {
                   3622:22):                     $forceedit = 1;
                   3623:22):                 }
                   3624:22):                 $cfile = $resurl;
1.1172.2.13  raeburn  3625:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3626:                 $incourse = 1;
                   3627:                 $forceview = 1;
                   3628:                 if ($symb) {
                   3629:                     my ($map,$id,$res)=&decode_symb($symb);
                   3630:                     $env{'request.symb'} = $symb;
                   3631:                     $cfile = &clutter($res);
                   3632:                 } else {
                   3633:                     $cfile = $env{'form.suppurl'};
1.1172.2.146.  .1(raebu 3634:22):                     my $escfile = &unescape($cfile);
                   3635:22):                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3636:22):                         $cfile = '/adm/wrapper'.$escfile;
                   3637:22):                     } else {
                   3638:22):                         $escfile =~ s{^http://}{};
                   3639:22):                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3640:22):                     }
1.1172.2.13  raeburn  3641:                 }
1.1172.2.31  raeburn  3642:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3643:                 if ($env{'form.forceedit'}) {
                   3644:                     $forceview = 1;
                   3645:                 } else {
                   3646:                     $forceedit = 1;
                   3647:                 }
                   3648:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3649:             }
                   3650:         }
                   3651:         if ($uploaded || $incourse) {
                   3652:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3653:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3654:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3655:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3656:             # Check that the user has permission to edit this resource
                   3657:             my $setpriv = 1;
                   3658:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3659:             if (defined($cfudom)) {
                   3660:                 $home=&homeserver($cfuname,$cfudom);
                   3661:                 $cfile=$file;
                   3662:             }
                   3663:         }
                   3664:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3665:             (($home ne '') && ($home ne 'no_host'))) {
                   3666:             my @ids=&current_machine_ids();
                   3667:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3668:                 $switchserver=1;
                   3669:             }
                   3670:         }
                   3671:     }
                   3672:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3673: }
                   3674: 
                   3675: sub is_course_upload {
                   3676:     my ($file,$cnum,$cdom) = @_;
                   3677:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3678:     $uploadpath =~ s{^\/}{};
                   3679:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3680:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3681:         return 1;
                   3682:     }
                   3683:     return;
                   3684: }
                   3685: 
                   3686: sub in_course {
                   3687:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3688:     if ($hideprivileged) {
                   3689:         my $skipuser;
1.1172.2.23  raeburn  3690:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3691:         my @possdoms = ($cdom);
                   3692:         if ($coursehash{'checkforpriv'}) {
                   3693:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3694:         }
                   3695:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3696:             $skipuser = 1;
                   3697:             if ($coursehash{'nothideprivileged'}) {
                   3698:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3699:                     my $user;
                   3700:                     if ($item =~ /:/) {
                   3701:                         $user = $item;
                   3702:                     } else {
                   3703:                         $user = join(':',split(/[\@]/,$item));
                   3704:                     }
                   3705:                     if ($user eq $uname.':'.$udom) {
                   3706:                         undef($skipuser);
                   3707:                         last;
                   3708:                     }
                   3709:                 }
                   3710:             }
                   3711:             if ($skipuser) {
                   3712:                 return 0;
                   3713:             }
                   3714:         }
                   3715:     }
                   3716:     $type ||= 'any';
                   3717:     if (!defined($cdom) || !defined($cnum)) {
                   3718:         my $cid  = $env{'request.course.id'};
                   3719:         $cdom = $env{'course.'.$cid.'.domain'};
                   3720:         $cnum = $env{'course.'.$cid.'.num'};
                   3721:     }
                   3722:     my $typesref;
                   3723:     if (($type eq 'any') || ($type eq 'all')) {
                   3724:         $typesref = ['active','previous','future'];
                   3725:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3726:         $typesref = [$type];
                   3727:     }
                   3728:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3729:                               $typesref,undef,[$cdom]);
                   3730:     my ($tmp) = keys(%roles);
                   3731:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3732:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3733:     if (@course_roles > 0) {
                   3734:         return 1;
                   3735:     }
                   3736:     return 0;
                   3737: }
                   3738: 
1.478     albertel 3739: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3740: # input: action, courseID, current domain, intended
1.637     raeburn  3741: #        path to file, source of file, instruction to parse file for objects,
                   3742: #        ref to hash for embedded objects,
                   3743: #        ref to hash for codebase of java objects.
1.1095    raeburn  3744: #        reference to scalar to accommodate mime type determined
                   3745: #          from File::MMagic if $parser = parse.
1.637     raeburn  3746: #
1.485     raeburn  3747: # output: url to file (if action was uploaddoc), 
                   3748: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3749: #
1.478     albertel 3750: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3751: # course.
1.477     raeburn  3752: #
1.478     albertel 3753: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3754: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3755: #          course's home server.
1.477     raeburn  3756: #
1.478     albertel 3757: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3758: #          be copied from $source (current location) to 
                   3759: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3760: #         and will then be copied to
                   3761: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3762: #         course's home server.
1.485     raeburn  3763: #
1.481     raeburn  3764: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3765: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3766: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3767: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3768: #         in course's home server.
1.637     raeburn  3769: #
1.477     raeburn  3770: 
                   3771: sub process_coursefile {
1.1095    raeburn  3772:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3773:         $mimetype)=@_;
1.477     raeburn  3774:     my $fetchresult;
1.638     albertel 3775:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3776:     if ($action eq 'propagate') {
1.638     albertel 3777:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3778: 			     $home);
1.481     raeburn  3779:     } else {
1.477     raeburn  3780:         my $fpath = '';
                   3781:         my $fname = $file;
1.478     albertel 3782:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3783:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3784:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3785:         if ($action eq 'copy') {
                   3786:             if ($source eq '') {
                   3787:                 $fetchresult = 'no source file';
                   3788:                 return $fetchresult;
                   3789:             } else {
                   3790:                 my $destination = $filepath.'/'.$fname;
                   3791:                 rename($source,$destination);
                   3792:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3793:                                  $home);
1.481     raeburn  3794:             }
                   3795:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3796:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3797:             print $fh $env{'form.'.$source};
1.481     raeburn  3798:             close($fh);
1.637     raeburn  3799:             if ($parser eq 'parse') {
1.1024    raeburn  3800:                 my $mm = new File::MMagic;
1.1095    raeburn  3801:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3802:                 if ($type eq 'text/html') {
1.1024    raeburn  3803:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3804:                     unless ($parse_result eq 'ok') {
                   3805:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3806:                     }
1.637     raeburn  3807:                 }
1.1095    raeburn  3808:                 if (ref($mimetype)) {
                   3809:                     $$mimetype = $type;
                   3810:                 } 
1.637     raeburn  3811:             }
1.477     raeburn  3812:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3813:                                  $home);
1.481     raeburn  3814:             if ($fetchresult eq 'ok') {
                   3815:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3816:             } else {
                   3817:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3818:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3819:                 return '/adm/notfound.html';
                   3820:             }
1.477     raeburn  3821:         }
                   3822:     }
1.485     raeburn  3823:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3824:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3825:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3826:     }
                   3827:     return $fetchresult;
                   3828: }
                   3829: 
1.637     raeburn  3830: sub build_filepath {
                   3831:     my ($fpath) = @_;
                   3832:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3833:     unless ($fpath eq '') {
                   3834:         my @parts=split('/',$fpath);
                   3835:         foreach my $part (@parts) {
                   3836:             $filepath.= '/'.$part;
                   3837:             if ((-e $filepath)!=1) {
                   3838:                 mkdir($filepath,0777);
                   3839:             }
                   3840:         }
                   3841:     }
                   3842:     return $filepath;
                   3843: }
                   3844: 
                   3845: sub store_edited_file {
1.638     albertel 3846:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3847:     my $file = $primary_url;
                   3848:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3849:     my $fpath = '';
                   3850:     my $fname = $file;
                   3851:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3852:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3853:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3854:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3855:     print $fh $content;
                   3856:     close($fh);
1.638     albertel 3857:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3858:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3859: 			  $home);
1.637     raeburn  3860:     if ($$fetchresult eq 'ok') {
                   3861:         return '/uploaded/'.$fpath.'/'.$fname;
                   3862:     } else {
1.638     albertel 3863:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3864: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3865:         return '/adm/notfound.html';
                   3866:     }
                   3867: }
                   3868: 
1.531     albertel 3869: sub clean_filename {
1.831     albertel 3870:     my ($fname,$args)=@_;
1.315     www      3871: # Replace Windows backslashes by forward slashes
1.257     www      3872:     $fname=~s/\\/\//g;
1.831     albertel 3873:     if (!$args->{'keep_path'}) {
                   3874:         # Get rid of everything but the actual filename
                   3875: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3876:     }
1.315     www      3877: # Replace spaces by underscores
                   3878:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  3879: # Transliterate non-ascii text to ascii
                   3880:     my $lang = &Apache::lonlocal::current_language();
                   3881:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3882: # Replace all other weird characters by nothing
1.831     albertel 3883:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3884: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3885: # numbers
                   3886:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1172.2.140  raeburn  3887: # Replace three or more adjacent underscores with one for consistency
                   3888: # with loncfile::filename_check() so complete url can be extracted by
                   3889: # lonnet::decode_symb()
                   3890:     $fname=~s/_{3,}/_/g;
1.531     albertel 3891:     return $fname;
                   3892: }
1.1172.2.110  raeburn  3893: 
1.1051    raeburn  3894: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3895: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3896: # image with the same aspect ratio as the original, but with dimensions which do 
                   3897: # not exceed $resizewidth and $resizeheight.
                   3898:  
1.984     neumanie 3899: sub resizeImage {
1.1051    raeburn  3900:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3901:     my $ima = Image::Magick->new;
                   3902:     my $resized;
                   3903:     if (-e $img_path) {
                   3904:         $ima->Read($img_path);
                   3905:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3906:             my $width = $ima->Get('width');
                   3907:             my $height = $ima->Get('height');
                   3908:             if ($width > $resizewidth) {
                   3909: 	        my $factor = $width/$resizewidth;
                   3910:                 my $newheight = $height/$factor;
                   3911:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3912:                 $resized = 1;
                   3913:             }
                   3914:         }
                   3915:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3916:             my $width = $ima->Get('width');
                   3917:             my $height = $ima->Get('height');
                   3918:             if ($height > $resizeheight) {
                   3919:                 my $factor = $height/$resizeheight;
                   3920:                 my $newwidth = $width/$factor;
                   3921:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3922:                 $resized = 1;
                   3923:             }
                   3924:         }
                   3925:         if ($resized) {
                   3926:             $ima->Write($img_path);
                   3927:         }
                   3928:     }
                   3929:     return;
1.977     amueller 3930: }
                   3931: 
1.608     albertel 3932: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3933: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3934: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3935: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.109  raeburn  3936: #                                    canceloverwrite, scantron or ''. 
1.1090    raeburn  3937: #                   if 'coursedoc': upload to the current course
                   3938: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3939: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3940: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3941: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  3942: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3943: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3944: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   3945: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  3946: #        $allfiles - reference to hash for embedded objects
                   3947: #        $codebase - reference to hash for codebase of java objects
                   3948: #        $desuname - username for permanent storage of uploaded file
                   3949: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3950: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3951: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3952: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3953: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3954: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3955: #                    from File::MMagic.
1.858     raeburn  3956: # 
1.686     albertel 3957: # output: url of file in userspace, or error: <message> 
                   3958: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3959: 
1.531     albertel 3960: sub userfileupload {
1.1090    raeburn  3961:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3962:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3963:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3964:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3965:     $fname=&clean_filename($fname);
1.1090    raeburn  3966:     # See if there is anything left
1.257     www      3967:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  3968:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   3969:     if ($fname =~ /^\./) {
                   3970:         my ($s,$usec) = &gettimeofday();
                   3971:         while (length($usec) < 6) {
                   3972:             $usec = '0'.$usec;
                   3973:         }
                   3974:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   3975:     }
1.1090    raeburn  3976:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3977:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3978:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3979:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3980:         my $now = time;
1.1090    raeburn  3981:         my $filepath;
1.1095    raeburn  3982:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3983:              $filepath = 'tmp/helprequests/'.$now;
                   3984:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3985:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3986:                          '_'.$env{'user.domain'}.'/pending';
                   3987:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3988:             my ($docuname,$docudom);
1.1172.2.96  raeburn  3989:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3990:                 $docudom = $destudom;
                   3991:             } else {
                   3992:                 $docudom = $env{'user.domain'};
                   3993:             }
1.1172.2.96  raeburn  3994:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  3995:                 $docuname = $destuname;
                   3996:             } else {
                   3997:                 $docuname = $env{'user.name'};
                   3998:             }
                   3999:             if (exists($env{'form.group'})) {
                   4000:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4001:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4002:             }
                   4003:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   4004:             if ($context eq 'canceloverwrite') {
                   4005:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   4006:                 if (-e  $tempfile) {
                   4007:                     my @info = stat($tempfile);
                   4008:                     if ($info[9] eq $env{'form.timestamp'}) {
                   4009:                         unlink($tempfile);
                   4010:                     }
                   4011:                 }
                   4012:                 return;
1.523     raeburn  4013:             }
                   4014:         }
1.1090    raeburn  4015:         # Create the directory if not present
1.741     raeburn  4016:         my @parts=split(/\//,$filepath);
                   4017:         my $fullpath = $perlvar{'lonDaemons'};
                   4018:         for (my $i=0;$i<@parts;$i++) {
                   4019:             $fullpath .= '/'.$parts[$i];
                   4020:             if ((-e $fullpath)!=1) {
                   4021:                 mkdir($fullpath,0777);
                   4022:             }
                   4023:         }
1.1172.2.96  raeburn  4024:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  4025:         print $fh $env{'form.'.$formname};
                   4026:         close($fh);
1.1090    raeburn  4027:         if ($context eq 'existingfile') {
                   4028:             my @info = stat($fullpath.'/'.$fname);
                   4029:             return ($fullpath.'/'.$fname,$info[9]);
                   4030:         } else {
                   4031:             return $fullpath.'/'.$fname;
                   4032:         }
1.523     raeburn  4033:     }
1.995     raeburn  4034:     if ($subdir eq 'scantron') {
                   4035:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  4036:     } else {
1.995     raeburn  4037:         $fname="$subdir/$fname";
                   4038:     }
1.1090    raeburn  4039:     if ($context eq 'coursedoc') {
1.638     albertel 4040: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4041: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  4042:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 4043:             return &finishuserfileupload($docuname,$docudom,
                   4044: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  4045: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  4046:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  4047:         } else {
1.1172.2.21  raeburn  4048:             if ($env{'form.folder'}) {
                   4049:                 $fname=$env{'form.folder'}.'/'.$fname;
                   4050:             }
1.638     albertel 4051:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   4052: 				       $fname,$formname,$parser,
1.1095    raeburn  4053: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  4054:         }
1.719     banghart 4055:     } elsif (defined($destuname)) {
                   4056:         my $docuname=$destuname;
                   4057:         my $docudom=$destudom;
1.860     raeburn  4058: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4059: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4060:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4061:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4062:     } else {
1.638     albertel 4063:         my $docuname=$env{'user.name'};
                   4064:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  4065:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  4066:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4067:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4068:         }
1.860     raeburn  4069: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4070: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4071:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4072:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4073:     }
1.271     www      4074: }
                   4075: 
                   4076: sub finishuserfileupload {
1.860     raeburn  4077:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  4078:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  4079:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      4080:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 4081:   
1.860     raeburn  4082:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 4083:     $file=$fname;
                   4084:     if ($fname=~m|/|) {
                   4085:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   4086: 	$path.=$fnamepath.'/';
                   4087:     }
1.259     www      4088:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      4089:     my $count;
                   4090:     for ($count=4;$count<=$#parts;$count++) {
                   4091:         $filepath.="/$parts[$count]";
                   4092:         if ((-e $filepath)!=1) {
                   4093: 	    mkdir($filepath,0777);
                   4094:         }
                   4095:     }
1.984     neumanie 4096: 
1.258     www      4097: # Save the file
                   4098:     {
1.1172.2.96  raeburn  4099: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4100: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4101: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4102: 	    return '/adm/notfound.html';
                   4103: 	}
1.1090    raeburn  4104:         if ($context eq 'overwrite') {
1.1117    foxr     4105:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4106:             my $target = $filepath.'/'.$file;
                   4107:             if (-e $source) {
                   4108:                 my @info = stat($source);
                   4109:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4110:                     unless (&File::Copy::move($source,$target)) {
                   4111:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4112:                         return "Moving from $source failed";
                   4113:                     }
                   4114:                 } else {
                   4115:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4116:                 }
                   4117:             } else {
                   4118:                 return "Temporary file: $source missing";
                   4119:             }
                   4120:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4121: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4122: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4123: 	    return '/adm/notfound.html';
                   4124: 	}
1.570     albertel 4125: 	close(FH);
1.1051    raeburn  4126:         if ($resizewidth && $resizeheight) {
                   4127:             my $mm = new File::MMagic;
                   4128:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4129:             if ($mime_type =~ m{^image/}) {
                   4130: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4131:             }  
1.977     amueller 4132: 	}
1.258     www      4133:     }
1.1152    raeburn  4134:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4135:         if (ref($mimetype)) {
                   4136:             if ($$mimetype eq '') {
                   4137:                 my $mm = new File::MMagic;
                   4138:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4139:                 $$mimetype = $type;
                   4140:             }
                   4141:         }
                   4142:     }
1.1172.2.109  raeburn  4143:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4144:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4145:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4146:                                                        $allfiles,$codebase);
                   4147:             unless ($parse_result eq 'ok') {
                   4148:                 &logthis('Failed to parse '.$filepath.$file.
                   4149: 	   	         ' for embedded media: '.$parse_result); 
                   4150:             }
1.637     raeburn  4151:         }
1.1172.2.109  raeburn  4152:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4153:         my $format = $env{'form.scantron_format'};
                   4154:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4155:     }
1.860     raeburn  4156:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4157:         my $input = $filepath.'/'.$file;
                   4158:         my $output = $filepath.'/'.'tn-'.$file;
                   4159:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  4160:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4161:         system({$args[0]} @args);
1.860     raeburn  4162:         if (-e $filepath.'/'.'tn-'.$file) {
                   4163:             $fetchthumb  = 1; 
                   4164:         }
                   4165:     }
1.858     raeburn  4166:  
1.259     www      4167: # Notify homeserver to grep it
                   4168: #
1.984     neumanie 4169:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4170:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4171:     if ($fetchresult eq 'ok') {
1.860     raeburn  4172:         if ($fetchthumb) {
                   4173:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4174:             if ($thumbresult ne 'ok') {
                   4175:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4176:                          $docuhome.': '.$thumbresult);
                   4177:             }
                   4178:         }
1.259     www      4179: #
1.258     www      4180: # Return the URL to it
1.494     albertel 4181:         return '/uploaded/'.$path.$file;
1.263     www      4182:     } else {
1.494     albertel 4183:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4184: 		 ': '.$fetchresult);
1.263     www      4185:         return '/adm/notfound.html';
1.858     raeburn  4186:     }
1.493     albertel 4187: }
                   4188: 
1.637     raeburn  4189: sub extract_embedded_items {
1.961     raeburn  4190:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4191:     my @state = ();
1.1164    raeburn  4192:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4193:     my %javafiles = (
                   4194:                       codebase => '',
                   4195:                       code => '',
                   4196:                       archive => ''
                   4197:                     );
                   4198:     my %mediafiles = (
                   4199:                       src => '',
                   4200:                       movie => '',
                   4201:                      );
1.648     raeburn  4202:     my $p;
                   4203:     if ($content) {
                   4204:         $p = HTML::LCParser->new($content);
                   4205:     } else {
1.961     raeburn  4206:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4207:     }
1.641     albertel 4208:     while (my $t=$p->get_token()) {
1.640     albertel 4209: 	if ($t->[0] eq 'S') {
                   4210: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4211: 	    push(@state, $tagname);
1.648     raeburn  4212:             if (lc($tagname) eq 'allow') {
                   4213:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4214:             }
1.640     albertel 4215: 	    if (lc($tagname) eq 'img') {
                   4216: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4217: 	    }
1.886     albertel 4218: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  4219:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   4220: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   4221:                 }
1.886     albertel 4222: 	    }
1.645     raeburn  4223:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4224:                 my $src;
1.645     raeburn  4225:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4226:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4227:                 } else {
1.1164    raeburn  4228:                     if ($attr->{'src'} ne '') {
                   4229:                         $src = $attr->{'src'};
                   4230:                         &add_filetype($allfiles,$src,'src');
                   4231:                     }
                   4232:                 }
                   4233:                 my $text = $p->get_trimmed_text();
                   4234:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4235:                     my @swfargs = split(/,/,$1);
                   4236:                     foreach my $item (@swfargs) {
                   4237:                         $item =~ s/["']//g;
                   4238:                         $item =~ s/^\s+//;
                   4239:                         $item =~ s/\s+$//;
                   4240:                     }
                   4241:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4242:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4243:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4244:                         } else {
                   4245:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4246:                         }
                   4247:                     }
1.645     raeburn  4248:                 }
                   4249:             }
                   4250:             if (lc($tagname) eq 'link') {
                   4251:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4252:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4253:                 }
                   4254:             }
1.640     albertel 4255: 	    if (lc($tagname) eq 'object' ||
                   4256: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4257: 		foreach my $item (keys(%javafiles)) {
                   4258: 		    $javafiles{$item} = '';
                   4259: 		}
1.1164    raeburn  4260:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4261:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4262:                 }
1.640     albertel 4263: 	    }
                   4264: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4265: 		my $name = lc($attr->{'name'});
                   4266: 		foreach my $item (keys(%javafiles)) {
                   4267: 		    if ($name eq $item) {
                   4268: 			$javafiles{$item} = $attr->{'value'};
                   4269: 			last;
                   4270: 		    }
                   4271: 		}
1.1164    raeburn  4272:                 my $pathfrom;
1.640     albertel 4273: 		foreach my $item (keys(%mediafiles)) {
                   4274: 		    if ($name eq $item) {
1.1164    raeburn  4275:                         $pathfrom = $attr->{'value'};
                   4276:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4277: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4278: 			last;
                   4279: 		    }
                   4280: 		}
1.1164    raeburn  4281:                 if ($name eq 'flashvars') {
                   4282:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4283:                 }
                   4284:                 if ($pathfrom ne '') {
                   4285:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4286:                                          $pathfrom);
                   4287:                 }
1.640     albertel 4288: 	    }
                   4289: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4290: 		foreach my $item (keys(%javafiles)) {
                   4291: 		    if ($attr->{$item}) {
                   4292: 			$javafiles{$item} = $attr->{$item};
                   4293: 			last;
                   4294: 		    }
                   4295: 		}
                   4296: 		foreach my $item (keys(%mediafiles)) {
                   4297: 		    if ($attr->{$item}) {
                   4298: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4299: 			last;
                   4300: 		    }
                   4301: 		}
1.1164    raeburn  4302:                 if (lc($tagname) eq 'embed') {
                   4303:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4304:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4305:                                              $attr->{'src'});
                   4306:                     }
                   4307:                 }
1.640     albertel 4308: 	    }
1.1172.2.35  raeburn  4309:             if (lc($tagname) eq 'iframe') {
                   4310:                 my $src = $attr->{'src'} ;
                   4311:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4312:                     &add_filetype($allfiles,$src,'src');
                   4313:                 } elsif ($src =~ m{^/}) {
                   4314:                     if ($env{'request.course.id'}) {
                   4315:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4316:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4317:                         my $url = &hreflocation('',$fullpath);
                   4318:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4319:                             my $relpath = $1;
                   4320:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4321:                                 &add_filetype($allfiles,$1,'src');
                   4322:                             }
                   4323:                         }
                   4324:                     }
                   4325:                 }
                   4326:             }
1.1164    raeburn  4327:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4328:                 pop(@state);
1.1164    raeburn  4329:             }
1.640     albertel 4330: 	} elsif ($t->[0] eq 'E') {
                   4331: 	    my ($tagname) = ($t->[1]);
                   4332: 	    if ($javafiles{'codebase'} ne '') {
                   4333: 		$javafiles{'codebase'} .= '/';
                   4334: 	    }  
                   4335: 	    if (lc($tagname) eq 'applet' ||
                   4336: 		lc($tagname) eq 'object' ||
                   4337: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4338: 		) {
                   4339: 		foreach my $item (keys(%javafiles)) {
                   4340: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4341: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4342: 			&add_filetype($allfiles,$file,$item);
                   4343: 		    }
                   4344: 		}
                   4345: 	    } 
                   4346: 	    pop @state;
                   4347: 	}
                   4348:     }
1.1164    raeburn  4349:     foreach my $id (sort(keys(%flashvars))) {
                   4350:         if ($shockwave{$id} ne '') {
                   4351:             my @pairs = split(/\&/,$flashvars{$id});
                   4352:             foreach my $pair (@pairs) {
                   4353:                 my ($key,$value) = split(/\=/,$pair);
                   4354:                 if ($key eq 'thumb') {
                   4355:                     &add_filetype($allfiles,$value,$key);
                   4356:                 } elsif ($key eq 'content') {
                   4357:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4358:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4359:                     if ($ext ne '') {
                   4360:                         &add_filetype($allfiles,$path.$value,$ext);
                   4361:                     }
                   4362:                 }
                   4363:             }
                   4364:         }
                   4365:     }
1.637     raeburn  4366:     return 'ok';
                   4367: }
                   4368: 
1.639     albertel 4369: sub add_filetype {
                   4370:     my ($allfiles,$file,$type)=@_;
                   4371:     if (exists($allfiles->{$file})) {
                   4372: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4373: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4374: 	}
                   4375:     } else {
                   4376: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4377:     }
                   4378: }
                   4379: 
1.1164    raeburn  4380: sub embedded_dependency {
                   4381:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4382:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4383:         if (($identifier ne '') &&
                   4384:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4385:             ($pathfrom ne '')) {
                   4386:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4387:             foreach my $dep (@{$related->{$identifier}}) {
                   4388:                 &add_filetype($allfiles,$path.$dep,'object');
                   4389:             }
                   4390:         }
                   4391:     }
                   4392:     return;
                   4393: }
                   4394: 
1.1172.2.109  raeburn  4395: sub bubblesheet_converter {
                   4396:     my ($cdom,$fullpath,$config,$format) = @_;
                   4397:     if ((&domain($cdom) ne '') &&
                   4398:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4399:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4400:         my (%csvcols,%csvoptions);
                   4401:         if (ref($config->{'fields'}) eq 'HASH') {
                   4402:             %csvcols = %{$config->{'fields'}};
                   4403:         }
                   4404:         if (ref($config->{'options'}) eq 'HASH') {
                   4405:             %csvoptions = %{$config->{'options'}};
                   4406:         }
                   4407:         my %csvbynum = reverse(%csvcols);
                   4408:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4409:         if (keys(%scantronconf)) {
                   4410:             my %bynum = (
                   4411:                           $scantronconf{CODEstart} => 'CODEstart',
                   4412:                           $scantronconf{IDstart}   => 'IDstart',
                   4413:                           $scantronconf{PaperID}   => 'PaperID',
                   4414:                           $scantronconf{FirstName} => 'FirstName',
                   4415:                           $scantronconf{LastName}  => 'LastName',
                   4416:                           $scantronconf{Qstart}    => 'Qstart',
                   4417:                         );
                   4418:             my @ordered;
                   4419:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4420:                 push(@ordered,$bynum{$item});
                   4421:             }
                   4422:             my %mapstart = (
                   4423:                               CODEstart => 'CODE',
                   4424:                               IDstart   => 'ID',
                   4425:                               PaperID   => 'PaperID',
                   4426:                               FirstName => 'FirstName',
                   4427:                               LastName  => 'LastName',
                   4428:                               Qstart    => 'FirstQuestion',
                   4429:                            );
                   4430:             my %maplength = (
                   4431:                               CODEstart => 'CODElength',
                   4432:                               IDstart   => 'IDlength',
                   4433:                               PaperID   => 'PaperIDlength',
                   4434:                               FirstName => 'FirstNamelength',
                   4435:                               LastName  => 'LastNamelength',
                   4436:             );
                   4437:             if (open(my $fh,'<',$fullpath)) {
                   4438:                 my $output;
                   4439:                 my %lettdig = &letter_to_digits();
                   4440:                 my %diglett = reverse(%lettdig);
                   4441:                 my $numletts = scalar(keys(%lettdig));
                   4442:                 my $num = 0;
                   4443:                 while (my $line=<$fh>) {
                   4444:                     $num ++;
                   4445:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4446:                     $line =~ s{[\r\n]+$}{};
                   4447:                     my %found;
1.1172.2.143  raeburn  4448:                     my @values = split(/,/,$line,-1);
1.1172.2.109  raeburn  4449:                     my ($qstart,$record);
                   4450:                     for (my $i=0; $i<@values; $i++) {
                   4451:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4452:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4453:                             if ($values[$i] eq '') {
                   4454:                                 $values[$i] = $scantronconf{'Qoff'};
                   4455:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4456:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4457:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4458:                                 }
                   4459:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4460:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4461:                                     $values[$i] = $diglett{$values[$i]};
                   4462:                                 }
                   4463:                             } else {
                   4464:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4465:                                     my $digit;
                   4466:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4467:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4468:                                         if ($values[$i] eq 'J') {
                   4469:                                             $digit += $numletts;
                   4470:                                         }
                   4471:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4472:                                         $digit = $values[$i]-1;
                   4473:                                         if ($values[$i] eq '0') {
                   4474:                                             $digit += $numletts;
                   4475:                                         }
                   4476:                                     }
                   4477:                                     my $qval='';
                   4478:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4479:                                         if ($j == $digit) {
                   4480:                                             $qval .= $scantronconf{'Qon'};
                   4481:                                         } else {
                   4482:                                             $qval .= $scantronconf{'Qoff'};
                   4483:                                         }
                   4484:                                     }
                   4485:                                     $values[$i] = $qval;
                   4486:                                 }
                   4487:                             }
                   4488:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4489:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4490:                             }
                   4491:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4492:                             if ($numblank > 0) {
                   4493:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4494:                             }
                   4495:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4496:                                 $qstart = $i;
                   4497:                                 $found{$csvbynum{$i}} = $values[$i];
                   4498:                             } else {
                   4499:                                 $found{'FirstQuestion'} .= $values[$i];
                   4500:                             }
                   4501:                         } elsif (exists($csvbynum{$i})) {
                   4502:                             if ($csvoptions{'rem'}) {
                   4503:                                 $values[$i] =~ s/^\s+//;
                   4504:                             }
                   4505:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4506:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4507:                                     $values[$i] = '0'.$values[$i];
                   4508:                                 }
                   4509:                             }
                   4510:                             $found{$csvbynum{$i}} = $values[$i];
                   4511:                         }
                   4512:                     }
                   4513:                     foreach my $item (@ordered) {
                   4514:                         my $currlength = 1+length($record);
                   4515:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4516:                         if ($numspaces > 0) {
                   4517:                             $record .= (' ' x $numspaces);
                   4518:                         }
                   4519:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4520:                             unless ($item eq 'Qstart') {
                   4521:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4522:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4523:                                 }
                   4524:                             }
                   4525:                             $record .= $found{$mapstart{$item}};
                   4526:                         }
                   4527:                     }
                   4528:                     $output .= "$record\n";
                   4529:                 }
                   4530:                 close($fh);
                   4531:                 if ($output) {
                   4532:                     if (open(my $fh,'>',$fullpath)) {
                   4533:                         print $fh $output;
                   4534:                         close($fh);
                   4535:                     }
                   4536:                 }
                   4537:             }
                   4538:         }
                   4539:         return;
                   4540:     }
                   4541: }
                   4542: 
                   4543: sub letter_to_digits {
                   4544:     my %lettdig = (
                   4545:                     A => 1,
                   4546:                     B => 2,
                   4547:                     C => 3,
                   4548:                     D => 4,
                   4549:                     E => 5,
                   4550:                     F => 6,
                   4551:                     G => 7,
                   4552:                     H => 8,
                   4553:                     I => 9,
                   4554:                     J => 0,
                   4555:                   );
                   4556:     return %lettdig;
                   4557: }
                   4558: 
                   4559: sub get_scantron_config {
                   4560:     my ($which,$cdom) = @_;
                   4561:     my @lines = &get_scantronformat_file($cdom);
                   4562:     my %config;
                   4563:     #FIXME probably should move to XML it has already gotten a bit much now
                   4564:     foreach my $line (@lines) {
                   4565:         my ($name,$descrip)=split(/:/,$line);
                   4566:         if ($name ne $which ) { next; }
                   4567:         chomp($line);
                   4568:         my @config=split(/:/,$line);
                   4569:         $config{'name'}=$config[0];
                   4570:         $config{'description'}=$config[1];
                   4571:         $config{'CODElocation'}=$config[2];
                   4572:         $config{'CODEstart'}=$config[3];
                   4573:         $config{'CODElength'}=$config[4];
                   4574:         $config{'IDstart'}=$config[5];
                   4575:         $config{'IDlength'}=$config[6];
                   4576:         $config{'Qstart'}=$config[7];
                   4577:         $config{'Qlength'}=$config[8];
                   4578:         $config{'Qoff'}=$config[9];
                   4579:         $config{'Qon'}=$config[10];
                   4580:         $config{'PaperID'}=$config[11];
                   4581:         $config{'PaperIDlength'}=$config[12];
                   4582:         $config{'FirstName'}=$config[13];
                   4583:         $config{'FirstNamelength'}=$config[14];
                   4584:         $config{'LastName'}=$config[15];
                   4585:         $config{'LastNamelength'}=$config[16];
                   4586:         $config{'BubblesPerRow'}=$config[17];
                   4587:         last;
                   4588:     }
                   4589:     return %config;
                   4590: }
                   4591: 
                   4592: sub get_scantronformat_file {
                   4593:     my ($cdom) = @_;
                   4594:     if ($cdom eq '') {
                   4595:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4596:     }
                   4597:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4598:     my $gottab = 0;
                   4599:     my @lines;
                   4600:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4601:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4602:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4603:             if ($formatfile ne '-1') {
                   4604:                 @lines = split("\n",$formatfile,-1);
                   4605:                 $gottab = 1;
                   4606:             }
                   4607:         }
                   4608:     }
                   4609:     if (!$gottab) {
                   4610:         my $confname = $cdom.'-domainconfig';
                   4611:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4612:         my $formatfile = &getfile($default);
                   4613:         if ($formatfile ne '-1') {
                   4614:             @lines = split("\n",$formatfile,-1);
                   4615:             $gottab = 1;
                   4616:         }
                   4617:     }
                   4618:     if (!$gottab) {
                   4619:         my @domains = &current_machine_domains();
                   4620:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4621:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4622:                 @lines = <$fh>;
                   4623:                 close($fh);
                   4624:             }
                   4625:         } else {
                   4626:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4627:                 @lines = <$fh>;
                   4628:                 close($fh);
                   4629:             }
                   4630:         }
                   4631:     }
                   4632:     return @lines;
                   4633: }
                   4634: 
1.493     albertel 4635: sub removeuploadedurl {
1.984     neumanie 4636:     my ($url)=@_;	
                   4637:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4638:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4639: }
                   4640: 
                   4641: sub removeuserfile {
                   4642:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4643:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4644:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4645:     if ($result eq 'ok') {	
1.798     raeburn  4646:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4647:             my $metafile = $fname.'.meta';
                   4648:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4649: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4650:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4651:             my $sqlresult = 
1.823     albertel 4652:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4653:                                         'portfolio_metadata',$group,
                   4654:                                         'delete');
1.798     raeburn  4655:         }
                   4656:     }
                   4657:     return $result;
1.257     www      4658: }
1.15      www      4659: 
1.530     albertel 4660: sub mkdiruserfile {
                   4661:     my ($docuname,$docudom,$dir)=@_;
                   4662:     my $home=&homeserver($docuname,$docudom);
                   4663:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4664: }
                   4665: 
1.531     albertel 4666: sub renameuserfile {
                   4667:     my ($docuname,$docudom,$old,$new)=@_;
                   4668:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4669:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4670:                         &escape("$old").':'.&escape("$new"),$home);
                   4671:     if ($result eq 'ok') {
                   4672:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4673:             my $oldmeta = $old.'.meta';
                   4674:             my $newmeta = $new.'.meta';
                   4675:             my $metaresult = 
                   4676:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4677: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4678:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4679:             my $sqlresult = 
1.823     albertel 4680:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4681:                                         'portfolio_metadata',$group,
                   4682:                                         'delete');
1.798     raeburn  4683:         }
                   4684:     }
                   4685:     return $result;
1.531     albertel 4686: }
                   4687: 
1.14      www      4688: # ------------------------------------------------------------------------- Log
                   4689: 
                   4690: sub log {
                   4691:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4692:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4693: }
                   4694: 
                   4695: # ------------------------------------------------------------------ Course Log
1.352     www      4696: #
                   4697: # This routine flushes several buffers of non-mission-critical nature
                   4698: #
1.157     www      4699: 
                   4700: sub flushcourselogs {
1.352     www      4701:     &logthis('Flushing log buffers');
                   4702: #
                   4703: # course logs
                   4704: # This is a log of all transactions in a course, which can be used
                   4705: # for data mining purposes
                   4706: #
                   4707: # It also collects the courseid database, which lists last transaction
                   4708: # times and course titles for all courseids
                   4709: #
                   4710:     my %courseidbuffer=();
1.921     raeburn  4711:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4712:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4713: 		          &escape($courselogs{$crsid}),
                   4714: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4715: 	    delete $courselogs{$crsid};
                   4716:         } else {
                   4717:             &logthis('Failed to flush log buffer for '.$crsid);
                   4718:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4719:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4720:                         " exceeded maximum size, deleting.</font>");
                   4721:                delete $courselogs{$crsid};
                   4722:             }
1.352     www      4723:         }
1.920     raeburn  4724:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4725:             'description' => $coursedescrbuf{$crsid},
                   4726:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4727:             'type'        => $coursetypebuf{$crsid},
                   4728:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4729:         };
1.191     harris41 4730:     }
1.352     www      4731: #
                   4732: # Write course id database (reverse lookup) to homeserver of courses 
                   4733: # Is used in pickcourse
                   4734: #
1.840     albertel 4735:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4736:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4737:                                     $courseidbuffer{$crs_home},
                   4738:                                     $crs_home,'timeonly');
1.352     www      4739:     }
                   4740: #
                   4741: # File accesses
                   4742: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4743: #
1.449     matthew  4744:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4745:         if ($entry =~ /___count$/) {
                   4746:             my ($dom,$name);
1.807     albertel 4747:             ($dom,$name,undef)=
1.811     albertel 4748: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4749:             if (! defined($dom) || $dom eq '' || 
                   4750:                 ! defined($name) || $name eq '') {
1.620     albertel 4751:                 my $cid = $env{'request.course.id'};
1.1172.2.142  raeburn  4752: #
                   4753: # FIXME 11/29/2021
                   4754: # Typo in rev. 1.458 (2003/12/09)??
                   4755: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
                   4756: #
                   4757: # While these ramain as  $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
                   4758: # $dom and $name will always be null, so the &inc() call will default to storing this data
                   4759: # in a nohist_accesscount.db file for the user rather than the course.
                   4760: #
                   4761: # That said there is a lot of noise in the data being stored.
                   4762: # So counts for prtspool/  and adm/ etc. are recorded.
                   4763: #
                   4764: # A review of which items ending '___count' are written to %accesshash should likely be
                   4765: # made before deciding whether to set these to 'course.' instead of 'request.'
                   4766: #
                   4767: # Under the current scheme each user receives a nohist_accesscount.db file listing
                   4768: # accesses for things which are not published resources, regardless of course, and
                   4769: # there is not a nohist_accesscount.db file in a course, which might log accesses from
                   4770: # anyone in the course for things which are not published resources.
                   4771: #
                   4772: # For an author, nohist_accesscount.db ends up having records for other items
                   4773: # mixed up with the legitimate access counts for the author's published resources.
                   4774: #
1.620     albertel 4775:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4776:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4777:             }
1.450     matthew  4778:             my $value = $accesshash{$entry};
                   4779:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4780:             my %temphash=($url => $value);
1.449     matthew  4781:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4782:             if ($result eq 'ok') {
                   4783:                 delete $accesshash{$entry};
                   4784:             }
                   4785:         } else {
1.811     albertel 4786:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4787:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4788:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4789:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4790:                 delete $accesshash{$entry};
                   4791:             }
1.185     www      4792:         }
1.191     harris41 4793:     }
1.352     www      4794: #
                   4795: # Roles
                   4796: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4797: #
1.800     albertel 4798:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4799:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4800: 	    split(/\:/,$entry);
                   4801:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4802:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4803:                 $rudom,$runame) eq 'ok') {
                   4804: 	    delete $userrolehash{$entry};
                   4805:         }
                   4806:     }
1.662     raeburn  4807: #
1.1172.2.90  raeburn  4808: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4809: #
                   4810:     my %domrolebuffer = ();
1.1000    raeburn  4811:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4812:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4813:         if ($domrolebuffer{$rudom}) {
                   4814:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4815:                       '='.&escape($domainrolehash{$entry});
                   4816:         } else {
                   4817:             $domrolebuffer{$rudom}.=&escape($entry).
                   4818:                       '='.&escape($domainrolehash{$entry});
                   4819:         }
                   4820:         delete $domainrolehash{$entry};
                   4821:     }
                   4822:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4823:         my %servers;
                   4824:         if (defined(&domain($dom,'primary'))) {
                   4825:             my $primary=&domain($dom,'primary');
                   4826:             my $hostname=&hostname($primary);
                   4827:             $servers{$primary} = $hostname;
                   4828:         } else {
                   4829:             %servers = &get_servers($dom,'library');
                   4830:         }
1.841     albertel 4831: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4832: 	    if (&reply('domroleput:'.$dom.':'.
                   4833: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4834: 	        last;
                   4835: 	    } else {
1.841     albertel 4836: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4837: 	    }
1.662     raeburn  4838:         }
                   4839:     }
1.186     www      4840:     $dumpcount++;
1.157     www      4841: }
                   4842: 
                   4843: sub courselog {
                   4844:     my $what=shift;
1.158     www      4845:     $what=time.':'.$what;
1.620     albertel 4846:     unless ($env{'request.course.id'}) { return ''; }
                   4847:     $coursedombuf{$env{'request.course.id'}}=
                   4848:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4849:     $coursenumbuf{$env{'request.course.id'}}=
                   4850:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4851:     $coursehombuf{$env{'request.course.id'}}=
                   4852:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4853:     $coursedescrbuf{$env{'request.course.id'}}=
                   4854:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4855:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4856:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4857:     $courseownerbuf{$env{'request.course.id'}}=
                   4858:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4859:     $coursetypebuf{$env{'request.course.id'}}=
                   4860:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4861:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4862: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4863:     } else {
1.620     albertel 4864: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4865:     }
1.620     albertel 4866:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4867: 	&flushcourselogs();
                   4868:     }
1.158     www      4869: }
                   4870: 
                   4871: sub courseacclog {
                   4872:     my $fnsymb=shift;
1.620     albertel 4873:     unless ($env{'request.course.id'}) { return ''; }
                   4874:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4875:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4876:         $what.=':POST';
1.583     matthew  4877:         # FIXME: Probably ought to escape things....
1.800     albertel 4878: 	foreach my $key (keys(%env)) {
                   4879:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4880:                 my $formitem = $1;
                   4881:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4882:                     $what.=':'.$formitem.'='.$env{$key};
                   4883:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.131  raeburn  4884:                     if ($formitem eq 'proctorpassword') {
1.1172.2.132  raeburn  4885:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1172.2.131  raeburn  4886:                     } else {
                   4887:                         $what.=':'.$formitem.'='.$env{$key};
                   4888:                     }
1.975     raeburn  4889:                 }
1.158     www      4890:             }
1.191     harris41 4891:         }
1.583     matthew  4892:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4893:         # FIXME: We should not be depending on a form parameter that someone
                   4894:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4895:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4896:             $what.= ':POST';
                   4897:             # FIXME: Probably ought to escape things....
                   4898:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4899:                                  'crsdiscuss') {
1.620     albertel 4900:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4901:             }
                   4902:         }
1.158     www      4903:     }
                   4904:     &courselog($what);
1.149     www      4905: }
                   4906: 
1.185     www      4907: sub countacc {
                   4908:     my $url=&declutter(shift);
1.458     matthew  4909:     return if (! defined($url) || $url eq '');
1.620     albertel 4910:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4911: #
                   4912: # Mark that this url was used in this course
                   4913: #
1.620     albertel 4914:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4915: #
                   4916: # Increase the access count for this resource in this child process
                   4917: #
1.281     www      4918:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4919:     $accesshash{$key}++;
1.185     www      4920: }
1.349     www      4921: 
1.361     www      4922: sub linklog {
                   4923:     my ($from,$to)=@_;
                   4924:     $from=&declutter($from);
                   4925:     $to=&declutter($to);
                   4926:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4927:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4928: }
1.1160    www      4929: 
                   4930: sub statslog {
                   4931:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4932:     if ($users<2) { return; }
                   4933:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4934:             'course'       => $env{'request.course.id'},
                   4935:             'sections'     => '"all"',
                   4936:             'num_students' => $users,
                   4937:             'part'         => $part,
                   4938:             'symb'         => $symb,
                   4939:             'mean_tries'   => $av_attempts,
                   4940:             'deg_of_diff'  => $degdiff});
                   4941:     foreach my $key (keys(%dynstore)) {
                   4942:         $accesshash{$key}=$dynstore{$key};
                   4943:     }
                   4944: }
1.361     www      4945:   
1.349     www      4946: sub userrolelog {
                   4947:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4948:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4949:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4950:        $userrolehash
                   4951:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4952:                     =$tend.':'.$tstart;
1.662     raeburn  4953:     }
1.1169    droeschl 4954:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4955:        $userrolehash
                   4956:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4957:                     =$tend.':'.$tstart;
                   4958:     }
1.1172.2.90  raeburn  4959:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4960:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4961:        $domainrolehash
                   4962:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4963:                     = $tend.':'.$tstart;
                   4964:     }
1.351     www      4965: }
                   4966: 
1.957     raeburn  4967: sub courserolelog {
                   4968:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  4969:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4970:         my $cdom = $1;
                   4971:         my $cnum = $2;
                   4972:         my $sec = $3;
                   4973:         my $namespace = 'rolelog';
                   4974:         my %storehash = (
                   4975:                            role    => $trole,
                   4976:                            start   => $tstart,
                   4977:                            end     => $tend,
                   4978:                            selfenroll => $selfenroll,
                   4979:                            context    => $context,
                   4980:                         );
                   4981:         if ($trole eq 'gr') {
                   4982:             $namespace = 'groupslog';
                   4983:             $storehash{'group'} = $sec;
                   4984:         } else {
                   4985:             $storehash{'section'} = $sec;
                   4986:         }
                   4987:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4988:                    $domain,$cnum,$cdom);
                   4989:         if (($trole ne 'st') || ($sec ne '')) {
                   4990:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4991:         }
                   4992:     }
                   4993:     return;
                   4994: }
                   4995: 
1.1172.2.9  raeburn  4996: sub domainrolelog {
                   4997:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4998:     if ($area =~ m{^/($match_domain)/$}) {
                   4999:         my $cdom = $1;
                   5000:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   5001:         my $namespace = 'rolelog';
                   5002:         my %storehash = (
                   5003:                            role    => $trole,
                   5004:                            start   => $tstart,
                   5005:                            end     => $tend,
                   5006:                            context => $context,
                   5007:                         );
                   5008:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   5009:                    $domain,$domconfiguser,$cdom);
                   5010:     }
                   5011:     return;
                   5012: 
                   5013: }
                   5014: 
                   5015: sub coauthorrolelog {
                   5016:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5017:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   5018:         my $audom = $1;
                   5019:         my $auname = $2;
                   5020:         my $namespace = 'rolelog';
                   5021:         my %storehash = (
                   5022:                            role    => $trole,
                   5023:                            start   => $tstart,
                   5024:                            end     => $tend,
                   5025:                            context => $context,
                   5026:                         );
                   5027:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   5028:                    $domain,$auname,$audom);
                   5029:     }
                   5030:     return;
                   5031: }
                   5032: 
1.351     www      5033: sub get_course_adv_roles {
1.948     raeburn  5034:     my ($cid,$codes) = @_;
1.620     albertel 5035:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      5036:     my %coursehash=&coursedescription($cid);
1.988     raeburn  5037:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      5038:     my %nothide=();
1.800     albertel 5039:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  5040:         if ($user !~ /:/) {
                   5041: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   5042:         } else {
                   5043:             $nothide{$user}=1;
                   5044:         }
1.470     www      5045:     }
1.1172.2.23  raeburn  5046:     my @possdoms = ($coursehash{'domain'});
                   5047:     if ($coursehash{'checkforpriv'}) {
                   5048:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   5049:     }
1.351     www      5050:     my %returnhash=();
                   5051:     my %dumphash=
                   5052:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   5053:     my $now=time;
1.997     raeburn  5054:     my %privileged;
1.1000    raeburn  5055:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 5056: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      5057:         if (($tstart) && ($tstart<0)) { next; }
                   5058:         if (($tend) && ($tend<$now)) { next; }
                   5059:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 5060:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 5061: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  5062:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  5063:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 5064: 	if ($role eq 'cr') { next; }
1.948     raeburn  5065:         if ($codes) {
                   5066:             if ($section) { $role .= ':'.$section; }
                   5067:             if ($returnhash{$role}) {
                   5068:                 $returnhash{$role}.=','.$username.':'.$domain;
                   5069:             } else {
                   5070:                 $returnhash{$role}=$username.':'.$domain;
                   5071:             }
1.351     www      5072:         } else {
1.988     raeburn  5073:             my $key=&plaintext($role,$crstype);
1.973     bisitz   5074:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  5075:             if ($returnhash{$key}) {
                   5076: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   5077:             } else {
                   5078:                 $returnhash{$key}=$username.':'.$domain;
                   5079:             }
1.351     www      5080:         }
1.948     raeburn  5081:     }
1.400     www      5082:     return %returnhash;
                   5083: }
                   5084: 
                   5085: sub get_my_roles {
1.937     raeburn  5086:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 5087:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   5088:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  5089:     my (%dumphash,%nothide);
1.1086    raeburn  5090:     if ($context eq 'userroles') {
1.1166    raeburn  5091:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  5092:     } else {
1.1172.2.23  raeburn  5093:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  5094:         if ($hidepriv) {
                   5095:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   5096:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   5097:                 if ($user !~ /:/) {
                   5098:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   5099:                 } else {
                   5100:                     $nothide{$user} = 1;
                   5101:                 }
                   5102:             }
                   5103:         }
1.858     raeburn  5104:     }
1.400     www      5105:     my %returnhash=();
                   5106:     my $now=time;
1.999     raeburn  5107:     my %privileged;
1.800     albertel 5108:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  5109:         my ($role,$tend,$tstart);
                   5110:         if ($context eq 'userroles') {
1.1149    raeburn  5111:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  5112: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   5113:         } else {
                   5114:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   5115:         }
1.400     www      5116:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  5117:         my $status = 'active';
1.939     raeburn  5118:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  5119:             $status = 'previous';
                   5120:         } 
                   5121:         if (($tstart) && ($now<$tstart)) {
                   5122:             $status = 'future';
                   5123:         }
                   5124:         if (ref($types) eq 'ARRAY') {
                   5125:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   5126:                 next;
                   5127:             } 
                   5128:         } else {
                   5129:             if ($status ne 'active') {
                   5130:                 next;
                   5131:             }
                   5132:         }
1.867     raeburn  5133:         my ($rolecode,$username,$domain,$section,$area);
                   5134:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  5135:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5136:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5137:         } else {
                   5138:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5139:         }
1.832     raeburn  5140:         if (ref($roledoms) eq 'ARRAY') {
                   5141:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5142:                 next;
                   5143:             }
                   5144:         }
                   5145:         if (ref($roles) eq 'ARRAY') {
                   5146:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5147:                 if ($role =~ /^cr\//) {
                   5148:                     if (!grep(/^cr$/,@{$roles})) {
                   5149:                         next;
                   5150:                     }
1.1104    raeburn  5151:                 } elsif ($role =~ /^gr\//) {
                   5152:                     if (!grep(/^gr$/,@{$roles})) {
                   5153:                         next;
                   5154:                     }
1.922     raeburn  5155:                 } else {
                   5156:                     next;
                   5157:                 }
1.832     raeburn  5158:             }
1.867     raeburn  5159:         }
1.937     raeburn  5160:         if ($hidepriv) {
1.1172.2.23  raeburn  5161:             my @privroles = ('dc','su');
1.999     raeburn  5162:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  5163:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5164:             } else {
1.1172.2.23  raeburn  5165:                 my $possdoms = [$domain];
                   5166:                 if (ref($roledoms) eq 'ARRAY') {
                   5167:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  5168:                 }
1.1172.2.23  raeburn  5169:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5170:                     if (!$nothide{$username.':'.$domain}) {
                   5171:                         next;
                   5172:                     }
                   5173:                 }
1.937     raeburn  5174:             }
                   5175:         }
1.933     raeburn  5176:         if ($withsec) {
                   5177:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5178:                 $tstart.':'.$tend;
                   5179:         } else {
                   5180:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5181:         }
1.832     raeburn  5182:     }
1.373     www      5183:     return %returnhash;
1.399     www      5184: }
                   5185: 
1.1172.2.89  raeburn  5186: sub get_all_adhocroles {
                   5187:     my ($dom) = @_;
                   5188:     my @roles_by_num = ();
                   5189:     my %domdefaults = &get_domain_defaults($dom);
                   5190:     my (%description,%access_in_dom,%access_info);
                   5191:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5192:         my $count = 0;
                   5193:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5194:         my %ordered;
                   5195:         foreach my $role (sort(keys(%domcurrent))) {
                   5196:             my ($order,$desc,$access_in_dom);
                   5197:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5198:                 $order = $domcurrent{$role}{'order'};
                   5199:                 $desc = $domcurrent{$role}{'desc'};
                   5200:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5201:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5202:             }
                   5203:             if ($order eq '') {
                   5204:                 $order = $count;
                   5205:             }
                   5206:             $ordered{$order} = $role;
                   5207:             if ($desc ne '') {
                   5208:                 $description{$role} = $desc;
                   5209:             } else {
                   5210:                 $description{$role}= $role;
                   5211:             }
                   5212:             $count++;
                   5213:         }
                   5214:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5215:             push(@roles_by_num,$ordered{$item});
                   5216:         }
                   5217:     }
                   5218:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5219: }
                   5220: 
                   5221: sub get_my_adhocroles {
                   5222:     my ($cid,$checkreg) = @_;
                   5223:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5224:     if ($env{'request.course.id'} eq $cid) {
                   5225:         $cdom = $env{'course.'.$cid.'.domain'};
                   5226:         $cnum = $env{'course.'.$cid.'.num'};
                   5227:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5228:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5229:         $cdom = $1;
                   5230:         $cnum = $2;
                   5231:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5232:                                      $cdom,$cnum);
                   5233:     }
                   5234:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5235:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5236:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5237:         if ($rosterhash{$user} ne '') {
                   5238:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5239:             return ([],{}) if ($type eq 'auto');
                   5240:         }
                   5241:     }
                   5242:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5243:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5244:             my $then=$env{'user.login.time'};
                   5245:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5246:             if (!$update) {
                   5247:                 $update = $then;
                   5248:             }
                   5249:             my @liveroles;
                   5250:             foreach my $role ('dh','da') {
                   5251:                 if ($env{"user.role.$role./$cdom/"}) {
                   5252:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5253:                     my $limit = $update;
                   5254:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5255:                         $limit = $then;
                   5256:                     }
                   5257:                     my $activerole = 1;
                   5258:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5259:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5260:                     if ($activerole) {
                   5261:                         push(@liveroles,$role);
                   5262:                     }
                   5263:                 }
                   5264:             }
                   5265:             if (@liveroles) {
1.1172.2.89  raeburn  5266:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5267:                     my ($accessref,$accessinfo,%access_in_dom);
                   5268:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5269:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5270:                         if (@{$roles_by_num}) {
                   5271:                             my %settings;
                   5272:                             if ($env{'request.course.id'} eq $cid) {
                   5273:                                 foreach my $envkey (keys(%env)) {
                   5274:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5275:                                         $settings{$1} = $env{$envkey};
                   5276:                                     }
                   5277:                                 }
                   5278:                             } else {
                   5279:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5280:                             }
                   5281:                             my %setincrs;
                   5282:                             if ($settings{'internal.adhocaccess'}) {
                   5283:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5284:                             }
                   5285:                             my @statuses;
                   5286:                             if ($env{'environment.inststatus'}) {
                   5287:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5288:                             }
                   5289:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5290:                             if (ref($accessref) eq 'HASH') {
                   5291:                                 %access_in_dom = %{$accessref};
                   5292:                             }
                   5293:                             foreach my $role (@{$roles_by_num}) {
                   5294:                                 my ($curraccess,@okstatus,@personnel);
                   5295:                                 if ($setincrs{$role}) {
                   5296:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5297:                                     if ($curraccess eq 'status') {
                   5298:                                         @okstatus = split(/\&/,$rest);
                   5299:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5300:                                         @personnel = split(/\&/,$rest);
                   5301:                                     }
                   5302:                                 } else {
                   5303:                                     $curraccess = $access_in_dom{$role};
                   5304:                                     if (ref($accessinfo) eq 'HASH') {
                   5305:                                         if ($curraccess eq 'status') {
                   5306:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5307:                                                 @okstatus = @{$accessinfo->{$role}};
                   5308:                                             }
                   5309:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5310:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5311:                                                 @personnel = @{$accessinfo->{$role}};
                   5312:                                             }
                   5313:                                         }
                   5314:                                     }
                   5315:                                 }
                   5316:                                 if ($curraccess eq 'none') {
                   5317:                                     next;
                   5318:                                 } elsif ($curraccess eq 'all') {
                   5319:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5320:                                 } elsif ($curraccess eq 'dh') {
                   5321:                                     if (grep(/^dh$/,@liveroles)) {
                   5322:                                         push(@possroles,$role);
                   5323:                                     } else {
                   5324:                                         next;
                   5325:                                     }
                   5326:                                 } elsif ($curraccess eq 'da') {
                   5327:                                     if (grep(/^da$/,@liveroles)) {
                   5328:                                         push(@possroles,$role);
                   5329:                                     } else {
                   5330:                                         next;
                   5331:                                     }
1.1172.2.89  raeburn  5332:                                 } elsif ($curraccess eq 'status') {
                   5333:                                     if (@okstatus) {
                   5334:                                         if (!@statuses) {
                   5335:                                             if (grep(/^default$/,@okstatus)) {
                   5336:                                                 push(@possroles,$role);
                   5337:                                             }
                   5338:                                         } else {
                   5339:                                             foreach my $status (@okstatus) {
                   5340:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5341:                                                     push(@possroles,$role);
                   5342:                                                     last;
                   5343:                                                 }
                   5344:                                             }
                   5345:                                         }
                   5346:                                     }
                   5347:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5348:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5349:                                         if ($curraccess eq 'exc') {
                   5350:                                             push(@possroles,$role);
                   5351:                                         }
                   5352:                                     } elsif ($curraccess eq 'inc') {
                   5353:                                         push(@possroles,$role);
                   5354:                                     }
                   5355:                                 }
                   5356:                             }
                   5357:                         }
                   5358:                     }
                   5359:                 }
                   5360:             }
                   5361:         }
                   5362:     }
                   5363:     unless (ref($description) eq 'HASH') {
                   5364:         if (ref($roles_by_num) eq 'ARRAY') {
                   5365:             my %desc;
                   5366:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5367:             $description = \%desc;
                   5368:         } else {
                   5369:             $description = {};
                   5370:         }
                   5371:     }
                   5372:     return (\@possroles,$description);
                   5373: }
                   5374: 
1.399     www      5375: # ----------------------------------------------------- Frontpage Announcements
                   5376: #
                   5377: #
                   5378: 
                   5379: sub postannounce {
                   5380:     my ($server,$text)=@_;
1.844     albertel 5381:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5382:     unless ($text=~/\w/) { $text=''; }
                   5383:     return &reply('setannounce:'.&escape($text),$server);
                   5384: }
                   5385: 
                   5386: sub getannounce {
1.448     albertel 5387: 
1.1172.2.96  raeburn  5388:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5389: 	my $announcement='';
1.800     albertel 5390: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5391: 	close($fh);
1.399     www      5392: 	if ($announcement=~/\w/) { 
                   5393: 	    return 
                   5394:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5395:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5396: 	} else {
                   5397: 	    return '';
                   5398: 	}
                   5399:     } else {
                   5400: 	return '';
                   5401:     }
1.351     www      5402: }
1.353     www      5403: 
                   5404: # ---------------------------------------------------------- Course ID routines
                   5405: # Deal with domain's nohist_courseid.db files
                   5406: #
                   5407: 
                   5408: sub courseidput {
1.921     raeburn  5409:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5410:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5411:     my $outcome;
                   5412:     if ($caller eq 'timeonly') {
                   5413:         my $cids = '';
                   5414:         foreach my $item (keys(%$storehash)) {
                   5415:             $cids.=&escape($item).'&';
                   5416:         }
                   5417:         $cids=~s/\&$//;
                   5418:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5419:                           $coursehome);       
                   5420:     } else {
                   5421:         my $items = '';
                   5422:         foreach my $item (keys(%$storehash)) {
                   5423:             $items.= &escape($item).'='.
                   5424:                      &freeze_escape($$storehash{$item}).'&';
                   5425:         }
                   5426:         $items=~s/\&$//;
                   5427:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5428:                           $coursehome);
1.918     raeburn  5429:     }
                   5430:     if ($outcome eq 'unknown_cmd') {
                   5431:         my $what;
                   5432:         foreach my $cid (keys(%$storehash)) {
                   5433:             $what .= &escape($cid).'=';
1.921     raeburn  5434:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5435:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5436:             }
                   5437:             $what =~ s/\:$/&/;
                   5438:         }
                   5439:         $what =~ s/\&$//;  
                   5440:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5441:     } else {
                   5442:         return $outcome;
                   5443:     }
1.353     www      5444: }
                   5445: 
                   5446: sub courseiddump {
1.921     raeburn  5447:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5448:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5449:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5450:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5451:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5452:     my $as_hash = 1;
                   5453:     my %returnhash;
                   5454:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5455:     my %libserv = &all_library();
                   5456:     foreach my $tryserver (keys(%libserv)) {
                   5457:         if ( (  $hostidflag == 1 
                   5458: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5459: 	     || (!defined($hostidflag)) ) {
                   5460: 
1.918     raeburn  5461: 	    if (($domfilter eq '') ||
                   5462: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5463:                 my $rep;
                   5464:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5465:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5466:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5467:                                 &escape($descfilter), &escape($instcodefilter),
                   5468:                                 &escape($ownerfilter), &escape($coursefilter),
                   5469:                                 &escape($typefilter), &escape($regexp_ok),
                   5470:                                 $as_hash, &escape($selfenrollonly),
                   5471:                                 &escape($catfilter), $showhidden, $caller,
                   5472:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5473:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5474:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5475:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5476:                 } else {
                   5477:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5478:                              $sincefilter.':'.&escape($descfilter).':'.
                   5479:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5480:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5481:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5482:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5483:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5484:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5485:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5486:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5487:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5488:                 }
                   5489: 
1.918     raeburn  5490:                 my @pairs=split(/\&/,$rep);
                   5491:                 foreach my $item (@pairs) {
                   5492:                     my ($key,$value)=split(/\=/,$item,2);
                   5493:                     $key = &unescape($key);
                   5494:                     next if ($key =~ /^error: 2 /);
                   5495:                     my $result = &thaw_unescape($value);
                   5496:                     if (ref($result) eq 'HASH') {
                   5497:                         $returnhash{$key}=$result;
                   5498:                     } else {
1.921     raeburn  5499:                         my @responses = split(/:/,$value);
                   5500:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5501:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5502:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5503:                         }
1.1008    raeburn  5504:                     }
1.353     www      5505:                 }
                   5506:             }
                   5507:         }
                   5508:     }
                   5509:     return %returnhash;
                   5510: }
                   5511: 
1.1055    raeburn  5512: sub courselastaccess {
                   5513:     my ($cdom,$cnum,$hostidref) = @_;
                   5514:     my %returnhash;
                   5515:     if ($cdom && $cnum) {
                   5516:         my $chome = &homeserver($cnum,$cdom);
                   5517:         if ($chome ne 'no_host') {
                   5518:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5519:             &extract_lastaccess(\%returnhash,$rep);
                   5520:         }
                   5521:     } else {
                   5522:         if (!$cdom) { $cdom=''; }
                   5523:         my %libserv = &all_library();
                   5524:         foreach my $tryserver (keys(%libserv)) {
                   5525:             if (ref($hostidref) eq 'ARRAY') {
                   5526:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5527:             } 
                   5528:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5529:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5530:                 &extract_lastaccess(\%returnhash,$rep);
                   5531:             }
                   5532:         }
                   5533:     }
                   5534:     return %returnhash;
                   5535: }
                   5536: 
                   5537: sub extract_lastaccess {
                   5538:     my ($returnhash,$rep) = @_;
                   5539:     if (ref($returnhash) eq 'HASH') {
                   5540:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5541:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5542:                  $rep eq '') {
                   5543:             my @pairs=split(/\&/,$rep);
                   5544:             foreach my $item (@pairs) {
                   5545:                 my ($key,$value)=split(/\=/,$item,2);
                   5546:                 $key = &unescape($key);
                   5547:                 next if ($key =~ /^error: 2 /);
                   5548:                 $returnhash->{$key} = &thaw_unescape($value);
                   5549:             }
                   5550:         }
                   5551:     }
                   5552:     return;
                   5553: }
                   5554: 
1.658     raeburn  5555: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5556: 
                   5557: sub dcmailput {
1.685     raeburn  5558:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5559:     my $status = &Apache::lonnet::critical(
1.740     www      5560:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5561:        &escape($message),$server);
1.662     raeburn  5562:     return $status;
                   5563: }
                   5564: 
1.658     raeburn  5565: sub dcmaildump {
                   5566:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5567:     my %returnhash=();
1.846     albertel 5568: 
                   5569:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5570:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5571:                                                          &escape($enddate).':';
                   5572: 	my @esc_senders=map { &escape($_)} @$senders;
                   5573: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5574: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5575:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5576:             if (($key) && ($value)) {
                   5577:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5578:             }
                   5579:         }
                   5580:     }
                   5581:     return %returnhash;
                   5582: }
1.662     raeburn  5583: # ---------------------------------------------------------- Domain roles
                   5584: 
                   5585: sub get_domain_roles {
                   5586:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5587:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5588:         $startdate = '.';
                   5589:     }
1.1018    raeburn  5590:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5591:         $enddate = '.';
                   5592:     }
1.922     raeburn  5593:     my $rolelist;
                   5594:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5595:         $rolelist = join('&',@{$roles});
1.922     raeburn  5596:     }
1.662     raeburn  5597:     my %personnel = ();
1.841     albertel 5598: 
                   5599:     my %servers = &get_servers($dom,'library');
                   5600:     foreach my $tryserver (keys(%servers)) {
                   5601: 	%{$personnel{$tryserver}}=();
                   5602: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5603: 					    &escape($startdate).':'.
                   5604: 					    &escape($enddate).':'.
                   5605: 					    &escape($rolelist), $tryserver))) {
                   5606: 	    my ($key,$value) = split(/\=/,$line,2);
                   5607: 	    if (($key) && ($value)) {
                   5608: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5609: 	    }
                   5610: 	}
1.662     raeburn  5611:     }
                   5612:     return %personnel;
                   5613: }
1.658     raeburn  5614: 
1.1172.2.89  raeburn  5615: sub get_active_domroles {
                   5616:     my ($dom,$roles) = @_;
                   5617:     return () unless (ref($roles) eq 'ARRAY');
                   5618:     my $now = time;
                   5619:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5620:     my %domroles;
                   5621:     foreach my $server (keys(%dompersonnel)) {
                   5622:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5623:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5624:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5625:         }
                   5626:     }
                   5627:     return %domroles;
                   5628: }
                   5629: 
1.1057    www      5630: # ----------------------------------------------------------- Interval timing 
1.149     www      5631: 
1.1153    www      5632: {
                   5633: # Caches needed for speedup of navmaps
                   5634: # We don't want to cache this for very long at all (5 seconds at most)
                   5635: # 
                   5636: # The user for whom we cache
                   5637: my $cachedkey='';
                   5638: # The cached times for this user
                   5639: my %cachedtimes=();
                   5640: # When this was last done
1.1172.2.66  raeburn  5641: my $cachedtime='';
1.1153    www      5642: 
                   5643: sub load_all_first_access {
1.1172.2.146.  .1(raebu 5644:22):     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5645:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.146.  .1(raebu 5646:22):         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5647:22):         (!$ignorecache)) {
1.1154    raeburn  5648:         return;
                   5649:     }
                   5650:     $cachedtime=time;
                   5651:     $cachedkey=$uname.':'.$udom;
                   5652:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5653: }
                   5654: 
1.504     albertel 5655: sub get_first_access {
1.1172.2.146.  .1(raebu 5656:22):     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5657:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5658:     if ($argsymb) { $symb=$argsymb; }
                   5659:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5660:     if ($argmap) { $map = $argmap; }
1.926     albertel 5661:     if ($type eq 'course') {
                   5662: 	$res='course';
                   5663:     } elsif ($type eq 'map') {
1.588     albertel 5664: 	$res=&symbread($map);
                   5665:     } else {
                   5666: 	$res=$symb;
                   5667:     }
1.1172.2.146.  .1(raebu 5668:22):     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5669:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5670: }
                   5671: 
                   5672: sub set_first_access {
1.1162    raeburn  5673:     my ($type,$interval)=@_;
1.790     albertel 5674:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5675:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5676:     if ($type eq 'course') {
                   5677: 	$res='course';
                   5678:     } elsif ($type eq 'map') {
1.588     albertel 5679: 	$res=&symbread($map);
                   5680:     } else {
                   5681: 	$res=$symb;
                   5682:     }
1.1153    www      5683:     $cachedkey='';
1.1162    raeburn  5684:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5685:     if ($firstaccess) {
                   5686:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5687:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5688:                  "in $courseid");
                   5689:         return 'already_set';
                   5690:     } else {
1.1162    raeburn  5691:         my $start = time;
                   5692: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5693:                           $udom,$uname);
                   5694:         if ($putres eq 'ok') {
                   5695:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5696:                  $udom,$uname); 
                   5697:             &appenv(
                   5698:                      {
                   5699:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5700:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5701:                      }
                   5702:                   );
1.1172.2.97  raeburn  5703:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5704:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5705:             }
1.1172.2.102  raeburn  5706:         } elsif ($putres ne 'refused') {
                   5707:             &logthis("Result: $putres when attempting to set first access time ".
                   5708:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5709:         }
                   5710:         return $putres;
1.505     albertel 5711:     }
                   5712:     return 'already_set';
1.504     albertel 5713: }
1.1153    www      5714: }
1.1172.2.32  raeburn  5715: 
                   5716: sub checkout {
                   5717:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5718:     my $now=time;
                   5719:     my $lonhost=$perlvar{'lonHostID'};
1.1172.2.134  raeburn  5720:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5721:     my $infostr=&escape(
                   5722:                  'CHECKOUTTOKEN&'.
                   5723:                  $tuname.'&'.
                   5724:                  $tudom.'&'.
                   5725:                  $tcrsid.'&'.
                   5726:                  $symb.'&'.
1.1172.2.134  raeburn  5727:                  $now.'&'.$ip);
1.1172.2.32  raeburn  5728:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5729:     if ($token=~/^error\:/) {
                   5730:         &logthis("<font color=\"blue\">WARNING: ".
                   5731:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5732:                  "</font>");
                   5733:         return '';
                   5734:     }
                   5735: 
                   5736:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5737:     $token=~tr/a-z/A-Z/;
                   5738: 
                   5739:     my %infohash=('resource.0.outtoken' => $token,
                   5740:                   'resource.0.checkouttime' => $now,
1.1172.2.134  raeburn  5741:                   'resource.0.outremote' => $ip);
1.1172.2.32  raeburn  5742: 
                   5743:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5744:        return '';
                   5745:     } else {
                   5746:         &logthis("<font color=\"blue\">WARNING: ".
                   5747:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5748:                  "</font>");
                   5749:     }
                   5750: 
                   5751:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5752:                          &escape('Checkout '.$infostr.' - '.
                   5753:                                                  $token)) ne 'ok') {
                   5754:         return '';
                   5755:     } else {
                   5756:         &logthis("<font color=\"blue\">WARNING: ".
                   5757:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5758:                  "</font>");
                   5759:     }
                   5760:     return $token;
                   5761: }
                   5762: 
                   5763: # ------------------------------------------------------------ Check in an item
                   5764: 
                   5765: sub checkin {
                   5766:     my $token=shift;
                   5767:     my $now=time;
                   5768:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5769:     $lonhost=~tr/A-Z/a-z/;
                   5770:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5771:     $dtoken=~s/\W/\_/g;
1.1172.2.134  raeburn  5772:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5773:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5774:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5775: 
                   5776:     unless (($tuname) && ($tudom)) {
                   5777:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5778:         return '';
                   5779:     }
                   5780: 
                   5781:     unless (&allowed('mgr',$tcrsid)) {
                   5782:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5783:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5784:         return '';
                   5785:     }
                   5786: 
                   5787:     my %infohash=('resource.0.intoken' => $token,
                   5788:                   'resource.0.checkintime' => $now,
1.1172.2.134  raeburn  5789:                   'resource.0.inremote' => $ip);
1.1172.2.32  raeburn  5790: 
                   5791:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5792:        return '';
                   5793:     }
                   5794: 
                   5795:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5796:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5797:         return '';
                   5798:     }
                   5799: 
                   5800:     return ($symb,$tuname,$tudom,$tcrsid);
                   5801: }
                   5802: 
1.110     www      5803: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5804: 
                   5805: sub expirespread {
                   5806:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5807:     my $cid=$env{'request.course.id'}; 
1.110     www      5808:     if ($cid) {
                   5809:        my $now=time;
                   5810:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5811:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5812:                             $env{'course.'.$cid.'.num'}.
1.110     www      5813: 	        	    ':nohist_expirationdates:'.
                   5814:                             &escape($key).'='.$now,
1.620     albertel 5815:                             $env{'course.'.$cid.'.home'})
1.110     www      5816:     }
                   5817:     return 'ok';
1.14      www      5818: }
                   5819: 
1.109     www      5820: # ----------------------------------------------------- Devalidate Spreadsheets
                   5821: 
                   5822: sub devalidate {
1.325     www      5823:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5824:     my $cid=$env{'request.course.id'}; 
1.109     www      5825:     if ($cid) {
1.391     matthew  5826:         # delete the stored spreadsheets for
                   5827:         # - the student level sheet of this user in course's homespace
                   5828:         # - the assessment level sheet for this resource 
                   5829:         #   for this user in user's homespace
1.553     albertel 5830: 	# - current conditional state info
1.325     www      5831: 	my $key=$uname.':'.$udom.':';
1.109     www      5832:         my $status=
1.299     matthew  5833: 	    &del('nohist_calculatedsheets',
1.391     matthew  5834: 		 [$key.'studentcalc:'],
1.620     albertel 5835: 		 $env{'course.'.$cid.'.domain'},
                   5836: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5837: 		.' '.
                   5838: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5839: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5840:         unless ($status eq 'ok ok') {
                   5841:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5842:                     $uname.' at '.$udom.' for '.
1.109     www      5843: 		    $symb.': '.$status);
1.133     albertel 5844:         }
1.553     albertel 5845: 	&delenv('user.state.'.$cid);
1.109     www      5846:     }
                   5847: }
                   5848: 
1.265     albertel 5849: sub get_scalar {
                   5850:     my ($string,$end) = @_;
                   5851:     my $value;
                   5852:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5853: 	$value = $1;
                   5854:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5855: 	$value = $1;
                   5856:     }
                   5857:     return &unescape($value);
                   5858: }
                   5859: 
                   5860: sub array2str {
                   5861:   my (@array) = @_;
                   5862:   my $result=&arrayref2str(\@array);
                   5863:   $result=~s/^__ARRAY_REF__//;
                   5864:   $result=~s/__END_ARRAY_REF__$//;
                   5865:   return $result;
                   5866: }
                   5867: 
1.204     albertel 5868: sub arrayref2str {
                   5869:   my ($arrayref) = @_;
1.265     albertel 5870:   my $result='__ARRAY_REF__';
1.204     albertel 5871:   foreach my $elem (@$arrayref) {
1.265     albertel 5872:     if(ref($elem) eq 'ARRAY') {
                   5873:       $result.=&arrayref2str($elem).'&';
                   5874:     } elsif(ref($elem) eq 'HASH') {
                   5875:       $result.=&hashref2str($elem).'&';
                   5876:     } elsif(ref($elem)) {
                   5877:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5878:     } else {
                   5879:       $result.=&escape($elem).'&';
                   5880:     }
                   5881:   }
                   5882:   $result=~s/\&$//;
1.265     albertel 5883:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5884:   return $result;
                   5885: }
                   5886: 
1.168     albertel 5887: sub hash2str {
1.204     albertel 5888:   my (%hash) = @_;
                   5889:   my $result=&hashref2str(\%hash);
1.265     albertel 5890:   $result=~s/^__HASH_REF__//;
                   5891:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5892:   return $result;
                   5893: }
                   5894: 
                   5895: sub hashref2str {
                   5896:   my ($hashref)=@_;
1.265     albertel 5897:   my $result='__HASH_REF__';
1.800     albertel 5898:   foreach my $key (sort(keys(%$hashref))) {
                   5899:     if (ref($key) eq 'ARRAY') {
                   5900:       $result.=&arrayref2str($key).'=';
                   5901:     } elsif (ref($key) eq 'HASH') {
                   5902:       $result.=&hashref2str($key).'=';
                   5903:     } elsif (ref($key)) {
1.265     albertel 5904:       $result.='=';
1.800     albertel 5905:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5906:     } else {
1.1132    raeburn  5907: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5908:     }
                   5909: 
1.800     albertel 5910:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5911:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5912:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5913:       $result.=&hashref2str($hashref->{$key}).'&';
                   5914:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5915:        $result.='&';
1.800     albertel 5916:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5917:     } else {
1.800     albertel 5918:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5919:     }
                   5920:   }
1.168     albertel 5921:   $result=~s/\&$//;
1.265     albertel 5922:   $result .= '__END_HASH_REF__';
1.168     albertel 5923:   return $result;
                   5924: }
                   5925: 
                   5926: sub str2hash {
1.265     albertel 5927:     my ($string)=@_;
                   5928:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5929:     return %$hash;
                   5930: }
                   5931: 
                   5932: sub str2hashref {
1.168     albertel 5933:   my ($string) = @_;
1.265     albertel 5934: 
                   5935:   my %hash;
                   5936: 
                   5937:   if($string !~ /^__HASH_REF__/) {
                   5938:       if (! ($string eq '' || !defined($string))) {
                   5939: 	  $hash{'error'}='Not hash reference';
                   5940:       }
                   5941:       return (\%hash, $string);
                   5942:   }
                   5943: 
                   5944:   $string =~ s/^__HASH_REF__//;
                   5945: 
                   5946:   while($string !~ /^__END_HASH_REF__/) {
                   5947:       #key
                   5948:       my $key='';
                   5949:       if($string =~ /^__HASH_REF__/) {
                   5950:           ($key, $string)=&str2hashref($string);
                   5951:           if(defined($key->{'error'})) {
                   5952:               $hash{'error'}='Bad data';
                   5953:               return (\%hash, $string);
                   5954:           }
                   5955:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5956:           ($key, $string)=&str2arrayref($string);
                   5957:           if($key->[0] eq 'Array reference error') {
                   5958:               $hash{'error'}='Bad data';
                   5959:               return (\%hash, $string);
                   5960:           }
                   5961:       } else {
                   5962:           $string =~ s/^(.*?)=//;
1.267     albertel 5963: 	  $key=&unescape($1);
1.265     albertel 5964:       }
                   5965:       $string =~ s/^=//;
                   5966: 
                   5967:       #value
                   5968:       my $value='';
                   5969:       if($string =~ /^__HASH_REF__/) {
                   5970:           ($value, $string)=&str2hashref($string);
                   5971:           if(defined($value->{'error'})) {
                   5972:               $hash{'error'}='Bad data';
                   5973:               return (\%hash, $string);
                   5974:           }
                   5975:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5976:           ($value, $string)=&str2arrayref($string);
                   5977:           if($value->[0] eq 'Array reference error') {
                   5978:               $hash{'error'}='Bad data';
                   5979:               return (\%hash, $string);
                   5980:           }
                   5981:       } else {
                   5982: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5983:       }
                   5984:       $string =~ s/^&//;
                   5985: 
                   5986:       $hash{$key}=$value;
1.204     albertel 5987:   }
1.265     albertel 5988: 
                   5989:   $string =~ s/^__END_HASH_REF__//;
                   5990: 
                   5991:   return (\%hash, $string);
1.204     albertel 5992: }
                   5993: 
                   5994: sub str2array {
1.265     albertel 5995:     my ($string)=@_;
                   5996:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5997:     return @$array;
                   5998: }
                   5999: 
                   6000: sub str2arrayref {
1.204     albertel 6001:   my ($string) = @_;
1.265     albertel 6002:   my @array;
                   6003: 
                   6004:   if($string !~ /^__ARRAY_REF__/) {
                   6005:       if (! ($string eq '' || !defined($string))) {
                   6006: 	  $array[0]='Array reference error';
                   6007:       }
                   6008:       return (\@array, $string);
                   6009:   }
                   6010: 
                   6011:   $string =~ s/^__ARRAY_REF__//;
                   6012: 
                   6013:   while($string !~ /^__END_ARRAY_REF__/) {
                   6014:       my $value='';
                   6015:       if($string =~ /^__HASH_REF__/) {
                   6016:           ($value, $string)=&str2hashref($string);
                   6017:           if(defined($value->{'error'})) {
                   6018:               $array[0] ='Array reference error';
                   6019:               return (\@array, $string);
                   6020:           }
                   6021:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6022:           ($value, $string)=&str2arrayref($string);
                   6023:           if($value->[0] eq 'Array reference error') {
                   6024:               $array[0] ='Array reference error';
                   6025:               return (\@array, $string);
                   6026:           }
                   6027:       } else {
                   6028: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   6029:       }
                   6030:       $string =~ s/^&//;
                   6031: 
                   6032:       push(@array, $value);
1.191     harris41 6033:   }
1.265     albertel 6034: 
                   6035:   $string =~ s/^__END_ARRAY_REF__//;
                   6036: 
                   6037:   return (\@array, $string);
1.168     albertel 6038: }
                   6039: 
1.167     albertel 6040: # -------------------------------------------------------------------Temp Store
                   6041: 
1.168     albertel 6042: sub tmpreset {
                   6043:   my ($symb,$namespace,$domain,$stuname) = @_;
                   6044:   if (!$symb) {
                   6045:     $symb=&symbread();
1.620     albertel 6046:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6047:   }
                   6048:   $symb=escape($symb);
                   6049: 
1.620     albertel 6050:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 6051:   $namespace=~s/\//\_/g;
                   6052:   $namespace=~s/\W//g;
                   6053: 
1.620     albertel 6054:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6055:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6056:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6057:       $stuname=&get_requestor_ip();
1.591     albertel 6058:   }
1.1117    foxr     6059:   my $path=LONCAPA::tempdir();
1.168     albertel 6060:   my %hash;
                   6061:   if (tie(%hash,'GDBM_File',
                   6062: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6063: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  6064:     foreach my $key (keys(%hash)) {
1.180     albertel 6065:       if ($key=~ /:$symb/) {
1.168     albertel 6066: 	delete($hash{$key});
                   6067:       }
                   6068:     }
                   6069:   }
                   6070: }
                   6071: 
1.167     albertel 6072: sub tmpstore {
1.168     albertel 6073:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   6074: 
                   6075:   if (!$symb) {
                   6076:     $symb=&symbread();
1.620     albertel 6077:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6078:   }
                   6079:   $symb=escape($symb);
                   6080: 
                   6081:   if (!$namespace) {
                   6082:     # I don't think we would ever want to store this for a course.
                   6083:     # it seems this will only be used if we don't have a course.
1.620     albertel 6084:     #$namespace=$env{'request.course.id'};
1.168     albertel 6085:     #if (!$namespace) {
1.620     albertel 6086:       $namespace=$env{'request.state'};
1.168     albertel 6087:     #}
                   6088:   }
                   6089:   $namespace=~s/\//\_/g;
                   6090:   $namespace=~s/\W//g;
1.620     albertel 6091:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6092:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6093:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6094:       $stuname=&get_requestor_ip();
1.591     albertel 6095:   }
1.168     albertel 6096:   my $now=time;
                   6097:   my %hash;
1.1117    foxr     6098:   my $path=LONCAPA::tempdir();
1.168     albertel 6099:   if (tie(%hash,'GDBM_File',
                   6100: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6101: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 6102:     $hash{"version:$symb"}++;
                   6103:     my $version=$hash{"version:$symb"};
                   6104:     my $allkeys=''; 
                   6105:     foreach my $key (keys(%$storehash)) {
                   6106:       $allkeys.=$key.':';
1.591     albertel 6107:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 6108:     }
                   6109:     $hash{"$version:$symb:timestamp"}=$now;
                   6110:     $allkeys.='timestamp';
                   6111:     $hash{"$version:keys:$symb"}=$allkeys;
                   6112:     if (untie(%hash)) {
                   6113:       return 'ok';
                   6114:     } else {
                   6115:       return "error:$!";
                   6116:     }
                   6117:   } else {
                   6118:     return "error:$!";
                   6119:   }
                   6120: }
1.167     albertel 6121: 
1.168     albertel 6122: # -----------------------------------------------------------------Temp Restore
1.167     albertel 6123: 
1.168     albertel 6124: sub tmprestore {
                   6125:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 6126: 
1.168     albertel 6127:   if (!$symb) {
                   6128:     $symb=&symbread();
1.620     albertel 6129:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6130:   }
                   6131:   $symb=escape($symb);
                   6132: 
1.620     albertel 6133:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 6134: 
1.620     albertel 6135:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6136:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6137:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6138:       $stuname=&get_requestor_ip();
1.591     albertel 6139:   }
1.168     albertel 6140:   my %returnhash;
                   6141:   $namespace=~s/\//\_/g;
                   6142:   $namespace=~s/\W//g;
                   6143:   my %hash;
1.1117    foxr     6144:   my $path=LONCAPA::tempdir();
1.168     albertel 6145:   if (tie(%hash,'GDBM_File',
                   6146: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6147: 	  &GDBM_READER(),0640)) {
1.168     albertel 6148:     my $version=$hash{"version:$symb"};
                   6149:     $returnhash{'version'}=$version;
                   6150:     my $scope;
                   6151:     for ($scope=1;$scope<=$version;$scope++) {
                   6152:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6153:       my @keys=split(/:/,$vkeys);
                   6154:       my $key;
                   6155:       $returnhash{"$scope:keys"}=$vkeys;
                   6156:       foreach $key (@keys) {
1.591     albertel 6157: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6158: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6159:       }
                   6160:     }
1.168     albertel 6161:     if (!(untie(%hash))) {
                   6162:       return "error:$!";
                   6163:     }
                   6164:   } else {
                   6165:     return "error:$!";
                   6166:   }
                   6167:   return %returnhash;
1.167     albertel 6168: }
                   6169: 
1.9       www      6170: # ----------------------------------------------------------------------- Store
                   6171: 
                   6172: sub store {
1.1172.2.64  raeburn  6173:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6174:     my $home='';
                   6175: 
1.168     albertel 6176:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6177: 
1.213     www      6178:     $symb=&symbclean($symb);
1.122     albertel 6179:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6180: 
1.620     albertel 6181:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6182:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6183: 
                   6184:     &devalidate($symb,$stuname,$domain);
1.109     www      6185: 
                   6186:     $symb=escape($symb);
1.187     www      6187:     if (!$namespace) { 
1.620     albertel 6188:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6189:           return ''; 
                   6190:        } 
                   6191:     }
1.620     albertel 6192:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6193: 
1.1172.2.138  raeburn  6194:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6195:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6196: 
1.12      www      6197:     my $namevalue='';
1.800     albertel 6198:     foreach my $key (keys(%$storehash)) {
                   6199:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6200:     }
1.12      www      6201:     $namevalue=~s/\&$//;
1.187     www      6202:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  6203:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6204: }
                   6205: 
1.47      www      6206: # -------------------------------------------------------------- Critical Store
                   6207: 
                   6208: sub cstore {
1.1172.2.64  raeburn  6209:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6210:     my $home='';
                   6211: 
1.168     albertel 6212:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6213: 
1.213     www      6214:     $symb=&symbclean($symb);
1.122     albertel 6215:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6216: 
1.620     albertel 6217:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6218:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6219: 
                   6220:     &devalidate($symb,$stuname,$domain);
1.109     www      6221: 
                   6222:     $symb=escape($symb);
1.187     www      6223:     if (!$namespace) { 
1.620     albertel 6224:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6225:           return ''; 
                   6226:        } 
                   6227:     }
1.620     albertel 6228:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6229: 
1.1172.2.138  raeburn  6230:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6231:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6232: 
1.47      www      6233:     my $namevalue='';
1.800     albertel 6234:     foreach my $key (keys(%$storehash)) {
                   6235:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6236:     }
1.47      www      6237:     $namevalue=~s/\&$//;
1.187     www      6238:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6239:     return critical
1.1172.2.64  raeburn  6240:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6241: }
                   6242: 
1.9       www      6243: # --------------------------------------------------------------------- Restore
                   6244: 
                   6245: sub restore {
1.124     www      6246:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6247:     my $home='';
                   6248: 
1.168     albertel 6249:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6250: 
1.122     albertel 6251:     if (!$symb) {
1.1172.2.26  raeburn  6252:         return if ($namespace eq 'courserequests');
                   6253:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6254:     } else {
1.1172.2.26  raeburn  6255:         unless ($namespace eq 'courserequests') {
                   6256:             $symb=&escape(&symbclean($symb));
                   6257:         }
1.122     albertel 6258:     }
1.188     www      6259:     if (!$namespace) { 
1.620     albertel 6260:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6261:           return ''; 
                   6262:        } 
                   6263:     }
1.620     albertel 6264:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6265:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6266:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6267:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6268: 
1.12      www      6269:     my %returnhash=();
1.800     albertel 6270:     foreach my $line (split(/\&/,$answer)) {
                   6271: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6272:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6273:     }
1.75      www      6274:     my $version;
                   6275:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6276:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6277:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6278:        }
1.75      www      6279:     }
1.13      www      6280:     return %returnhash;
1.34      www      6281: }
                   6282: 
                   6283: # ---------------------------------------------------------- Course Description
1.1118    foxr     6284: #
                   6285: #  
1.34      www      6286: 
                   6287: sub coursedescription {
1.731     albertel 6288:     my ($courseid,$args)=@_;
1.34      www      6289:     $courseid=~s/^\///;
1.49      www      6290:     $courseid=~s/\_/\//g;
1.34      www      6291:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6292:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6293:     my $normalid=$cdomain.'_'.$cnum;
                   6294:     # need to always cache even if we get errors otherwise we keep 
                   6295:     # trying and trying and trying to get the course description.
                   6296:     my %envhash=();
                   6297:     my %returnhash=();
1.731     albertel 6298:     
                   6299:     my $expiretime=600;
                   6300:     if ($env{'request.course.id'} eq $normalid) {
                   6301: 	$expiretime=120;
                   6302:     }
                   6303: 
                   6304:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6305:     if (!$args->{'freshen_cache'}
                   6306: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6307: 	foreach my $key (keys(%env)) {
                   6308: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6309: 	    my ($setting) = $1;
                   6310: 	    $returnhash{$setting} = $env{$key};
                   6311: 	}
                   6312: 	return %returnhash;
                   6313:     }
                   6314: 
1.1118    foxr     6315:     # get the data again
                   6316: 
1.731     albertel 6317:     if (!$args->{'one_time'}) {
                   6318: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6319:     }
1.811     albertel 6320: 
1.34      www      6321:     if ($chome ne 'no_host') {
1.302     albertel 6322:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6323:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6324: 	   my $username = $env{'user.name'}; # Defult username
                   6325: 	   if(defined $args->{'user'}) {
                   6326: 	       $username = $args->{'user'};
                   6327: 	   }
1.129     albertel 6328:            $returnhash{'home'}= $chome;
                   6329: 	   $returnhash{'domain'} = $cdomain;
                   6330: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6331:            if (!defined($returnhash{'type'})) {
                   6332:                $returnhash{'type'} = 'Course';
                   6333:            }
1.130     albertel 6334:            while (my ($name,$value) = each %returnhash) {
1.53      www      6335:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6336:            }
1.270     www      6337:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6338:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6339: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6340:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6341:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6342:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6343:        }
                   6344:     }
1.731     albertel 6345:     if (!$args->{'one_time'}) {
1.949     raeburn  6346: 	&appenv(\%envhash);
1.731     albertel 6347:     }
1.302     albertel 6348:     return %returnhash;
1.461     www      6349: }
                   6350: 
1.1080    raeburn  6351: sub update_released_required {
                   6352:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6353:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6354:         $cid = $env{'request.course.id'};
                   6355:         $cdom = $env{'course.'.$cid.'.domain'};
                   6356:         $cnum = $env{'course.'.$cid.'.num'};
                   6357:         $chome = $env{'course.'.$cid.'.home'};
                   6358:     }
                   6359:     if ($needsrelease) {
                   6360:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6361:         my $needsupdate;
                   6362:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6363:             $needsupdate = 1;
                   6364:         } else {
                   6365:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6366:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6367:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6368:                 $needsupdate = 1;
                   6369:             }
                   6370:         }
                   6371:         if ($needsupdate) {
                   6372:             my %needshash = (
                   6373:                              'internal.releaserequired' => $needsrelease,
                   6374:                             );
                   6375:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6376:             if ($putresult eq 'ok') {
                   6377:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6378:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6379:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6380:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6381:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6382:                 }
                   6383:             }
                   6384:         }
                   6385:     }
                   6386:     return;
                   6387: }
                   6388: 
1.461     www      6389: # -------------------------------------------------See if a user is privileged
                   6390: 
                   6391: sub privileged {
1.1172.2.23  raeburn  6392:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6393:     my $now = time;
1.1172.2.23  raeburn  6394:     my $roles;
                   6395:     if (ref($possroles) eq 'ARRAY') {
                   6396:         $roles = $possroles;
                   6397:     } else {
                   6398:         $roles = ['dc','su'];
                   6399:     }
                   6400:     if (ref($possdomains) eq 'ARRAY') {
                   6401:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6402:         foreach my $dom (@{$possdomains}) {
                   6403:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6404:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6405:                 foreach my $role (@{$roles}) {
                   6406:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6407:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6408:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6409:                             return 1 unless (($end && $end < $now) ||
                   6410:                                              ($start && $start > $now));
                   6411:                         }
                   6412:                     }
                   6413:                 }
                   6414:             }
                   6415:         }
                   6416:     } else {
                   6417:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6418:         my $now = time;
1.1170    droeschl 6419: 
1.1172.2.58  raeburn  6420:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6421:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6422:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6423:                 return 1 unless ($tend && $tend < $now)
                   6424:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6425:             }
1.1172.2.23  raeburn  6426:         }
                   6427:     }
1.461     www      6428:     return 0;
1.9       www      6429: }
1.1       albertel 6430: 
1.1172.2.23  raeburn  6431: sub privileged_by_domain {
                   6432:     my ($domains,$roles) = @_;
                   6433:     my %privileged = ();
                   6434:     my $cachetime = 60*60*24;
                   6435:     my $now = time;
                   6436:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6437:         return %privileged;
                   6438:     }
                   6439:     foreach my $dom (@{$domains}) {
                   6440:         next if (ref($privileged{$dom}) eq 'HASH');
                   6441:         my $needroles;
                   6442:         foreach my $role (@{$roles}) {
                   6443:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6444:             if (defined($cached)) {
                   6445:                 if (ref($result) eq 'HASH') {
                   6446:                     $privileged{$dom}{$role} = $result;
                   6447:                 }
                   6448:             } else {
                   6449:                 $needroles = 1;
                   6450:             }
                   6451:         }
                   6452:         if ($needroles) {
                   6453:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6454:             $privileged{$dom} = {};
                   6455:             foreach my $server (keys(%dompersonnel)) {
                   6456:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6457:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6458:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6459:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6460:                         next if ($end && $end < $now);
                   6461:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6462:                             $dompersonnel{$server}{$item};
                   6463:                     }
                   6464:                 }
                   6465:             }
                   6466:             if (ref($privileged{$dom}) eq 'HASH') {
                   6467:                 foreach my $role (@{$roles}) {
                   6468:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6469:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6470:                     } else {
                   6471:                         my %hash = ();
                   6472:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6473:                     }
                   6474:                 }
                   6475:             }
                   6476:         }
                   6477:     }
                   6478:     return %privileged;
                   6479: }
                   6480: 
1.103     harris41 6481: # -------------------------------------------------------- Get user privileges
1.11      www      6482: 
                   6483: sub rolesinit {
1.1169    droeschl 6484:     my ($domain, $username) = @_;
                   6485:     my %userroles = ('user.login.time' => time);
                   6486:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6487: 
                   6488:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6489:     # also, blocking can be triggered by an activating timer
                   6490:     # it's saved in the user's %env.
                   6491:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6492:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6493:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6494:         %timerintchk, %timerintenv);
                   6495: 
1.1162    raeburn  6496:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6497:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6498:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6499:     }
1.1169    droeschl 6500: 
1.1162    raeburn  6501:     foreach my $key (keys(%timerinterval)) {
                   6502:         my ($cid,$rest) = split(/\0/,$key);
                   6503:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6504:     }
1.1169    droeschl 6505: 
1.11      www      6506:     my %allroles=();
1.1162    raeburn  6507:     my %allgroups=();
1.11      www      6508: 
1.1172.2.58  raeburn  6509:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6510:         my $role = $rolesdump{$area};
                   6511:         $area =~ s/\_\w\w$//;
                   6512: 
                   6513:         my ($trole, $tend, $tstart, $group_privs);
                   6514: 
                   6515:         if ($role =~ /^cr/) {
                   6516:         # Custom role, defined by a user 
                   6517:         # e.g., user.role.cr/msu/smith/mynewrole
                   6518:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6519:                 $trole = $1;
                   6520:                 ($tend, $tstart) = split('_', $2);
                   6521:             } else {
                   6522:                 $trole = $role;
                   6523:             }
                   6524:         } elsif ($role =~ m|^gr/|) {
                   6525:         # Role of member in a group, defined within a course/community
                   6526:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6527:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6528:             next if $tstart eq '-1';
                   6529:             ($trole, $group_privs) = split(/\//, $trole);
                   6530:             $group_privs = &unescape($group_privs);
                   6531:         } else {
                   6532:         # Just a normal role, defined in roles.tab
                   6533:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6534:         }
                   6535: 
                   6536:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6537:                  $username);
                   6538:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6539: 
                   6540:         # role expired or not available yet?
                   6541:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6542:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6543: 
                   6544:         next if $area eq '' or $trole eq '';
                   6545: 
                   6546:         my $spec = "$trole.$area";
                   6547:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6548: 
                   6549:         if ($trole =~ /^cr\//) {
                   6550:         # Custom role, defined by a user
                   6551:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6552:         } elsif ($trole eq 'gr') {
                   6553:         # Role of a member in a group, defined within a course/community
                   6554:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6555:             next;
                   6556:         } else {
                   6557:         # Normal role, defined in roles.tab
                   6558:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6559:         }
                   6560: 
                   6561:         my $cid = $tdomain.'_'.$trest;
                   6562:         unless ($firstaccchk{$cid}) {
                   6563:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6564:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6565:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6566:                         $coursetimerstarts{$cid}{$item}; 
                   6567:                 }
                   6568:             }
                   6569:             $firstaccchk{$cid} = 1;
                   6570:         }
                   6571:         unless ($timerintchk{$cid}) {
                   6572:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6573:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6574:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6575:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6576:                 }
1.12      www      6577:             }
1.1169    droeschl 6578:             $timerintchk{$cid} = 1;
1.191     harris41 6579:         }
1.11      www      6580:     }
1.1169    droeschl 6581: 
1.1172.2.91  raeburn  6582:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6583:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6584:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6585:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6586: 
1.1162    raeburn  6587:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6588: }
                   6589: 
1.567     raeburn  6590: sub set_arearole {
1.1172.2.19  raeburn  6591:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6592:     unless ($nolog) {
1.567     raeburn  6593: # log the associated role with the area
1.1172.2.19  raeburn  6594:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6595:     }
1.743     albertel 6596:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6597: }
                   6598: 
                   6599: sub custom_roleprivs {
                   6600:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6601:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6602:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6603:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6604:         my ($rdummy,$roledef)=
                   6605:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6606:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6607:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6608:             if (defined($syspriv)) {
1.1043    raeburn  6609:                 if ($trest =~ /^$match_community$/) {
                   6610:                     $syspriv =~ s/bre\&S//; 
                   6611:                 }
1.567     raeburn  6612:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6613:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6614:             }
                   6615:             if ($tdomain ne '') {
                   6616:                 if (defined($dompriv)) {
                   6617:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6618:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6619:                 }
                   6620:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6621:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6622:                         my $rolename = $1;
                   6623:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6624:                     }
1.567     raeburn  6625:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6626:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6627:                 }
                   6628:             }
                   6629:         }
                   6630:     }
                   6631: }
                   6632: 
1.1172.2.89  raeburn  6633: sub course_adhocrole_privs {
                   6634:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6635:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6636:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6637:         my (%currprivs,%storeprivs);
                   6638:         foreach my $item (split(/:/,$coursepriv)) {
                   6639:             my ($priv,$restrict) = split(/\&/,$item);
                   6640:             $currprivs{$priv} = $restrict;
                   6641:         }
                   6642:         my (%possadd,%possremove,%full);
                   6643:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6644:             my ($priv,$restrict)=split(/\&/,$item);
                   6645:             $full{$priv} = $restrict;
                   6646:         }
                   6647:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6648:              next if ($item eq '');
                   6649:              my ($rule,$rest) = split(/=/,$item);
                   6650:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6651:              foreach my $priv (split(/:/,$rest)) {
                   6652:                  if ($priv ne '') {
                   6653:                      if ($rule eq 'off') {
                   6654:                          $possremove{$priv} = 1;
                   6655:                      } else {
                   6656:                          $possadd{$priv} = 1;
                   6657:                      }
                   6658:                  }
                   6659:              }
                   6660:          }
                   6661:          foreach my $priv (sort(keys(%full))) {
                   6662:              if (exists($currprivs{$priv})) {
                   6663:                  unless (exists($possremove{$priv})) {
                   6664:                      $storeprivs{$priv} = $currprivs{$priv};
                   6665:                  }
                   6666:              } elsif (exists($possadd{$priv})) {
                   6667:                  $storeprivs{$priv} = $full{$priv};
                   6668:              }
                   6669:          }
                   6670:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6671:      }
                   6672:      return $coursepriv;
                   6673: }
                   6674: 
1.678     raeburn  6675: sub group_roleprivs {
                   6676:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6677:     my $access = 1;
                   6678:     my $now = time;
                   6679:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6680:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6681:     if ($access) {
1.811     albertel 6682:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6683:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6684:     }
                   6685: }
1.567     raeburn  6686: 
                   6687: sub standard_roleprivs {
                   6688:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6689:     if (defined($pr{$trole.':s'})) {
                   6690:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6691:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6692:     }
                   6693:     if ($tdomain ne '') {
                   6694:         if (defined($pr{$trole.':d'})) {
                   6695:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6696:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6697:         }
                   6698:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6699:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6700:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6701:         }
                   6702:     }
                   6703: }
                   6704: 
                   6705: sub set_userprivs {
1.1064    raeburn  6706:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6707:     my $author=0;
                   6708:     my $adv=0;
1.1172.2.91  raeburn  6709:     my $rar=0;
1.678     raeburn  6710:     my %grouproles = ();
                   6711:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6712:         my @groupkeys; 
1.1000    raeburn  6713:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6714:             push(@groupkeys,$role);
                   6715:         }
                   6716:         if (ref($groups_roles) eq 'HASH') {
                   6717:             foreach my $key (keys(%{$groups_roles})) {
                   6718:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6719:                     push(@groupkeys,$key);
                   6720:                 }
                   6721:             }
                   6722:         }
                   6723:         if (@groupkeys > 0) {
                   6724:             foreach my $role (@groupkeys) {
                   6725:                 my ($trole,$area,$sec,$extendedarea);
                   6726:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6727:                     $trole = $1;
                   6728:                     $area = $2;
                   6729:                     $sec = $3;
                   6730:                     $extendedarea = $area.$sec;
                   6731:                     if (exists($$allgroups{$area})) {
                   6732:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6733:                             my $spec = $trole.'.'.$extendedarea;
                   6734:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6735:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6736:                         }
1.678     raeburn  6737:                     }
                   6738:                 }
                   6739:             }
                   6740:         }
                   6741:     }
1.800     albertel 6742:     foreach my $group (keys(%grouproles)) {
                   6743:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6744:     }
1.800     albertel 6745:     foreach my $role (keys(%{$allroles})) {
                   6746:         my %thesepriv;
1.941     raeburn  6747:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6748:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6749:             if ($item ne '') {
                   6750:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6751:                 if ($restrictions eq '') {
                   6752:                     $thesepriv{$privilege}='F';
                   6753:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6754:                     $thesepriv{$privilege}.=$restrictions;
                   6755:                 }
                   6756:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6757:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6758:             }
                   6759:         }
                   6760:         my $thesestr='';
1.1104    raeburn  6761:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6762: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6763: 	}
                   6764:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6765:     }
1.1172.2.91  raeburn  6766:     return ($author,$adv,$rar);
1.567     raeburn  6767: }
                   6768: 
1.994     raeburn  6769: sub role_status {
1.1104    raeburn  6770:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6771:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6772:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6773:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6774:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6775:             $$where = '/'.$two;
1.994     raeburn  6776:             $$trolecode=$$role.'.'.$$where;
                   6777:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6778:             $$tstatus='is';
1.1104    raeburn  6779:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6780:                 $$tstatus='future';
1.1034    raeburn  6781:                 if ($$tstart<$now) {
                   6782:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6783:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6784:                             my (%allroles,%allgroups,$group_privs,
                   6785:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6786:                             my %userroles = (
                   6787:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6788:                             );
1.1064    raeburn  6789:                             @rolecodes = ('cm'); 
1.1002    raeburn  6790:                             my $spec=$$role.'.'.$$where;
                   6791:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6792:                             if ($$role =~ /^cr\//) {
                   6793:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6794:                                 push(@rolecodes,'cr');
1.1002    raeburn  6795:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6796:                                 push(@rolecodes,$$role);
1.1002    raeburn  6797:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6798:                                                     $env{'user.name'});
1.1064    raeburn  6799:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6800:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6801:                                 $group_privs = &unescape($group_privs);
                   6802:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6803:                                 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  6804:                                 &get_groups_roles($tdomain,$trest,
                   6805:                                                   \%course_roles,\@rolecodes,
                   6806:                                                   \%groups_roles);
1.1002    raeburn  6807:                             } else {
1.1064    raeburn  6808:                                 push(@rolecodes,$$role);
1.1002    raeburn  6809:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6810:                             }
1.1172.2.91  raeburn  6811:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6812:                                                                    \%groups_roles);
1.1064    raeburn  6813:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6814:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6815:                         }
                   6816:                     }
1.1034    raeburn  6817:                     $$tstatus = 'is';
1.1002    raeburn  6818:                 }
1.994     raeburn  6819:             }
                   6820:             if ($$tend) {
1.1104    raeburn  6821:                 if ($$tend<$update) {
1.994     raeburn  6822:                     $$tstatus='expired';
                   6823:                 } elsif ($$tend<$now) {
                   6824:                     $$tstatus='will_not';
                   6825:                 }
                   6826:             }
                   6827:         }
                   6828:     }
                   6829: }
                   6830: 
1.1104    raeburn  6831: sub get_groups_roles {
                   6832:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6833:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6834:                   (ref($rolecodes) eq 'ARRAY') && 
                   6835:                   (ref($groups_roles) eq 'HASH')); 
                   6836:     if (keys(%{$cdom_courseroles}) > 0) {
                   6837:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6838:         if ($cdom ne '' && $cnum ne '') {
                   6839:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6840:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6841:                     my $crsrole = $1;
                   6842:                     my $crssec = $2;
                   6843:                     if ($crsrole =~ /^cr/) {
                   6844:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6845:                             push(@{$rolecodes},'cr');
                   6846:                         }
                   6847:                     } else {
                   6848:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6849:                             push(@{$rolecodes},$crsrole);
                   6850:                         }
                   6851:                     }
                   6852:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6853:                     if ($crssec ne '') {
                   6854:                         $rolekey .= "/$crssec";
                   6855:                     }
                   6856:                     $rolekey .= './';
                   6857:                     $groups_roles->{$rolekey} = $rolecodes;
                   6858:                 }
                   6859:             }
                   6860:         }
                   6861:     }
                   6862:     return;
                   6863: }
                   6864: 
                   6865: sub delete_env_groupprivs {
                   6866:     my ($where,$courseroles,$possroles) = @_;
                   6867:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6868:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6869:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6870:         %{$courseroles->{$udom}} =
                   6871:             &get_my_roles('','','userroles',['active'],
                   6872:                           $possroles,[$udom],1);
                   6873:     }
                   6874:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6875:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6876:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6877:             my $area = '/'.$cdom.'/'.$cnum;
                   6878:             my $privkey = "user.priv.$crsrole.$area";
                   6879:             if ($crssec ne '') {
                   6880:                 $privkey .= '/'.$crssec;
                   6881:             }
                   6882:             $privkey .= ".$area/$group";
                   6883:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6884:         }
                   6885:     }
                   6886:     return;
                   6887: }
                   6888: 
1.994     raeburn  6889: sub check_adhoc_privs {
1.1172.2.86  raeburn  6890:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6891:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6892:     if ($sec) {
                   6893:         $cckey .= '/'.$sec;
                   6894:     }
1.1172.2.9  raeburn  6895:     my $setprivs;
1.994     raeburn  6896:     if ($env{$cckey}) {
                   6897:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6898:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6899:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6900:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6901:             $setprivs = 1;
1.994     raeburn  6902:         }
                   6903:     } else {
1.1172.2.87  raeburn  6904:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6905:         $setprivs = 1;
1.994     raeburn  6906:     }
1.1172.2.9  raeburn  6907:     return $setprivs;
1.994     raeburn  6908: }
                   6909: 
                   6910: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6911: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6912:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6913:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6914:     if ($sec ne '') {
                   6915:         $area .= '/'.$sec;
                   6916:     }
1.994     raeburn  6917:     my $spec = $role.'.'.$area;
                   6918:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6919:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6920:     my %rolehash = ();
1.1172.2.89  raeburn  6921:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6922:         my $rolename = $1;
1.1172.2.84  raeburn  6923:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6924:         my %domdef = &get_domain_defaults($dcdom);
                   6925:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6926:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6927:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6928:             }
                   6929:         }
1.1172.2.84  raeburn  6930:     } else {
                   6931:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6932:     }
1.1172.2.91  raeburn  6933:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6934:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6935:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1172.2.146.  .1(raebu 6936:22):     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
                   6937:22):             ($caller eq 'tiny')) {
1.1088    raeburn  6938:         &appenv( {'request.role'        => $spec,
                   6939:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6940:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6941:                  }
                   6942:                );
                   6943:         my $tadv=0;
                   6944:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6945:         &appenv({'request.role.adv'    => $tadv});
                   6946:     }
1.994     raeburn  6947: }
                   6948: 
1.12      www      6949: # --------------------------------------------------------------- get interface
                   6950: 
                   6951: sub get {
1.131     albertel 6952:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6953:    my $items='';
1.800     albertel 6954:    foreach my $item (@$storearr) {
                   6955:        $items.=&escape($item).'&';
1.191     harris41 6956:    }
1.12      www      6957:    $items=~s/\&$//;
1.620     albertel 6958:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6959:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6960:    my $uhome=&homeserver($uname,$udomain);
                   6961: 
1.133     albertel 6962:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6963:    my @pairs=split(/\&/,$rep);
1.273     albertel 6964:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6965:      return @pairs;
                   6966:    }
1.15      www      6967:    my %returnhash=();
1.42      www      6968:    my $i=0;
1.800     albertel 6969:    foreach my $item (@$storearr) {
                   6970:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6971:       $i++;
1.191     harris41 6972:    }
1.15      www      6973:    return %returnhash;
1.27      www      6974: }
                   6975: 
                   6976: # --------------------------------------------------------------- del interface
                   6977: 
                   6978: sub del {
1.133     albertel 6979:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6980:    my $items='';
1.800     albertel 6981:    foreach my $item (@$storearr) {
                   6982:        $items.=&escape($item).'&';
1.191     harris41 6983:    }
1.984     neumanie 6984: 
1.27      www      6985:    $items=~s/\&$//;
1.620     albertel 6986:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6987:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6988:    my $uhome=&homeserver($uname,$udomain);
                   6989:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6990: }
                   6991: 
                   6992: # -------------------------------------------------------------- dump interface
                   6993: 
1.1172.2.22  raeburn  6994: sub unserialize {
                   6995:     my ($rep, $escapedkeys) = @_;
                   6996: 
                   6997:     return {} if $rep =~ /^error/;
                   6998: 
                   6999:     my %returnhash=();
                   7000:     foreach my $item (split(/\&/,$rep)) {
                   7001:         my ($key, $value) = split(/=/, $item, 2);
                   7002:         $key = unescape($key) unless $escapedkeys;
                   7003:         next if $key =~ /^error: 2 /;
                   7004:         $returnhash{$key} = &thaw_unescape($value);
                   7005:     }
                   7006:     return \%returnhash;
                   7007: }
                   7008: 
                   7009: # see Lond::dump_with_regexp
                   7010: # if $escapedkeys hash keys won't get unescaped.
1.15      www      7011: sub dump {
1.1172.2.146.  .1(raebu 7012:22):     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
1.755     albertel 7013:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7014:     if (!$uname) { $uname=$env{'user.name'}; }
                   7015:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 7016: 
1.1172.2.55  raeburn  7017:     if ($regexp) {
                   7018:         $regexp=&escape($regexp);
                   7019:     } else {
                   7020:         $regexp='.';
                   7021:     }
1.1172.2.22  raeburn  7022:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   7023:         # user is hosted on this machine
1.1172.2.55  raeburn  7024:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  7025:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  7026:         return %{&unserialize($reply, $escapedkeys)};
                   7027:     }
1.1172.2.146.  .1(raebu 7028:22):     my $rep;
                   7029:22):     if ($encrypt) {
                   7030:22):         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   7031:22):     } else {
                   7032:22):         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   7033:22):     }
1.755     albertel 7034:     my @pairs=split(/\&/,$rep);
                   7035:     my %returnhash=();
1.1098    foxr     7036:     if (!($rep =~ /^error/ )) {
                   7037: 	foreach my $item (@pairs) {
                   7038: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  7039:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     7040: 	    next if ($key =~ /^error: 2 /);
                   7041: 	    $returnhash{$key}=&thaw_unescape($value);
                   7042: 	}
1.755     albertel 7043:     }
                   7044:     return %returnhash;
1.407     www      7045: }
                   7046: 
1.1098    foxr     7047: 
1.717     albertel 7048: # --------------------------------------------------------- dumpstore interface
                   7049: 
                   7050: sub dumpstore {
                   7051:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  7052:    # same as dump but keys must be escaped. They may contain colon separated
                   7053:    # lists of values that may themself contain colons (e.g. symbs).
                   7054:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 7055: }
                   7056: 
1.407     www      7057: # -------------------------------------------------------------- keys interface
                   7058: 
                   7059: sub getkeys {
                   7060:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 7061:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7062:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      7063:    my $uhome=&homeserver($uname,$udomain);
                   7064:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   7065:    my @keyarray=();
1.800     albertel 7066:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  7067:       next if ($key =~ /^error: 2 /);
1.800     albertel 7068:       push(@keyarray,&unescape($key));
1.407     www      7069:    }
                   7070:    return @keyarray;
1.318     matthew  7071: }
                   7072: 
1.319     matthew  7073: # --------------------------------------------------------------- currentdump
                   7074: sub currentdump {
1.328     matthew  7075:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 7076:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   7077:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   7078:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  7079:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  7080:    my $rep;
                   7081: 
                   7082:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   7083:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   7084:                    $courseid)));
                   7085:    } else {
                   7086:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   7087:    }
                   7088: 
1.318     matthew  7089:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  7090:    #
1.318     matthew  7091:    my %returnhash=();
1.319     matthew  7092:    #
                   7093:    if ($rep eq "unknown_cmd") { 
                   7094:        # an old lond will not know currentdump
                   7095:        # Do a dump and make it look like a currentdump
1.822     albertel 7096:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  7097:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   7098:        my %hash = @tmp;
                   7099:        @tmp=();
1.424     matthew  7100:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  7101:    } else {
                   7102:        my @pairs=split(/\&/,$rep);
1.800     albertel 7103:        foreach my $pair (@pairs) {
                   7104:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  7105:            my ($symb,$param) = split(/:/,$key);
                   7106:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 7107:                                                         &thaw_unescape($value);
1.319     matthew  7108:        }
1.191     harris41 7109:    }
1.12      www      7110:    return %returnhash;
1.424     matthew  7111: }
                   7112: 
                   7113: sub convert_dump_to_currentdump{
                   7114:     my %hash = %{shift()};
                   7115:     my %returnhash;
                   7116:     # Code ripped from lond, essentially.  The only difference
                   7117:     # here is the unescaping done by lonnet::dump().  Conceivably
                   7118:     # we might run in to problems with parameter names =~ /^v\./
                   7119:     while (my ($key,$value) = each(%hash)) {
                   7120:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 7121: 	$symb  = &unescape($symb);
                   7122: 	$param = &unescape($param);
1.424     matthew  7123:         next if ($v eq 'version' || $symb eq 'keys');
                   7124:         next if (exists($returnhash{$symb}) &&
                   7125:                  exists($returnhash{$symb}->{$param}) &&
                   7126:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   7127:         $returnhash{$symb}->{$param}=$value;
                   7128:         $returnhash{$symb}->{'v.'.$param}=$v;
                   7129:     }
                   7130:     #
                   7131:     # Remove all of the keys in the hashes which keep track of
                   7132:     # the version of the parameter.
                   7133:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   7134:         # use a foreach because we are going to delete from the hash.
                   7135:         foreach my $key (keys(%$param_hash)) {
                   7136:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   7137:         }
                   7138:     }
                   7139:     return \%returnhash;
1.12      www      7140: }
                   7141: 
1.627     albertel 7142: # ------------------------------------------------------ critical inc interface
                   7143: 
                   7144: sub cinc {
                   7145:     return &inc(@_,'critical');
                   7146: }
                   7147: 
1.449     matthew  7148: # --------------------------------------------------------------- inc interface
                   7149: 
                   7150: sub inc {
1.627     albertel 7151:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7152:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7153:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7154:     my $uhome=&homeserver($uname,$udomain);
                   7155:     my $items='';
                   7156:     if (! ref($store)) {
                   7157:         # got a single value, so use that instead
                   7158:         $items = &escape($store).'=&';
                   7159:     } elsif (ref($store) eq 'SCALAR') {
                   7160:         $items = &escape($$store).'=&';        
                   7161:     } elsif (ref($store) eq 'ARRAY') {
                   7162:         $items = join('=&',map {&escape($_);} @{$store});
                   7163:     } elsif (ref($store) eq 'HASH') {
                   7164:         while (my($key,$value) = each(%{$store})) {
                   7165:             $items.= &escape($key).'='.&escape($value).'&';
                   7166:         }
                   7167:     }
                   7168:     $items=~s/\&$//;
1.627     albertel 7169:     if ($critical) {
                   7170: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7171:     } else {
                   7172: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7173:     }
1.449     matthew  7174: }
                   7175: 
1.12      www      7176: # --------------------------------------------------------------- put interface
                   7177: 
                   7178: sub put {
1.1172.2.146.  .1(raebu 7179:22):    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
1.620     albertel 7180:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7181:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7182:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7183:    my $items='';
1.800     albertel 7184:    foreach my $item (keys(%$storehash)) {
                   7185:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7186:    }
1.12      www      7187:    $items=~s/\&$//;
1.1172.2.146.  .1(raebu 7188:22):    if ($encrypt) {
                   7189:22):        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
                   7190:22):    } else {
                   7191:22):        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
                   7192:22):    }
1.47      www      7193: }
                   7194: 
1.631     albertel 7195: # ------------------------------------------------------------ newput interface
                   7196: 
                   7197: sub newput {
                   7198:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7199:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7200:    if (!$uname) { $uname=$env{'user.name'}; }
                   7201:    my $uhome=&homeserver($uname,$udomain);
                   7202:    my $items='';
                   7203:    foreach my $key (keys(%$storehash)) {
                   7204:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7205:    }
                   7206:    $items=~s/\&$//;
                   7207:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7208: }
                   7209: 
                   7210: # ---------------------------------------------------------  putstore interface
                   7211: 
1.524     raeburn  7212: sub putstore {
1.1172.2.59  raeburn  7213:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7214:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7215:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7216:    my $uhome=&homeserver($uname,$udomain);
                   7217:    my $items='';
1.715     albertel 7218:    foreach my $key (keys(%$storehash)) {
                   7219:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7220:    }
1.715     albertel 7221:    $items=~s/\&$//;
1.716     albertel 7222:    my $esc_symb=&escape($symb);
                   7223:    my $esc_v=&escape($version);
1.715     albertel 7224:    my $reply =
1.716     albertel 7225:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7226: 	      $uhome);
1.1172.2.59  raeburn  7227:    if (($tolog) && ($reply eq 'ok')) {
                   7228:        my $namevalue='';
                   7229:        foreach my $key (keys(%{$storehash})) {
                   7230:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7231:        }
1.1172.2.134  raeburn  7232:        my $ip = &get_requestor_ip();
1.1172.2.135  raeburn  7233:        $namevalue .= 'ip='.&escape($ip).
1.1172.2.59  raeburn  7234:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7235:                      '&version='.$esc_v.
                   7236:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7237:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7238:    }
1.715     albertel 7239:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7240:        # gfall back to way things use to be done
1.715     albertel 7241:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7242: 			    $uname);
1.524     raeburn  7243:    }
1.715     albertel 7244:    return $reply;
                   7245: }
                   7246: 
                   7247: sub old_putstore {
1.716     albertel 7248:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7249:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7250:     if (!$uname) { $uname=$env{'user.name'}; }
                   7251:     my $uhome=&homeserver($uname,$udomain);
                   7252:     my %newstorehash;
1.800     albertel 7253:     foreach my $item (keys(%$storehash)) {
                   7254: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7255: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7256:     }
                   7257:     my $items='';
                   7258:     my %allitems = ();
1.800     albertel 7259:     foreach my $item (keys(%newstorehash)) {
                   7260: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7261: 	    my $key = $1.':keys:'.$2;
                   7262: 	    $allitems{$key} .= $3.':';
                   7263: 	}
1.800     albertel 7264: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7265:     }
1.800     albertel 7266:     foreach my $item (keys(%allitems)) {
                   7267: 	$allitems{$item} =~ s/\:$//;
                   7268: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7269:     }
                   7270:     $items=~s/\&$//;
                   7271:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7272: }
                   7273: 
1.47      www      7274: # ------------------------------------------------------ critical put interface
                   7275: 
                   7276: sub cput {
1.134     albertel 7277:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7278:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7279:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7280:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7281:    my $items='';
1.800     albertel 7282:    foreach my $item (keys(%$storehash)) {
                   7283:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7284:    }
1.47      www      7285:    $items=~s/\&$//;
1.134     albertel 7286:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7287: }
                   7288: 
                   7289: # -------------------------------------------------------------- eget interface
                   7290: 
                   7291: sub eget {
1.133     albertel 7292:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7293:    my $items='';
1.800     albertel 7294:    foreach my $item (@$storearr) {
                   7295:        $items.=&escape($item).'&';
1.191     harris41 7296:    }
1.12      www      7297:    $items=~s/\&$//;
1.620     albertel 7298:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7299:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7300:    my $uhome=&homeserver($uname,$udomain);
                   7301:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7302:    my @pairs=split(/\&/,$rep);
                   7303:    my %returnhash=();
1.42      www      7304:    my $i=0;
1.800     albertel 7305:    foreach my $item (@$storearr) {
                   7306:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7307:       $i++;
1.191     harris41 7308:    }
1.12      www      7309:    return %returnhash;
                   7310: }
                   7311: 
1.667     albertel 7312: # ------------------------------------------------------------ tmpput interface
                   7313: sub tmpput {
1.802     raeburn  7314:     my ($storehash,$server,$context)=@_;
1.667     albertel 7315:     my $items='';
1.800     albertel 7316:     foreach my $item (keys(%$storehash)) {
                   7317: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7318:     }
                   7319:     $items=~s/\&$//;
1.802     raeburn  7320:     if (defined($context)) {
                   7321:         $items .= ':'.&escape($context);
                   7322:     }
1.667     albertel 7323:     return &reply("tmpput:$items",$server);
                   7324: }
                   7325: 
                   7326: # ------------------------------------------------------------ tmpget interface
                   7327: sub tmpget {
1.688     albertel 7328:     my ($token,$server)=@_;
                   7329:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7330:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7331:     my %returnhash;
1.1172.2.85  raeburn  7332:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7333:         return %returnhash;
                   7334:     }
1.667     albertel 7335:     foreach my $item (split(/\&/,$rep)) {
                   7336: 	my ($key,$value)=split(/=/,$item);
                   7337: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7338:     }
                   7339:     return %returnhash;
                   7340: }
                   7341: 
1.1113    raeburn  7342: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7343: sub tmpdel {
                   7344:     my ($token,$server)=@_;
                   7345:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7346:     return &reply("tmpdel:$token",$server);
                   7347: }
                   7348: 
1.1172.2.13  raeburn  7349: # ------------------------------------------------------------ get_timebased_id
                   7350: 
                   7351: sub get_timebased_id {
                   7352:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7353:         $maxtries) = @_;
                   7354:     my ($newid,$error,$dellock);
                   7355:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7356:         return ('','ok','invalid call to get suffix');
                   7357:     }
                   7358: 
                   7359: # set defaults for any optional args for which values were not supplied
                   7360:     if ($who eq '') {
                   7361:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7362:     }
                   7363:     if (!$locktries) {
                   7364:         $locktries = 3;
                   7365:     }
                   7366:     if (!$maxtries) {
                   7367:         $maxtries = 10;
                   7368:     }
                   7369: 
                   7370:     if (($cdom eq '') || ($cnum eq '')) {
                   7371:         if ($env{'request.course.id'}) {
                   7372:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7373:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7374:         }
                   7375:         if (($cdom eq '') || ($cnum eq '')) {
                   7376:             return ('','ok','call to get suffix not in course context');
                   7377:         }
                   7378:     }
                   7379: 
                   7380: # construct locking item
                   7381:     my $lockhash = {
                   7382:                       $prefix."\0".'locked_'.$keyid => $who,
                   7383:                    };
                   7384:     my $tries = 0;
                   7385: 
                   7386: # attempt to get lock on nohist_$namespace file
                   7387:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7388:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7389:         $tries ++;
                   7390:         sleep 1;
                   7391:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7392:     }
                   7393: 
                   7394: # attempt to get unique identifier, based on current timestamp
                   7395:     if ($gotlock eq 'ok') {
                   7396:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7397:         my $id = time;
                   7398:         $newid = $id;
1.1172.2.56  raeburn  7399:         if ($idtype eq 'addcode') {
                   7400:             $newid .= &sixnum_code();
                   7401:         }
1.1172.2.13  raeburn  7402:         my $idtries = 0;
                   7403:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7404:             if ($idtype eq 'concat') {
                   7405:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7406:             } elsif ($idtype eq 'addcode') {
                   7407:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7408:             } else {
                   7409:                 $newid ++;
                   7410:             }
                   7411:             $idtries ++;
                   7412:         }
                   7413:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7414:             my %new_item =  (
                   7415:                               $prefix."\0".$newid => $who,
                   7416:                             );
                   7417:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7418:                                                  $cdom,$cnum);
                   7419:             if ($putresult ne 'ok') {
                   7420:                 undef($newid);
                   7421:                 $error = 'error saving new item: '.$putresult;
                   7422:             }
                   7423:         } else {
1.1172.2.56  raeburn  7424:              undef($newid);
1.1172.2.13  raeburn  7425:              $error = ('error: no unique suffix available for the new item ');
                   7426:         }
                   7427: #  remove lock
                   7428:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7429:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7430:     } else {
                   7431:         $error = "error: could not obtain lockfile\n";
                   7432:         $dellock = 'ok';
1.1172.2.58  raeburn  7433:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7434:             $dellock = 'nolock';
                   7435:         }
1.1172.2.13  raeburn  7436:     }
                   7437:     return ($newid,$dellock,$error);
                   7438: }
                   7439: 
1.1172.2.56  raeburn  7440: sub sixnum_code {
                   7441:     my $code;
                   7442:     for (0..6) {
                   7443:         $code .= int( rand(9) );
                   7444:     }
                   7445:     return $code;
                   7446: }
                   7447: 
1.765     albertel 7448: # -------------------------------------------------- portfolio access checking
                   7449: 
                   7450: sub portfolio_access {
1.1172.2.77  raeburn  7451:     my ($requrl,$clientip) = @_;
1.765     albertel 7452:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7453:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7454:     if ($result) {
                   7455:         my %setters;
                   7456:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1172.2.142  raeburn  7457:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
                   7458:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
                   7459:             if (($startblock && $endblock) || ($by_ip))  {
1.814     raeburn  7460:                 return 'B';
                   7461:             }
                   7462:         } else {
1.1172.2.142  raeburn  7463:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdo) =
                   7464:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   7465:             if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  7466:                 return 'B';
                   7467:             }
                   7468:         }
                   7469:     }
1.765     albertel 7470:     if ($result eq 'ok') {
1.766     albertel 7471:        return 'F';
1.765     albertel 7472:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7473:        return 'A';
1.765     albertel 7474:     }
1.766     albertel 7475:     return '';
1.765     albertel 7476: }
                   7477: 
                   7478: sub get_portfolio_access {
1.1172.2.77  raeburn  7479:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7480: 
                   7481:     if (!ref($access_hash)) {
                   7482: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7483: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7484: 						   $file_name);
                   7485: 	$access_hash = $access_controls{$file_name};
                   7486:     }
                   7487: 
1.1172.2.77  raeburn  7488:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7489:     my $now = time;
                   7490:     if (ref($access_hash) eq 'HASH') {
                   7491:         foreach my $key (keys(%{$access_hash})) {
                   7492:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7493:             if ($start > $now) {
                   7494:                 next;
                   7495:             }
                   7496:             if ($end && $end<$now) {
                   7497:                 next;
                   7498:             }
                   7499:             if ($scope eq 'public') {
                   7500:                 $public = $key;
                   7501:                 last;
                   7502:             } elsif ($scope eq 'guest') {
                   7503:                 $guest = $key;
                   7504:             } elsif ($scope eq 'domains') {
                   7505:                 push(@domains,$key);
                   7506:             } elsif ($scope eq 'users') {
                   7507:                 push(@users,$key);
                   7508:             } elsif ($scope eq 'course') {
                   7509:                 push(@courses,$key);
                   7510:             } elsif ($scope eq 'group') {
                   7511:                 push(@groups,$key);
1.1172.2.77  raeburn  7512:             } elsif ($scope eq 'ip') {
                   7513:                 push(@ips,$key);
1.765     albertel 7514:             }
                   7515:         }
                   7516:         if ($public) {
                   7517:             return 'ok';
1.1172.2.77  raeburn  7518:         } elsif (@ips > 0) {
                   7519:             my $allowed;
                   7520:             foreach my $ipkey (@ips) {
                   7521:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7522:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7523:                         $allowed = 1;
                   7524:                         last;
                   7525:                     }
                   7526:                 }
                   7527:             }
                   7528:             if ($allowed) {
                   7529:                 return 'ok';
                   7530:             }
1.765     albertel 7531:         }
                   7532:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7533:             if ($guest) {
                   7534:                 return $guest;
                   7535:             }
                   7536:         } else {
                   7537:             if (@domains > 0) {
                   7538:                 foreach my $domkey (@domains) {
                   7539:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7540:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7541:                             return 'ok';
                   7542:                         }
                   7543:                     }
                   7544:                 }
                   7545:             }
                   7546:             if (@users > 0) {
                   7547:                 foreach my $userkey (@users) {
1.865     raeburn  7548:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7549:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7550:                             if (ref($item) eq 'HASH') {
                   7551:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7552:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7553:                                     return 'ok';
                   7554:                                 }
                   7555:                             }
                   7556:                         }
                   7557:                     } 
1.765     albertel 7558:                 }
                   7559:             }
                   7560:             my %roleshash;
                   7561:             my @courses_and_groups = @courses;
                   7562:             push(@courses_and_groups,@groups); 
                   7563:             if (@courses_and_groups > 0) {
                   7564:                 my (%allgroups,%allroles); 
                   7565:                 my ($start,$end,$role,$sec,$group);
                   7566:                 foreach my $envkey (%env) {
1.1060    raeburn  7567:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7568:                         my $cid = $2.'_'.$3; 
                   7569:                         if ($1 eq 'gr') {
                   7570:                             $group = $4;
                   7571:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7572:                         } else {
                   7573:                             if ($4 eq '') {
                   7574:                                 $sec = 'none';
                   7575:                             } else {
                   7576:                                 $sec = $4;
                   7577:                             }
                   7578:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7579:                         }
1.811     albertel 7580:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7581:                         my $cid = $2.'_'.$3;
                   7582:                         if ($4 eq '') {
                   7583:                             $sec = 'none';
                   7584:                         } else {
                   7585:                             $sec = $4;
                   7586:                         }
                   7587:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7588:                     }
                   7589:                 }
                   7590:                 if (keys(%allroles) == 0) {
                   7591:                     return;
                   7592:                 }
                   7593:                 foreach my $key (@courses_and_groups) {
                   7594:                     my %content = %{$$access_hash{$key}};
                   7595:                     my $cnum = $content{'number'};
                   7596:                     my $cdom = $content{'domain'};
                   7597:                     my $cid = $cdom.'_'.$cnum;
                   7598:                     if (!exists($allroles{$cid})) {
                   7599:                         next;
                   7600:                     }    
                   7601:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7602:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7603:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7604:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7605:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7606:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7607:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7608:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7609:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7610:                                         if (grep/^all$/,@sections) {
                   7611:                                             return 'ok';
                   7612:                                         } else {
                   7613:                                             if (grep/^$sec$/,@sections) {
                   7614:                                                 return 'ok';
                   7615:                                             }
                   7616:                                         }
                   7617:                                     }
                   7618:                                 }
                   7619:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7620:                                     if (grep/^none$/,@groups) {
                   7621:                                         return 'ok';
                   7622:                                     }
                   7623:                                 } else {
                   7624:                                     if (grep/^all$/,@groups) {
                   7625:                                         return 'ok';
                   7626:                                     } 
                   7627:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7628:                                         if (grep/^$group$/,@groups) {
                   7629:                                             return 'ok';
                   7630:                                         }
                   7631:                                     }
                   7632:                                 } 
                   7633:                             }
                   7634:                         }
                   7635:                     }
                   7636:                 }
                   7637:             }
                   7638:             if ($guest) {
                   7639:                 return $guest;
                   7640:             }
                   7641:         }
                   7642:     }
                   7643:     return;
                   7644: }
                   7645: 
                   7646: sub course_group_datechecker {
                   7647:     my ($dates,$now,$status) = @_;
                   7648:     my ($start,$end) = split(/\./,$dates);
                   7649:     if (!$start && !$end) {
                   7650:         return 'ok';
                   7651:     }
                   7652:     if (grep/^active$/,@{$status}) {
                   7653:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7654:             return 'ok';
                   7655:         }
                   7656:     }
                   7657:     if (grep/^previous$/,@{$status}) {
                   7658:         if ($end > $now ) {
                   7659:             return 'ok';
                   7660:         }
                   7661:     }
                   7662:     if (grep/^future$/,@{$status}) {
                   7663:         if ($start > $now) {
                   7664:             return 'ok';
                   7665:         }
                   7666:     }
                   7667:     return; 
                   7668: }
                   7669: 
                   7670: sub parse_portfolio_url {
                   7671:     my ($url) = @_;
                   7672: 
                   7673:     my ($type,$udom,$unum,$group,$file_name);
                   7674:     
1.823     albertel 7675:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7676: 	$type = 1;
                   7677:         $udom = $1;
                   7678:         $unum = $2;
                   7679:         $file_name = $3;
1.823     albertel 7680:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7681: 	$type = 2;
                   7682:         $udom = $1;
                   7683:         $unum = $2;
                   7684:         $group = $3;
                   7685:         $file_name = $3.'/'.$4;
                   7686:     }
                   7687:     if (wantarray) {
                   7688: 	return ($type,$udom,$unum,$file_name,$group);
                   7689:     }
                   7690:     return $type;
                   7691: }
                   7692: 
                   7693: sub is_portfolio_url {
                   7694:     my ($url) = @_;
                   7695:     return scalar(&parse_portfolio_url($url));
                   7696: }
                   7697: 
1.798     raeburn  7698: sub is_portfolio_file {
                   7699:     my ($file) = @_;
1.820     raeburn  7700:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7701:         return 1;
                   7702:     }
                   7703:     return;
                   7704: }
                   7705: 
1.976     raeburn  7706: sub usertools_access {
1.1084    raeburn  7707:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7708:     my ($access,%tools);
                   7709:     if ($context eq '') {
                   7710:         $context = 'tools';
                   7711:     }
                   7712:     if ($context eq 'requestcourses') {
                   7713:         %tools = (
                   7714:                       official   => 1,
                   7715:                       unofficial => 1,
1.1006    raeburn  7716:                       community  => 1,
1.1172.2.37  raeburn  7717:                       textbook   => 1,
1.985     raeburn  7718:                  );
1.1172.2.9  raeburn  7719:     } elsif ($context eq 'requestauthor') {
                   7720:         %tools = (
                   7721:                       requestauthor => 1,
                   7722:                  );
1.985     raeburn  7723:     } else {
                   7724:         %tools = (
                   7725:                       aboutme   => 1,
                   7726:                       blog      => 1,
1.1172.2.6  raeburn  7727:                       webdav    => 1,
1.985     raeburn  7728:                       portfolio => 1,
                   7729:                  );
                   7730:     }
1.976     raeburn  7731:     return if (!defined($tools{$tool}));
                   7732: 
1.1172.2.35  raeburn  7733:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7734:         $udom = $env{'user.domain'};
                   7735:         $uname = $env{'user.name'};
                   7736:     }
                   7737: 
1.978     raeburn  7738:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7739:         if ($action ne 'reload') {
1.985     raeburn  7740:             if ($context eq 'requestcourses') {
                   7741:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7742:             } elsif ($context eq 'requestauthor') {
                   7743:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7744:             } else {
                   7745:                 return $env{'environment.availabletools.'.$tool};
                   7746:             }
                   7747:         }
1.976     raeburn  7748:     }
                   7749: 
1.1172.2.9  raeburn  7750:     my ($toolstatus,$inststatus,$envkey);
                   7751:     if ($context eq 'requestauthor') {
                   7752:         $envkey = $context;
                   7753:     } else {
                   7754:         $envkey = $context.'.'.$tool;
                   7755:     }
1.976     raeburn  7756: 
1.985     raeburn  7757:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7758:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7759:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7760:         $inststatus = $env{'environment.inststatus'};
                   7761:     } else {
1.1084    raeburn  7762:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7763:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7764:             $inststatus = $userenvref->{'inststatus'};
                   7765:         } else {
1.1172.2.9  raeburn  7766:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7767:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7768:             $inststatus = $userenv{'inststatus'};
                   7769:         }
1.976     raeburn  7770:     }
                   7771: 
                   7772:     if ($toolstatus ne '') {
                   7773:         if ($toolstatus) {
                   7774:             $access = 1;
                   7775:         } else {
                   7776:             $access = 0;
                   7777:         }
                   7778:         return $access;
                   7779:     }
                   7780: 
1.1084    raeburn  7781:     my ($is_adv,%domdef);
                   7782:     if (ref($is_advref) eq 'HASH') {
                   7783:         $is_adv = $is_advref->{'is_adv'};
                   7784:     } else {
                   7785:         $is_adv = &is_advanced_user($udom,$uname);
                   7786:     }
                   7787:     if (ref($domdefref) eq 'HASH') {
                   7788:         %domdef = %{$domdefref};
                   7789:     } else {
                   7790:         %domdef = &get_domain_defaults($udom);
                   7791:     }
1.976     raeburn  7792:     if (ref($domdef{$tool}) eq 'HASH') {
                   7793:         if ($is_adv) {
                   7794:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7795:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7796:                     $access = 1;
                   7797:                 } else {
                   7798:                     $access = 0;
                   7799:                 }
                   7800:                 return $access;
                   7801:             }
                   7802:         }
                   7803:         if ($inststatus ne '') {
                   7804:             my ($hasaccess,$hasnoaccess);
                   7805:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7806:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7807:                     if ($domdef{$tool}{$affiliation}) {
                   7808:                         $hasaccess = 1;
                   7809:                     } else {
                   7810:                         $hasnoaccess = 1;
                   7811:                     }
                   7812:                 }
                   7813:             }
                   7814:             if ($hasaccess || $hasnoaccess) {
                   7815:                 if ($hasaccess) {
                   7816:                     $access = 1;
                   7817:                 } elsif ($hasnoaccess) {
                   7818:                     $access = 0; 
                   7819:                 }
                   7820:                 return $access;
                   7821:             }
                   7822:         } else {
                   7823:             if ($domdef{$tool}{'default'} ne '') {
                   7824:                 if ($domdef{$tool}{'default'}) {
                   7825:                     $access = 1;
                   7826:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7827:                     $access = 0;
                   7828:                 }
                   7829:                 return $access;
                   7830:             }
                   7831:         }
                   7832:     } else {
1.1172.2.6  raeburn  7833:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7834:             $access = 1;
                   7835:         } else {
                   7836:             $access = 0;
                   7837:         }
1.976     raeburn  7838:         return $access;
                   7839:     }
                   7840: }
                   7841: 
1.1050    raeburn  7842: sub is_course_owner {
                   7843:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7844:     if (($udom eq '') || ($uname eq '')) {
                   7845:         $udom = $env{'user.domain'};
                   7846:         $uname = $env{'user.name'};
                   7847:     }
                   7848:     unless (($udom eq '') || ($uname eq '')) {
                   7849:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7850:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7851:                 return 1;
                   7852:             } else {
                   7853:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7854:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7855:                     return 1;
                   7856:                 }
                   7857:             }
                   7858:         }
                   7859:     }
                   7860:     return;
                   7861: }
                   7862: 
1.976     raeburn  7863: sub is_advanced_user {
                   7864:     my ($udom,$uname) = @_;
1.1085    raeburn  7865:     if ($udom ne '' && $uname ne '') {
                   7866:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7867:             if (wantarray) {
                   7868:                 return ($env{'user.adv'},$env{'user.author'});
                   7869:             } else {
                   7870:                 return $env{'user.adv'};
                   7871:             }
1.1085    raeburn  7872:         }
                   7873:     }
1.976     raeburn  7874:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7875:     my %allroles;
1.1128    raeburn  7876:     my ($is_adv,$is_author);
1.976     raeburn  7877:     foreach my $role (keys(%roleshash)) {
                   7878:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7879:         my $area = '/'.$tdomain.'/'.$trest;
                   7880:         if ($sec ne '') {
                   7881:             $area .= '/'.$sec;
                   7882:         }
                   7883:         if (($area ne '') && ($trole ne '')) {
                   7884:             my $spec=$trole.'.'.$area;
                   7885:             if ($trole =~ /^cr\//) {
                   7886:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7887:             } elsif ($trole ne 'gr') {
                   7888:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7889:             }
1.1128    raeburn  7890:             if ($trole eq 'au') {
                   7891:                 $is_author = 1;
                   7892:             }
1.976     raeburn  7893:         }
                   7894:     }
                   7895:     foreach my $role (keys(%allroles)) {
                   7896:         last if ($is_adv);
                   7897:         foreach my $item (split(/:/,$allroles{$role})) {
                   7898:             if ($item ne '') {
                   7899:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7900:                 if ($privilege eq 'adv') {
                   7901:                     $is_adv = 1;
                   7902:                     last;
                   7903:                 }
                   7904:             }
                   7905:         }
                   7906:     }
1.1128    raeburn  7907:     if (wantarray) {
                   7908:         return ($is_adv,$is_author);
                   7909:     }
1.976     raeburn  7910:     return $is_adv;
                   7911: }
1.798     raeburn  7912: 
1.1035    raeburn  7913: sub check_can_request {
1.1036    raeburn  7914:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7915:     my $canreq = 0;
                   7916:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7917:     my @options = ('approval','validate','autolimit');
                   7918:     my $optregex = join('|',@options);
                   7919:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7920:         foreach my $type (@{$types}) {
                   7921:             if (&usertools_access($env{'user.name'},
                   7922:                                   $env{'user.domain'},
                   7923:                                   $type,undef,'requestcourses')) {
                   7924:                 $canreq ++;
1.1036    raeburn  7925:                 if (ref($request_domains) eq 'HASH') {
                   7926:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7927:                 }
1.1035    raeburn  7928:                 if ($dom eq $env{'user.domain'}) {
                   7929:                     $can_request->{$type} = 1;
                   7930:                 }
                   7931:             }
                   7932:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7933:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7934:                 if (@curr > 0) {
1.1036    raeburn  7935:                     foreach my $item (@curr) {
                   7936:                         if (ref($request_domains) eq 'HASH') {
                   7937:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7938:                             if ($otherdom ne '') {
                   7939:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7940:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7941:                                         push(@{$request_domains->{$type}},$otherdom);
                   7942:                                     }
                   7943:                                 } else {
                   7944:                                     push(@{$request_domains->{$type}},$otherdom);
                   7945:                                 }
                   7946:                             }
                   7947:                         }
                   7948:                     }
                   7949:                     unless($dom eq $env{'user.domain'}) {
                   7950:                         $canreq ++;
1.1035    raeburn  7951:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7952:                             $can_request->{$type} = 1;
                   7953:                         }
                   7954:                     }
                   7955:                 }
                   7956:             }
                   7957:         }
                   7958:     }
                   7959:     return $canreq;
                   7960: }
                   7961: 
1.341     www      7962: # ---------------------------------------------- Custom access rule evaluation
                   7963: 
                   7964: sub customaccess {
                   7965:     my ($priv,$uri)=@_;
1.807     albertel 7966:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7967:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7968:     $udom = &LONCAPA::clean_domain($udom);
                   7969:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7970:     my $access=0;
1.800     albertel 7971:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7972: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7973: 	if ($type eq 'user') {
                   7974: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7975: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7976: 		if ($tdom) {
                   7977: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7978: 		}
1.896     albertel 7979: 		if ($tuname) {
                   7980: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7981: 		}
                   7982: 		$access=($effect eq 'allow');
                   7983: 		last;
                   7984: 	    }
                   7985: 	} else {
                   7986: 	    if ($role) {
                   7987: 		if ($role ne $urole) { next; }
                   7988: 	    }
                   7989: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7990: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7991: 		if ($tdom) {
                   7992: 		    if ($tdom ne $udom) { next; }
                   7993: 		}
                   7994: 		if ($tcrs) {
                   7995: 		    if ($tcrs ne $ucrs) { next; }
                   7996: 		}
                   7997: 		if ($tsec) {
                   7998: 		    if ($tsec ne $usec) { next; }
                   7999: 		}
                   8000: 		$access=($effect eq 'allow');
                   8001: 		last;
                   8002: 	    }
                   8003: 	    if ($realm eq '' && $role eq '') {
                   8004: 		$access=($effect eq 'allow');
                   8005: 	    }
1.402     bowersj2 8006: 	}
1.341     www      8007:     }
                   8008:     return $access;
                   8009: }
                   8010: 
1.103     harris41 8011: # ------------------------------------------------- Check for a user privilege
1.12      www      8012: 
                   8013: sub allowed {
1.1172.2.146.  .1(raebu 8014:22):     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
1.705     albertel 8015:     my $ver_orguri=$uri;
1.439     www      8016:     $uri=&deversion($uri);
1.152     www      8017:     my $orguri=$uri;
1.52      www      8018:     $uri=&declutter($uri);
1.809     raeburn  8019: 
1.810     raeburn  8020:     if ($priv eq 'evb') {
1.1172.2.146.  .3(raebu 8021:22): # Evade communication block restrictions for specified role in a course or domain
1.810     raeburn  8022:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   8023:             return $1;
                   8024:         } else {
                   8025:             return;
                   8026:         }
                   8027:     }
                   8028: 
1.620     albertel 8029:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      8030: # Free bre access to adm and meta resources
1.1172.2.146.  .1(raebu 8031:22):     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
1.769     albertel 8032: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   8033: 	&& ($priv eq 'bre')) {
1.14      www      8034: 	return 'F';
1.159     www      8035:     }
                   8036: 
1.545     banghart 8037: # Free bre access to user's own portfolio contents
1.714     raeburn  8038:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  8039:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  8040: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  8041:         my %setters;
1.1172.2.142  raeburn  8042:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   8043:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   8044:         if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  8045:             return 'B';
                   8046:         } else {
                   8047:             return 'F';
                   8048:         }
1.545     banghart 8049:     }
                   8050: 
1.762     raeburn  8051: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  8052:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   8053:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   8054:         if (exists($env{'request.course.id'})) {
                   8055:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8056:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8057:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   8058:                 my $courseprivid=$env{'request.course.id'};
                   8059:                 $courseprivid=~s/\_/\//;
                   8060:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   8061:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   8062:                     return $1; 
1.762     raeburn  8063:                 } else {
                   8064:                     if ($env{'request.course.sec'}) {
                   8065:                         $courseprivid.='/'.$env{'request.course.sec'};
                   8066:                     }
                   8067:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   8068:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   8069:                         return $2;
                   8070:                     }
1.714     raeburn  8071:                 }
                   8072:             }
                   8073:         }
                   8074:     }
                   8075: 
1.159     www      8076: # Free bre to public access
                   8077: 
                   8078:     if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8079:22):         my $copyright;
                   8080:22):         unless ($uri =~ /ext\.tool/) {
                   8081:22):             $copyright=&metadata($uri,'copyright');
                   8082:22):         }
1.620     albertel 8083: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      8084:            return 'F'; 
                   8085:         }
1.238     www      8086:         if ($copyright eq 'priv') {
                   8087:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8088: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      8089: 		return '';
                   8090:             }
                   8091:         }
                   8092:         if ($copyright eq 'domain') {
                   8093:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8094: 	    unless (($env{'user.domain'} eq $1) ||
                   8095:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      8096: 		return '';
                   8097:             }
1.262     matthew  8098:         }
1.620     albertel 8099:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  8100:             # Library role, so allow browsing of resources in this domain.
                   8101:             return 'F';
1.238     www      8102:         }
1.341     www      8103:         if ($copyright eq 'custom') {
                   8104: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   8105:         }
1.14      www      8106:     }
1.264     matthew  8107:     # Domain coordinator is trying to create a course
1.620     albertel 8108:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  8109:         # uri is the requested domain in this case.
                   8110:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  8111:         # a role of dc for the domain in question.
1.620     albertel 8112:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  8113:     }
1.29      www      8114: 
1.52      www      8115:     my $thisallowed='';
                   8116:     my $statecond=0;
                   8117:     my $courseprivid='';
                   8118: 
1.1039    raeburn  8119:     my $ownaccess;
1.1043    raeburn  8120:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  8121:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   8122:         if ($uri eq '') {
                   8123:             $ownaccess = 1;
                   8124:         } else {
                   8125:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   8126:                 my $udom = $env{'user.domain'};
                   8127:                 my $uname = $env{'user.name'};
                   8128:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   8129:                     $ownaccess = 1;
1.1040    raeburn  8130:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  8131:                     unless ($uri =~ m{\.\./}) {
                   8132:                         $ownaccess = 1;
                   8133:                     }
                   8134:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   8135:                     my $now = time;
                   8136:                     if ($uri =~ m{^([^/]+)/?$}) {
                   8137:                         my $adom = $1;
                   8138:                         foreach my $key (keys(%env)) {
1.1042    raeburn  8139:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1172.2.142  raeburn  8140:                                 my ($start,$end) = split(/\./,$env{$key});
                   8141:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1039    raeburn  8142:                                     $ownaccess = 1;
                   8143:                                     last;
                   8144:                                 }
                   8145:                             }
                   8146:                         }
                   8147:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8148:                         my $adom = $1;
                   8149:                         my $aname = $2;
1.1042    raeburn  8150:                         foreach my $role ('ca','aa') { 
                   8151:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8152:                                 my ($start,$end) =
1.1172.2.142  raeburn  8153:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
                   8154:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1042    raeburn  8155:                                     $ownaccess = 1;
                   8156:                                     last;
                   8157:                                 }
1.1039    raeburn  8158:                             }
                   8159:                         }
                   8160:                     }
                   8161:                 }
                   8162:             }
                   8163:         }
                   8164:     }
                   8165: 
1.52      www      8166: # Course
                   8167: 
1.620     albertel 8168:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8169:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8170:             $thisallowed.=$1;
                   8171:         }
1.52      www      8172:     }
1.29      www      8173: 
1.52      www      8174: # Domain
                   8175: 
1.620     albertel 8176:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8177:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8178:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8179:             $thisallowed.=$1;
                   8180:         }
1.12      www      8181:     }
1.52      www      8182: 
1.1141    raeburn  8183: # User who is not author or co-author might still be able to edit
                   8184: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8185:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8186:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8187:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8188:             $thisallowed.=$1;
                   8189:         }
                   8190:     }
                   8191: 
1.52      www      8192: # Course: uri itself is a course
1.66      www      8193:     my $courseuri=$uri;
                   8194:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8195:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8196: 
1.620     albertel 8197:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8198:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  8199:         if ($priv eq 'mip') {
                   8200:             my $rem = $1;
                   8201:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8202:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8203:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8204:                 if ($cdom ne '') {
                   8205:                     my %passwdconf = &get_passwdconf($cdom);
                   8206:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8207:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8208:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8209:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8210:                                 unless (@inststatuses) {
                   8211:                                     @inststatuses = ('default');
                   8212:                                 }
                   8213:                                 foreach my $status (@inststatuses) {
                   8214:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8215:                                         $thisallowed.=$rem;
                   8216:                                     }
                   8217:                                 }
                   8218:                             }
                   8219:                         }
                   8220:                     }
                   8221:                 }
                   8222:             }
                   8223:         } else {
                   8224:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8225:                 $thisallowed.=$1;
                   8226:             }
1.1039    raeburn  8227:         }
1.12      www      8228:     }
1.29      www      8229: 
1.665     albertel 8230: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8231: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8232:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8233: 	$thisallowed='';
1.671     raeburn  8234:         my ($match)=&is_on_map($uri);
                   8235:         if ($match) {
                   8236:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8237:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  8238:                 my $value = $1;
1.1172.2.146.  .1(raebu 8239:22):                 my $deeplinkblock;
                   8240:22):                 unless ($nodeeplinkcheck) {
                   8241:22):                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8242:22):                 }
                   8243:22):                 if ($deeplinkblock) {
                   8244:22):                     $thisallowed='D';
                   8245:22):                 } elsif ($noblockcheck) {
1.1172.2.65  raeburn  8246:                     $thisallowed.=$value;
1.1162    raeburn  8247:                 } else {
1.1172.2.126  raeburn  8248:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8249:                     if (@blockers > 0) {
                   8250:                         $thisallowed = 'B';
                   8251:                     } else {
                   8252:                         $thisallowed.=$value;
                   8253:                     }
1.1162    raeburn  8254:                 }
1.671     raeburn  8255:             }
                   8256:         } else {
1.705     albertel 8257:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8258:             if ($refuri) {
                   8259:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8260:                     $thisallowed='F';
1.671     raeburn  8261:                 } else {
                   8262:                     $refuri=&declutter($refuri);
                   8263:                     my ($match) = &is_on_map($refuri);
                   8264:                     if ($match) {
1.1172.2.146.  .1(raebu 8265:22):                         my $deeplinkblock;
                   8266:22):                         unless ($nodeeplinkcheck) {
                   8267:22):                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8268:22):                         }
                   8269:22):                         if ($deeplinkblock) {
                   8270:22):                             $thisallowed='D';
                   8271:22):                         } elsif ($noblockcheck) {
1.1162    raeburn  8272:                             $thisallowed='F';
1.1172.2.65  raeburn  8273:                         } else {
1.1172.2.127  raeburn  8274:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8275:                             if (@blockers > 0) {
                   8276:                                 $thisallowed = 'B';
                   8277:                             } else {
                   8278:                                 $thisallowed='F';
                   8279:                             }
1.1162    raeburn  8280:                         }
1.671     raeburn  8281:                     }
1.669     raeburn  8282:                 }
1.671     raeburn  8283:             }
                   8284:         }
1.314     www      8285:     }
1.492     albertel 8286: 
1.766     albertel 8287:     if ($priv eq 'bre'
                   8288: 	&& $thisallowed ne 'F' 
                   8289: 	&& $thisallowed ne '2'
                   8290: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8291: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8292:     }
                   8293:     
1.52      www      8294: # Full access at system, domain or course-wide level? Exit.
1.29      www      8295:     if ($thisallowed=~/F/) {
                   8296: 	return 'F';
                   8297:     }
                   8298: 
1.52      www      8299: # If this is generating or modifying users, exit with special codes
1.29      www      8300: 
1.643     www      8301:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8302: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8303: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8304: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8305: 	    unless ($auname) { return $thisallowed; }
                   8306: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8307: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8308: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8309: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8310: 	}
1.52      www      8311: 	return $thisallowed;
                   8312:     }
                   8313: #
1.103     harris41 8314: # Gathered so far: system, domain and course wide privileges
1.52      www      8315: #
                   8316: # Course: See if uri or referer is an individual resource that is part of 
                   8317: # the course
                   8318: 
1.620     albertel 8319:     if ($env{'request.course.id'}) {
1.232     www      8320: 
1.1172.2.115  raeburn  8321: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8322: 
                   8323:         if ($priv eq 'mip') {
                   8324:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8325:                 return $thisallowed;
                   8326:             } else {
                   8327:                 return '';
                   8328:             }
                   8329:         }
                   8330: 
1.620     albertel 8331:        $courseprivid=$env{'request.course.id'};
                   8332:        if ($env{'request.course.sec'}) {
                   8333:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8334:        }
                   8335:        $courseprivid=~s/\_/\//;
                   8336:        my $checkreferer=1;
1.232     www      8337:        my ($match,$cond)=&is_on_map($uri);
                   8338:        if ($match) {
                   8339:            $statecond=$cond;
1.620     albertel 8340:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8341:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8342:                my $value = $1;
                   8343:                if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8344:22):                    my $deeplinkblock;
                   8345:22):                    unless ($nodeeplinkcheck) {
                   8346:22):                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8347:22):                    }
                   8348:22):                    if ($deeplinkblock) {
                   8349:22):                        $thisallowed = 'D';
                   8350:22):                    } elsif ($noblockcheck) {
1.1162    raeburn  8351:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8352:                    } else {
1.1172.2.126  raeburn  8353:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8354:                        if (@blockers > 0) {
                   8355:                            $thisallowed = 'B';
                   8356:                        } else {
                   8357:                            $thisallowed.=$value;
                   8358:                        }
1.1162    raeburn  8359:                    }
                   8360:                } else {
                   8361:                    $thisallowed.=$value;
                   8362:                }
1.52      www      8363:                $checkreferer=0;
                   8364:            }
1.29      www      8365:        }
1.1172.2.126  raeburn  8366: 
1.148     www      8367:        if ($checkreferer) {
1.620     albertel 8368: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8369:             unless ($refuri) {
1.800     albertel 8370:                 foreach my $key (keys(%env)) {
                   8371: 		    if ($key=~/^httpref\..*\*/) {
                   8372: 			my $pattern=$key;
1.156     www      8373:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8374:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8375:                         $pattern=~s/\//\\\//g;
1.152     www      8376:                         if ($orguri=~/$pattern/) {
1.800     albertel 8377: 			    $refuri=$env{$key};
1.148     www      8378:                         }
                   8379:                     }
1.191     harris41 8380:                 }
1.148     www      8381:             }
1.232     www      8382: 
1.148     www      8383:          if ($refuri) { 
1.152     www      8384: 	  $refuri=&declutter($refuri);
1.232     www      8385:           my ($match,$cond)=&is_on_map($refuri);
                   8386:             if ($match) {
                   8387:               my $refstatecond=$cond;
1.620     albertel 8388:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8389:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8390:                   my $value = $1;
                   8391:                   if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8392:22):                       my $deeplinkblock;
                   8393:22):                       unless ($nodeeplinkcheck) {
                   8394:22):                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8395:22):                       }
                   8396:22):                       if ($deeplinkblock) {
                   8397:22):                           $thisallowed = 'D';
                   8398:22):                       } elsif ($noblockcheck) {
1.1162    raeburn  8399:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8400:                       } else {
1.1172.2.127  raeburn  8401:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8402:                           if (@blockers > 0) {
                   8403:                               $thisallowed = 'B';
                   8404:                           } else {
                   8405:                               $thisallowed.=$value;
                   8406:                           }
1.1162    raeburn  8407:                       }
                   8408:                   } else {
                   8409:                       $thisallowed.=$value;
                   8410:                   }
1.53      www      8411:                   $uri=$refuri;
                   8412:                   $statecond=$refstatecond;
1.52      www      8413:               }
                   8414:           }
1.148     www      8415:         }
1.29      www      8416:        }
1.52      www      8417:    }
1.29      www      8418: 
1.52      www      8419: #
1.103     harris41 8420: # Gathered now: all privileges that could apply, and condition number
1.52      www      8421: # 
                   8422: #
                   8423: # Full or no access?
                   8424: #
1.29      www      8425: 
1.52      www      8426:     if ($thisallowed=~/F/) {
                   8427: 	return 'F';
                   8428:     }
1.29      www      8429: 
1.52      www      8430:     unless ($thisallowed) {
                   8431:         return '';
                   8432:     }
1.29      www      8433: 
1.52      www      8434: # Restrictions exist, deal with them
                   8435: #
                   8436: #   C:according to course preferences
                   8437: #   R:according to resource settings
                   8438: #   L:unless locked
                   8439: #   X:according to user session state
                   8440: #
                   8441: 
                   8442: # Possibly locked functionality, check all courses
1.1172.2.142  raeburn  8443: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54      www      8444: # Locks might take effect only after 10 minutes cache expiration for other
1.1172.2.142  raeburn  8445: # courses, and 2 minutes for current course, in which user has st or ta role
                   8446: # which is neither expired nor a future role (unless current course).
1.52      www      8447: 
1.1172.2.142  raeburn  8448:     my ($needlockcheck,$now,$crsonly);
1.52      www      8449:     if ($thisallowed=~/L/) {
1.1172.2.142  raeburn  8450:         $now = time;
                   8451:         if ($priv eq 'bre') {
                   8452:             if ($uri ne '') {
                   8453:                 if ($orguri =~ m{^/+res/}) {
                   8454:                     if ($uri =~ m{^lib/templates/}) {
                   8455:                         if ($env{'request.course.id'}) {
                   8456:                             $crsonly = 1;
                   8457:                             $needlockcheck = 1;
                   8458:                         }
                   8459:                     } else {
                   8460:                         $needlockcheck = 1;
                   8461:                     }
                   8462:                 } elsif ($env{'request.course.id'}) {
                   8463:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
                   8464:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
                   8465:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
                   8466:                         $crsonly = 1;
                   8467:                     }
                   8468:                     $needlockcheck = 1;
                   8469:                 }
                   8470:             }
                   8471:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
                   8472:             $needlockcheck = 1;
                   8473:         }
                   8474:     }
                   8475:     if ($needlockcheck) {
                   8476:         foreach my $envkey (keys(%env)) {
1.54      www      8477:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8478:                my $courseid=$2;
                   8479:                my $roleid=$1.'.'.$2;
1.92      www      8480:                $courseid=~s/^\///;
1.1172.2.142  raeburn  8481:                unless ($env{'request.role'} eq $roleid) {
                   8482:                    my ($start,$end) = split(/\./,$env{$envkey});
                   8483:                    next unless (($now >= $start) && (!$end || $end > $now));
                   8484:                }
1.54      www      8485:                my $expiretime=600;
1.620     albertel 8486:                if ($env{'request.role'} eq $roleid) {
1.54      www      8487: 		  $expiretime=120;
                   8488:                }
                   8489: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8490:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8491:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8492: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8493:                }
1.620     albertel 8494:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8495:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8496: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8497:                        &log($env{'user.domain'},$env{'user.name'},
                   8498:                             $env{'user.home'},
1.57      www      8499:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8500:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8501:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8502: 		       return '';
                   8503:                    }
                   8504:                }
1.620     albertel 8505:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8506:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1172.2.142  raeburn  8507: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620     albertel 8508:                        &log($env{'user.domain'},$env{'user.name'},
                   8509:                             $env{'user.home'},
1.57      www      8510:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8511:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8512:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8513: 		       return '';
                   8514:                    }
                   8515:                }
                   8516: 	   }
1.29      www      8517:        }
1.52      www      8518:     }
1.1172.2.126  raeburn  8519: 
1.52      www      8520: #
                   8521: # Rest of the restrictions depend on selected course
                   8522: #
                   8523: 
1.620     albertel 8524:     unless ($env{'request.course.id'}) {
1.766     albertel 8525: 	if ($thisallowed eq 'A') {
                   8526: 	    return 'A';
1.814     raeburn  8527:         } elsif ($thisallowed eq 'B') {
                   8528:             return 'B';
1.766     albertel 8529: 	} else {
                   8530: 	    return '1';
                   8531: 	}
1.52      www      8532:     }
1.29      www      8533: 
1.52      www      8534: #
                   8535: # Now user is definitely in a course
                   8536: #
1.53      www      8537: 
                   8538: 
                   8539: # Course preferences
                   8540: 
                   8541:    if ($thisallowed=~/C/) {
1.620     albertel 8542:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8543:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8544:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8545: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8546: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8547: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8548: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8549: 			$env{'request.course.id'});
                   8550: 	   }
1.237     www      8551:            return '';
                   8552:        }
                   8553: 
1.620     albertel 8554:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8555: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8556: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8557: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8558: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8559: 			$env{'request.course.id'});
                   8560: 	   }
1.54      www      8561:            return '';
                   8562:        }
1.53      www      8563:    }
                   8564: 
                   8565: # Resource preferences
                   8566: 
                   8567:    if ($thisallowed=~/R/) {
1.620     albertel 8568:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8569:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8570: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8571: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8572: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8573: 	   }
                   8574: 	   return '';
1.54      www      8575:        }
1.53      www      8576:    }
1.30      www      8577: 
1.1172.2.146.  .1(raebu 8578:22): # Restricted for deeplinked session?
                   8579:22): 
                   8580:22):     if ($env{'request.deeplink.login'}) {
                   8581:22):         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
                   8582:22):             if (!$symb) { $symb=&symbread($uri,1); }
                   8583:22):             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
                   8584:22):                 return '';
                   8585:22):             }
                   8586:22):         }
                   8587:22):     }
                   8588:22): 
1.246     www      8589: # Restricted by state or randomout?
1.30      www      8590: 
1.52      www      8591:    if ($thisallowed=~/X/) {
1.620     albertel 8592:       if ($env{'acc.randomout'}) {
1.579     albertel 8593: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8594:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8595:             return ''; 
                   8596:          }
1.247     www      8597:       }
                   8598:       if (&condval($statecond)) {
1.52      www      8599: 	 return '2';
                   8600:       } else {
                   8601:          return '';
                   8602:       }
                   8603:    }
1.30      www      8604: 
1.766     albertel 8605:     if ($thisallowed eq 'A') {
                   8606: 	return 'A';
1.814     raeburn  8607:     } elsif ($thisallowed eq 'B') {
                   8608:         return 'B';
1.1172.2.146.  .1(raebu 8609:22):     } elsif ($thisallowed eq 'D') {
                   8610:22):         return 'D';
1.766     albertel 8611:     }
1.52      www      8612:    return 'F';
1.232     www      8613: }
1.1162    raeburn  8614: 
1.1172.2.13  raeburn  8615: # ------------------------------------------- Check construction space access
                   8616: 
                   8617: sub constructaccess {
                   8618:     my ($url,$setpriv)=@_;
                   8619: 
                   8620: # We do not allow editing of previous versions of files
                   8621:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8622: 
                   8623: # Get username and domain from URL
                   8624:     my ($ownername,$ownerdomain,$ownerhome);
                   8625: 
                   8626:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8627:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8628: 
                   8629: # The URL does not really point to any authorspace, forget it
                   8630:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8631: 
                   8632: # Now we need to see if the user has access to the authorspace of
                   8633: # $ownername at $ownerdomain
                   8634: 
                   8635:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8636: # Real author for this?
                   8637:        $ownerhome = $env{'user.home'};
                   8638:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8639:           return ($ownername,$ownerdomain,$ownerhome);
                   8640:        }
                   8641:     } else {
                   8642: # Co-author for this?
                   8643:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8644:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8645:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8646:             return ($ownername,$ownerdomain,$ownerhome);
                   8647:         }
                   8648:     }
                   8649: 
                   8650: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8651: # we might as well leave
                   8652:    unless ($setpriv) { return ''; }
                   8653: 
                   8654: # Backdoor access?
                   8655:     my $allowed=&allowed('eco',$ownerdomain);
                   8656: # Nope
                   8657:     unless ($allowed) { return ''; }
                   8658: # Looks like we may have access, but could be locked by the owner of the construction space
                   8659:     if ($allowed eq 'U') {
                   8660:         my %blocked=&get('environment',['domcoord.author'],
                   8661:                          $ownerdomain,$ownername);
                   8662: # Is blocked by owner
                   8663:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8664:     }
                   8665:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8666: # Grant temporary access
                   8667:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8668:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8669:         if (!$update) { $update = $then; }
                   8670:         my $refresh=$env{'user.refresh.time'};
                   8671:         if (!$refresh) { $refresh = $update; }
                   8672:         my $now = time;
                   8673:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8674:                            $now,'ca','constructaccess');
                   8675:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8676:         return($ownername,$ownerdomain,$ownerhome);
                   8677:     }
                   8678: # No business here
                   8679:     return '';
                   8680: }
                   8681: 
1.1172.2.66  raeburn  8682: # ----------------------------------------------------------- Content Blocking
                   8683: 
                   8684: {
                   8685: # Caches for faster Course Contents display where content blocking
                   8686: # is in operation (i.e., interval param set) for timed quiz.
                   8687: #
                   8688: # User for whom data are being temporarily cached.
                   8689: my $cacheduser='';
1.1172.2.126  raeburn  8690: # Course for which data are being temporarily cached.
                   8691: my $cachedcid='';
1.1172.2.66  raeburn  8692: # Cached blockers for this user (a hash of blocking items).
                   8693: my %cachedblockers=();
                   8694: # When the data were last cached.
                   8695: my $cachedlast='';
                   8696: 
                   8697: sub load_all_blockers {
1.1172.2.128  raeburn  8698:     my ($uname,$udom)=@_;
1.1172.2.66  raeburn  8699:     if (($uname ne '') && ($udom ne '')) {
                   8700:         if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126  raeburn  8701:             ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128  raeburn  8702:             (abs($cachedlast-time)<5)) {
1.1172.2.66  raeburn  8703:             return;
                   8704:         }
                   8705:     }
                   8706:     $cachedlast=time;
                   8707:     $cacheduser=$uname.':'.$udom;
1.1172.2.126  raeburn  8708:     $cachedcid=$env{'request.course.id'};
1.1172.2.128  raeburn  8709:     %cachedblockers = &get_commblock_resources();
1.1172.2.126  raeburn  8710:     return;
1.1172.2.66  raeburn  8711: }
                   8712: 
1.1162    raeburn  8713: sub get_comm_blocks {
                   8714:     my ($cdom,$cnum) = @_;
                   8715:     if ($cdom eq '' || $cnum eq '') {
                   8716:         return unless ($env{'request.course.id'});
                   8717:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8718:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8719:     }
                   8720:     my %commblocks;
                   8721:     my $hashid=$cdom.'_'.$cnum;
                   8722:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8723:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8724:         %commblocks = %{$blocksref};
                   8725:     } else {
                   8726:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8727:         my $cachetime = 600;
                   8728:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8729:     }
                   8730:     return %commblocks;
                   8731: }
                   8732: 
1.1172.2.66  raeburn  8733: sub get_commblock_resources {
                   8734:     my ($blocks) = @_;
                   8735:     my %blockers = ();
                   8736:     return %blockers unless ($env{'request.course.id'});
1.1172.2.142  raeburn  8737:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8738:     if ($env{'request.course.sec'}) {
                   8739:         $courseurl .= '/'.$env{'request.course.sec'};
                   8740:     }
                   8741:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162    raeburn  8742:     my %commblocks;
                   8743:     if (ref($blocks) eq 'HASH') {
                   8744:         %commblocks = %{$blocks};
                   8745:     } else {
                   8746:         %commblocks = &get_comm_blocks();
                   8747:     }
1.1172.2.66  raeburn  8748:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8749:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8750:     return %blockers unless (ref($navmap));
                   8751:     my $now = time;
1.1162    raeburn  8752:     foreach my $block (keys(%commblocks)) {
                   8753:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8754:             my ($start,$end) = ($1,$2);
                   8755:             if ($start <= $now && $end >= $now) {
                   8756:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8757:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8758:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8759:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8760:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8761:                             }
                   8762:                         }
                   8763:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8764:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8765:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8766:                             }
                   8767:                         }
                   8768:                     }
                   8769:                 }
                   8770:             }
                   8771:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8772:             my $item = $1;
                   8773:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8774:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.142  raeburn  8775:                     my (@interval,$mapname);
1.1172.2.66  raeburn  8776:                     my $type = 'map';
                   8777:                     if ($item eq 'course') {
                   8778:                         $type = 'course';
                   8779:                         @interval=&EXT("resource.0.interval");
                   8780:                     } else {
                   8781:                         if ($item =~ /___\d+___/) {
                   8782:                             $type = 'resource';
                   8783:                             @interval=&EXT("resource.0.interval",$item);
1.1162    raeburn  8784:                         } else {
1.1172.2.142  raeburn  8785:                             $mapname = &deversion($item);
                   8786:                             if (ref($navmap)) {
                   8787:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
                   8788:                                 @interval = ($timelimit,'map');
1.1162    raeburn  8789:                             }
                   8790:                         }
1.1172.2.66  raeburn  8791:                     }
1.1172.2.146.  .1(raebu 8792:22):                     if ($interval[0] =~ /^(\d+)/) {
                   8793:22):                         my $timelimit = $1;
1.1172.2.66  raeburn  8794:                         my $first_access;
                   8795:                         if ($type eq 'resource') {
                   8796:                             $first_access=&get_first_access($interval[1],$item);
                   8797:                         } elsif ($type eq 'map') {
                   8798:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8799:                         } else {
                   8800:                             $first_access=&get_first_access($interval[1]);
                   8801:                         }
                   8802:                         if ($first_access) {
1.1172.2.146.  .1(raebu 8803:22):                             my $timesup = $first_access+$timelimit;
1.1172.2.66  raeburn  8804:                             if ($timesup > $now) {
                   8805:                                 my $activeblock;
1.1172.2.142  raeburn  8806:                                 if ($type eq 'resource') {
                   8807:                                     if (ref($navmap)) {
                   8808:                                         my $res = $navmap->getBySymb($item);
                   8809:                                         if ($res->answerable()) {
                   8810:                                             $activeblock = 1;
                   8811:                                         }
                   8812:                                     }
                   8813:                                 } elsif ($type eq 'map') {
                   8814:                                     my $mapsymb = &symbread($mapname,1);
                   8815:                                     if (($mapsymb) && (ref($navmap))) {
                   8816:                                         my $mapres = $navmap->getBySymb($mapsymb);
                   8817:                                         if (ref($mapres)) {
                   8818:                                             my $first = $mapres->map_start();
                   8819:                                             my $finish = $mapres->map_finish();
                   8820:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   8821:                                             if (ref($it)) {
                   8822:                                                 my $res;
                   8823:                                                 while ($res = $it->next(undef,1)) {
                   8824:                                                     next unless (ref($res));
                   8825:                                                     my $symb = $res->symb();
                   8826:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
                   8827:                                                     @interval=&EXT("resource.0.interval",$symb);
                   8828:                                                     if ($interval[1] eq 'map') {
                   8829:                                                         if ($res->answerable()) {
                   8830:                                                             $activeblock = 1;
                   8831:                                                             last;
                   8832:                                                         }
                   8833:                                                     }
                   8834:                                                 }
                   8835:                                             }
                   8836:                                         }
1.1172.2.66  raeburn  8837:                                     }
                   8838:                                 }
                   8839:                                 if ($activeblock) {
                   8840:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8841:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8842:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8843:                                          }
                   8844:                                     }
                   8845:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8846:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8847:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8848:                                         }
1.1162    raeburn  8849:                                     }
                   8850:                                 }
                   8851:                             }
                   8852:                         }
                   8853:                     }
                   8854:                 }
                   8855:             }
                   8856:         }
                   8857:     }
1.1172.2.66  raeburn  8858:     return %blockers;
1.1162    raeburn  8859: }
                   8860: 
1.1172.2.66  raeburn  8861: sub has_comm_blocking {
1.1172.2.128  raeburn  8862:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66  raeburn  8863:     my @blockers;
                   8864:     return unless ($env{'request.course.id'});
                   8865:     return unless ($priv eq 'bre');
                   8866:     return if ($env{'request.state'} eq 'construct');
1.1172.2.142  raeburn  8867:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8868:     if ($env{'request.course.sec'}) {
                   8869:         $courseurl .= '/'.$env{'request.course.sec'};
                   8870:     }
                   8871:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1172.2.128  raeburn  8872:     my %blockinfo;
                   8873:     if (ref($blocks) eq 'HASH') {
                   8874:         %blockinfo = &get_commblock_resources($blocks);
                   8875:     } else {
                   8876:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   8877:         %blockinfo = %cachedblockers;
                   8878:     }
                   8879:     return unless (keys(%blockinfo) > 0);
1.1172.2.66  raeburn  8880:     my (%possibles,@symbs);
                   8881:     if (!$symb) {
1.1172.2.128  raeburn  8882:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  8883:     }
1.1172.2.66  raeburn  8884:     if ($symb) {
                   8885:         @symbs = ($symb);
                   8886:     } elsif (keys(%possibles)) {
                   8887:         @symbs = keys(%possibles);
                   8888:     }
                   8889:     my $noblock;
                   8890:     foreach my $symb (@symbs) {
                   8891:         last if ($noblock);
                   8892:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128  raeburn  8893:         foreach my $block (keys(%blockinfo)) {
1.1172.2.66  raeburn  8894:             if ($block =~ /^firstaccess____(.+)$/) {
                   8895:                 my $item = $1;
1.1172.2.126  raeburn  8896:                 unless ($blocked) {
                   8897:                     if (($item eq $map) || ($item eq $symb)) {
                   8898:                         $noblock = 1;
                   8899:                         last;
                   8900:                     }
1.1172.2.66  raeburn  8901:                 }
1.1162    raeburn  8902:             }
1.1172.2.128  raeburn  8903:             if (ref($blockinfo{$block}) eq 'HASH') {
                   8904:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   8905:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66  raeburn  8906:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8907:                             push(@blockers,$block);
                   8908:                         }
                   8909:                     }
                   8910:                 }
1.1172.2.128  raeburn  8911:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   8912:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126  raeburn  8913:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8914:                             push(@blockers,$block);
                   8915:                         }
1.1172.2.66  raeburn  8916:                     }
                   8917:                 }
1.1162    raeburn  8918:             }
                   8919:         }
                   8920:     }
1.1172.2.126  raeburn  8921:     unless ($noblock) {
                   8922:         return @blockers;
                   8923:     }
                   8924:     return;
1.1172.2.66  raeburn  8925: }
1.1162    raeburn  8926: }
                   8927: 
1.1172.2.146.  .1(raebu 8928:22): sub deeplink_check {
                   8929:22):     my ($priv,$symb,$uri) = @_;
                   8930:22):     return unless ($env{'request.course.id'});
                   8931:22):     return unless ($priv eq 'bre');
                   8932:22):     return if ($env{'request.state'} eq 'construct');
                   8933:22):     return if ($env{'request.role.adv'});
                   8934:22):     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8935:22):     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8936:22):     my (%possibles,@symbs);
                   8937:22):     if (!$symb) {
                   8938:22):         $symb = &symbread($uri,1,1,1,\%possibles);
                   8939:22):     }
                   8940:22):     if ($symb) {
                   8941:22):         @symbs = ($symb);
                   8942:22):     } elsif (keys(%possibles)) {
                   8943:22):         @symbs = keys(%possibles);
                   8944:22):     }
                   8945:22): 
                   8946:22):     my ($deeplink_symb,$allow);
                   8947:22):     if ($env{'request.deeplink.login'}) {
                   8948:22):         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
                   8949:22):     }
                   8950:22):     foreach my $symb (@symbs) {
                   8951:22):         last if ($allow);
                   8952:22):         my $deeplink = &EXT("resource.0.deeplink",$symb);
                   8953:22):         if ($deeplink eq '') {
                   8954:22):             $allow = 1;
                   8955:22):         } else {
                   8956:22):             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
                   8957:22):             if ($state ne 'only') {
                   8958:22):                 $allow = 1;
                   8959:22):             } else {
                   8960:22):                 my $check_deeplink_entry;
                   8961:22):                 if ($protect ne 'none') {
                   8962:22):                     my ($acctype,$item) = split(/:/,$protect);
                   8963:22):                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
                   8964:22):                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
                   8965:22):                             $check_deeplink_entry = 1
                   8966:22):                         }
                   8967:22):                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
                   8968:22):                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
                   8969:22):                             $check_deeplink_entry = 1;
                   8970:22):                         }
                   8971:22):                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
                   8972:22):                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
                   8973:22):                             $check_deeplink_entry = 1;
                   8974:22):                         }
                   8975:22):                     }
                   8976:22):                 }
                   8977:22):                 if (($protect eq 'none') || ($check_deeplink_entry)) {
                   8978:22):                     if ($scope eq 'res') {
                   8979:22):                         if ($symb eq $deeplink_symb) {
                   8980:22):                             $allow = 1;
                   8981:22):                         }
                   8982:22):                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
                   8983:22):                         my ($map_from_symb,$map_from_login);
                   8984:22):                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
                   8985:22):                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   8986:22):                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
                   8987:22):                         } else {
                   8988:22):                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
                   8989:22):                         }
                   8990:22):                         if (($map_from_symb) && ($map_from_login)) {
                   8991:22):                             if ($map_from_symb eq $map_from_login) {
                   8992:22):                                 $allow = 1;
                   8993:22):                             } elsif ($scope eq 'rec') {
                   8994:22):                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
                   8995:22):                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
                   8996:22):                                     $allow = 1;
                   8997:22):                                 }
                   8998:22):                             }
                   8999:22):                         }
                   9000:22):                     }
                   9001:22):                 }
                   9002:22):             }
                   9003:22):         }
                   9004:22):     }
                   9005:22):     return if ($allow);
                   9006:22):     return 1;
                   9007:22): }
                   9008:22): 
1.1172.2.66  raeburn  9009: # -------------------------------- Deversion and split uri into path an filename
                   9010: 
1.1133    foxr     9011: #
1.1172.2.66  raeburn  9012: #   Removes the version from a URI and
1.1133    foxr     9013: #   splits it in to its filename and path to the filename.
                   9014: #   Seems like File::Basename could have done this more clearly.
                   9015: #   Parameters:
                   9016: #      $uri   - input URI
                   9017: #   Returns:
                   9018: #     Two element list consisting of 
                   9019: #     $pathname  - the URI up to and excluding the trailing /
                   9020: #     $filename  - The part of the URI following the last /
                   9021: #  NOTE:
                   9022: #    Another realization of this is simply:
                   9023: #    use File::Basename;
                   9024: #    ...
                   9025: #    $uri = shift;
                   9026: #    $filename = basename($uri);
                   9027: #    $path     = dirname($uri);
                   9028: #    return ($filename, $path);
                   9029: #
                   9030: #     The implementation below is probably faster however.
                   9031: #
1.710     albertel 9032: sub split_uri_for_cond {
                   9033:     my $uri=&deversion(&declutter(shift));
                   9034:     my @uriparts=split(/\//,$uri);
                   9035:     my $filename=pop(@uriparts);
                   9036:     my $pathname=join('/',@uriparts);
                   9037:     return ($pathname,$filename);
                   9038: }
1.232     www      9039: # --------------------------------------------------- Is a resource on the map?
                   9040: 
                   9041: sub is_on_map {
1.710     albertel 9042:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 9043:     #Trying to find the conditional for the file
1.620     albertel 9044:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 9045: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      9046:     if ($match) {
1.289     bowersj2 9047: 	return (1,$1);
                   9048:     } else {
1.434     www      9049: 	return (0,0);
1.289     bowersj2 9050:     }
1.12      www      9051: }
                   9052: 
1.427     www      9053: # --------------------------------------------------------- Get symb from alias
                   9054: 
                   9055: sub get_symb_from_alias {
                   9056:     my $symb=shift;
                   9057:     my ($map,$resid,$url)=&decode_symb($symb);
                   9058: # Already is a symb
                   9059:     if ($url) { return $symb; }
                   9060: # Must be an alias
                   9061:     my $aliassymb='';
                   9062:     my %bighash;
1.620     albertel 9063:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      9064:                             &GDBM_READER(),0640)) {
                   9065:         my $rid=$bighash{'mapalias_'.$symb};
                   9066: 	if ($rid) {
                   9067: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 9068: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   9069: 				    $resid,$bighash{'src_'.$rid});
1.427     www      9070: 	}
                   9071:         untie %bighash;
                   9072:     }
                   9073:     return $aliassymb;
                   9074: }
                   9075: 
1.12      www      9076: # ----------------------------------------------------------------- Define Role
                   9077: 
                   9078: sub definerole {
                   9079:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  9080:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 9081:     foreach my $role (split(':',$sysrole)) {
                   9082: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9083:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   9084:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   9085: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9086:                return "refused:s:$crole&$cqual"; 
                   9087:             }
                   9088:         }
1.191     harris41 9089:     }
1.800     albertel 9090:     foreach my $role (split(':',$domrole)) {
                   9091: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9092:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   9093:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   9094: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      9095:                return "refused:d:$crole&$cqual"; 
                   9096:             }
                   9097:         }
1.191     harris41 9098:     }
1.800     albertel 9099:     foreach my $role (split(':',$courole)) {
                   9100: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9101:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   9102:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   9103: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9104:                return "refused:c:$crole&$cqual"; 
                   9105:             }
                   9106:         }
1.191     harris41 9107:     }
1.1172.2.84  raeburn  9108:     my $uhome;
                   9109:     if (($uname ne '') && ($udom ne '')) {
                   9110:         $uhome = &homeserver($uname,$udom);
                   9111:         return $uhome if ($uhome eq 'no_host');
                   9112:     } else {
                   9113:         $uname = $env{'user.name'};
                   9114:         $udom = $env{'user.domain'};
                   9115:         $uhome = $env{'user.home'};
                   9116:     }
1.620     albertel 9117:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  9118:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      9119:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  9120:     return reply($command,$uhome);
1.12      www      9121:   } else {
                   9122:     return 'refused';
                   9123:   }
1.105     harris41 9124: }
                   9125: 
                   9126: # ---------------- Make a metadata query against the network of library servers
                   9127: 
                   9128: sub metadata_query {
1.1172.2.33  raeburn  9129:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 9130:     my %rhash;
1.845     albertel 9131:     my %libserv = &all_library();
1.244     matthew  9132:     my @server_list = (defined($server_array) ? @$server_array
                   9133:                                               : keys(%libserv) );
                   9134:     for my $server (@server_list) {
1.1172.2.33  raeburn  9135:         my $domains = '';
                   9136:         if (ref($domains_hash) eq 'HASH') {
                   9137:             $domains = $domains_hash->{$server};    
                   9138:         }
1.118     harris41 9139: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  9140: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 9141: 	    $rhash{$server}=$reply;
                   9142: 	}
                   9143: 	else {
                   9144: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  9145: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 9146: 			     $server);
                   9147: 	    $rhash{$server}=$reply;
                   9148: 	}
1.112     harris41 9149:     }
1.118     harris41 9150:     return \%rhash;
1.240     www      9151: }
                   9152: 
                   9153: # ----------------------------------------- Send log queries and wait for reply
                   9154: 
                   9155: sub log_query {
                   9156:     my ($uname,$udom,$query,%filters)=@_;
                   9157:     my $uhome=&homeserver($uname,$udom);
                   9158:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 9159:     my $uhost=&hostname($uhome);
1.800     albertel 9160:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      9161:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   9162:                        $uhome);
1.479     albertel 9163:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      9164:     return get_query_reply($queryid);
                   9165: }
                   9166: 
1.818     raeburn  9167: # -------------------------- Update MySQL table for portfolio file
                   9168: 
                   9169: sub update_portfolio_table {
1.821     raeburn  9170:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  9171:     if ($group ne '') {
                   9172:         $file_name =~s /^\Q$group\E//;
                   9173:     }
1.818     raeburn  9174:     my $homeserver = &homeserver($uname,$udom);
                   9175:     my $queryid=
1.821     raeburn  9176:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   9177:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  9178:     my $reply = &get_query_reply($queryid);
                   9179:     return $reply;
                   9180: }
                   9181: 
1.899     raeburn  9182: # -------------------------- Update MySQL allusers table
                   9183: 
                   9184: sub update_allusers_table {
                   9185:     my ($uname,$udom,$names) = @_;
                   9186:     my $homeserver = &homeserver($uname,$udom);
                   9187:     my $queryid=
                   9188:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   9189:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   9190:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   9191:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   9192:                'generation='.&escape($names->{'generation'}).'%%'.
                   9193:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   9194:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  9195:     return;
1.899     raeburn  9196: }
                   9197: 
1.508     raeburn  9198: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  9199: 
                   9200: sub fetch_enrollment_query {
1.511     raeburn  9201:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  9202:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  9203:     my $maxtries = 1;
1.508     raeburn  9204:     if ($context eq 'automated') {
                   9205:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  9206:         $sleep = 2;
                   9207:         $loopmax = 100;
1.547     raeburn  9208:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  9209:     } else {
                   9210:         $homeserver = &homeserver($cnum,$dom);
                   9211:     }
1.838     albertel 9212:     my $host=&hostname($homeserver);
1.506     raeburn  9213:     my $cmd = '';
1.1000    raeburn  9214:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 9215:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  9216:     }
                   9217:     $cmd =~ s/%%$//;
                   9218:     $cmd = &escape($cmd);
                   9219:     my $query = 'fetchenrollment';
1.620     albertel 9220:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  9221:     unless ($queryid=~/^\Q$host\E\_/) { 
                   9222:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   9223:         return 'error: '.$queryid;
                   9224:     }
1.1172.2.93  raeburn  9225:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9226:     my $tries = 1;
                   9227:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  9228:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9229:         $tries ++;
                   9230:     }
1.526     raeburn  9231:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 9232:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  9233:     } else {
1.901     albertel 9234:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  9235:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 9236:             foreach my $line (@responses) {
                   9237:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  9238:                 $$replyref{$key} = $value;
                   9239:             }
                   9240:         } else {
1.1117    foxr     9241:             my $pathname = LONCAPA::tempdir();
1.800     albertel 9242:             foreach my $line (@responses) {
                   9243:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  9244:                 $$replyref{$key} = $value;
                   9245:                 if ($value > 0) {
1.800     albertel 9246:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   9247:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  9248:                         my $destname = $pathname.'/'.$filename;
                   9249:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  9250:                         if ($xml_classlist =~ /^error/) {
                   9251:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   9252:                         } else {
1.1172.2.96  raeburn  9253:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  9254:                                 print FILE &unescape($xml_classlist);
                   9255:                                 close(FILE);
1.526     raeburn  9256:                             } else {
                   9257:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  9258:                             }
                   9259:                         }
                   9260:                     }
                   9261:                 }
                   9262:             }
                   9263:         }
                   9264:         return 'ok';
                   9265:     }
                   9266:     return 'error';
                   9267: }
                   9268: 
1.242     www      9269: sub get_query_reply {
1.1172.2.79  raeburn  9270:     my ($queryid,$sleep,$loopmax) = @_;
                   9271:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9272:         $sleep = 0.2;
                   9273:     }
                   9274:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9275:         $loopmax = 100;
                   9276:     }
1.1117    foxr     9277:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9278:     my $reply='';
1.1172.2.79  raeburn  9279:     for (1..$loopmax) {
                   9280: 	sleep($sleep);
1.240     www      9281:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  9282: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9283: 		$reply = join('',<$fh>);
                   9284: 		close($fh);
1.240     www      9285: 	   } else { return 'error: reply_file_error'; }
1.242     www      9286:            return &unescape($reply);
                   9287: 	}
1.240     www      9288:     }
1.242     www      9289:     return 'timeout:'.$queryid;
1.240     www      9290: }
                   9291: 
                   9292: sub courselog_query {
1.241     www      9293: #
                   9294: # possible filters:
                   9295: # url: url or symb
                   9296: # username
                   9297: # domain
                   9298: # action: view, submit, grade
                   9299: # start: timestamp
                   9300: # end: timestamp
                   9301: #
1.240     www      9302:     my (%filters)=@_;
1.620     albertel 9303:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9304:     if ($filters{'url'}) {
                   9305: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9306:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9307:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9308:     }
1.620     albertel 9309:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9310:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9311:     return &log_query($cname,$cdom,'courselog',%filters);
                   9312: }
                   9313: 
                   9314: sub userlog_query {
1.858     raeburn  9315: #
                   9316: # possible filters:
                   9317: # action: log check role
                   9318: # start: timestamp
                   9319: # end: timestamp
                   9320: #
1.240     www      9321:     my ($uname,$udom,%filters)=@_;
                   9322:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9323: }
                   9324: 
1.506     raeburn  9325: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9326: 
                   9327: sub auto_run {
1.508     raeburn  9328:     my ($cnum,$cdom) = @_;
1.876     raeburn  9329:     my $response = 0;
                   9330:     my $settings;
                   9331:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9332:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9333:         $settings = $domconfig{'autoenroll'};
                   9334:         if ($settings->{'run'} eq '1') {
                   9335:             $response = 1;
                   9336:         }
                   9337:     } else {
1.934     raeburn  9338:         my $homeserver;
                   9339:         if (&is_course($cdom,$cnum)) {
                   9340:             $homeserver = &homeserver($cnum,$cdom);
                   9341:         } else {
                   9342:             $homeserver = &domain($cdom,'primary');
                   9343:         }
                   9344:         if ($homeserver ne 'no_host') {
                   9345:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9346:         }
1.876     raeburn  9347:     }
1.506     raeburn  9348:     return $response;
                   9349: }
1.776     albertel 9350: 
1.506     raeburn  9351: sub auto_get_sections {
1.508     raeburn  9352:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9353:     my $homeserver;
                   9354:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9355:         $homeserver = &homeserver($cnum,$cdom);
                   9356:     }
                   9357:     if (!defined($homeserver)) { 
                   9358:         if ($cdom =~ /^$match_domain$/) {
                   9359:             $homeserver = &domain($cdom,'primary');
                   9360:         }
                   9361:     }
                   9362:     my @secs;
                   9363:     if (defined($homeserver)) {
                   9364:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9365:         unless ($response eq 'refused') {
                   9366:             @secs = split(/:/,$response);
                   9367:         }
1.506     raeburn  9368:     }
                   9369:     return @secs;
                   9370: }
1.776     albertel 9371: 
1.506     raeburn  9372: sub auto_new_course {
1.1099    raeburn  9373:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9374:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9375:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9376:     return $response;
                   9377: }
1.776     albertel 9378: 
1.506     raeburn  9379: sub auto_validate_courseID {
1.508     raeburn  9380:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9381:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9382:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9383:     return $response;
                   9384: }
1.776     albertel 9385: 
1.1007    raeburn  9386: sub auto_validate_instcode {
1.1020    raeburn  9387:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9388:     my ($homeserver,$response);
                   9389:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9390:         $homeserver = &homeserver($cnum,$cdom);
                   9391:     }
                   9392:     if (!defined($homeserver)) {
                   9393:         if ($cdom =~ /^$match_domain$/) {
                   9394:             $homeserver = &domain($cdom,'primary');
                   9395:         }
                   9396:     }
1.1065    raeburn  9397:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9398:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  9399:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9400:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9401: }
                   9402: 
1.1172.2.141  raeburn  9403: sub auto_validate_inst_crosslist {
                   9404:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
                   9405:     my ($homeserver,$response);
                   9406:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9407:         $homeserver = &homeserver($cnum,$cdom);
                   9408:     }
                   9409:     if (!defined($homeserver)) {
                   9410:         if ($cdom =~ /^$match_domain$/) {
                   9411:             $homeserver = &domain($cdom,'primary');
                   9412:         }
                   9413:     }
                   9414:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
                   9415:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
                   9416:                          &escape($instcode).':'.&escape($inst_xlist).':'.
                   9417:                          &escape($coowner),$homeserver);
                   9418:     }
                   9419:     return $response;
                   9420: }
                   9421: 
1.506     raeburn  9422: sub auto_create_password {
1.873     raeburn  9423:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9424:     my ($homeserver,$response);
1.506     raeburn  9425:     my $create_passwd = 0;
                   9426:     my $authchk = '';
1.873     raeburn  9427:     if ($udom =~ /^$match_domain$/) {
                   9428:         $homeserver = &domain($udom,'primary');
                   9429:     }
                   9430:     if ($homeserver eq '') {
                   9431:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9432:             $homeserver = &homeserver($cnum,$cdom);
                   9433:         }
                   9434:     }
                   9435:     if ($homeserver eq '') {
                   9436:         $authchk = 'nodomain';
1.506     raeburn  9437:     } else {
1.873     raeburn  9438:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9439:         if ($response eq 'refused') {
                   9440:             $authchk = 'refused';
                   9441:         } else {
1.901     albertel 9442:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9443:         }
1.506     raeburn  9444:     }
                   9445:     return ($authparam,$create_passwd,$authchk);
                   9446: }
                   9447: 
1.706     raeburn  9448: sub auto_photo_permission {
                   9449:     my ($cnum,$cdom,$students) = @_;
                   9450:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9451:     my ($outcome,$perm_reqd,$conditions) = 
                   9452: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9453:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9454: 	return (undef,undef);
                   9455:     }
1.706     raeburn  9456:     return ($outcome,$perm_reqd,$conditions);
                   9457: }
                   9458: 
                   9459: sub auto_checkphotos {
                   9460:     my ($uname,$udom,$pid) = @_;
                   9461:     my $homeserver = &homeserver($uname,$udom);
                   9462:     my ($result,$resulttype);
                   9463:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9464: 				   &escape($uname).':'.&escape($pid),
                   9465: 				   $homeserver));
1.709     albertel 9466:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9467: 	return (undef,undef);
                   9468:     }
1.706     raeburn  9469:     if ($outcome) {
                   9470:         ($result,$resulttype) = split(/:/,$outcome);
                   9471:     } 
                   9472:     return ($result,$resulttype);
                   9473: }
                   9474: 
                   9475: sub auto_photochoice {
                   9476:     my ($cnum,$cdom) = @_;
                   9477:     my $homeserver = &homeserver($cnum,$cdom);
                   9478:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9479: 						       &escape($cdom),
                   9480: 						       $homeserver)));
1.709     albertel 9481:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9482: 	return (undef,undef);
                   9483:     }
1.706     raeburn  9484:     return ($update,$comment);
                   9485: }
                   9486: 
                   9487: sub auto_photoupdate {
                   9488:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9489:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9490:     my $host=&hostname($homeserver);
1.706     raeburn  9491:     my $cmd = '';
                   9492:     my $maxtries = 1;
1.800     albertel 9493:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9494:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9495:     }
                   9496:     $cmd =~ s/%%$//;
                   9497:     $cmd = &escape($cmd);
                   9498:     my $query = 'institutionalphotos';
                   9499:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9500:     unless ($queryid=~/^\Q$host\E\_/) {
                   9501:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9502:         return 'error: '.$queryid;
                   9503:     }
                   9504:     my $reply = &get_query_reply($queryid);
                   9505:     my $tries = 1;
                   9506:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9507:         $reply = &get_query_reply($queryid);
                   9508:         $tries ++;
                   9509:     }
                   9510:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9511:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9512:     } else {
                   9513:         my @responses = split(/:/,$reply);
                   9514:         my $outcome = shift(@responses); 
                   9515:         foreach my $item (@responses) {
                   9516:             my ($key,$value) = split(/=/,$item);
                   9517:             $$photo{$key} = $value;
                   9518:         }
                   9519:         return $outcome;
                   9520:     }
                   9521:     return 'error';
                   9522: }
                   9523: 
1.521     raeburn  9524: sub auto_instcode_format {
1.793     albertel 9525:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9526: 	$cat_order) = @_;
1.521     raeburn  9527:     my $courses = '';
1.772     raeburn  9528:     my @homeservers;
1.521     raeburn  9529:     if ($caller eq 'global') {
1.841     albertel 9530: 	my %servers = &get_servers($codedom,'library');
                   9531: 	foreach my $tryserver (keys(%servers)) {
                   9532: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9533: 		push(@homeservers,$tryserver);
                   9534: 	    }
1.584     raeburn  9535:         }
1.1022    raeburn  9536:     } elsif ($caller eq 'requests') {
                   9537:         if ($codedom =~ /^$match_domain$/) {
                   9538:             my $chome = &domain($codedom,'primary');
                   9539:             unless ($chome eq 'no_host') {
                   9540:                 push(@homeservers,$chome);
                   9541:             }
                   9542:         }
1.521     raeburn  9543:     } else {
1.772     raeburn  9544:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9545:     }
1.793     albertel 9546:     foreach my $code (keys(%{$instcodes})) {
                   9547:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9548:     }
                   9549:     chop($courses);
1.772     raeburn  9550:     my $ok_response = 0;
                   9551:     my $response;
                   9552:     while (@homeservers > 0 && $ok_response == 0) {
                   9553:         my $server = shift(@homeservers); 
                   9554:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9555:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9556:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9557: 		split(/:/,$response);
1.772     raeburn  9558:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9559:             push(@{$codetitles},&str2array($codetitles_str));
                   9560:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9561:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9562:             $ok_response = 1;
                   9563:         }
                   9564:     }
                   9565:     if ($ok_response) {
1.521     raeburn  9566:         return 'ok';
1.772     raeburn  9567:     } else {
                   9568:         return $response;
1.521     raeburn  9569:     }
                   9570: }
                   9571: 
1.792     raeburn  9572: sub auto_instcode_defaults {
                   9573:     my ($domain,$returnhash,$code_order) = @_;
                   9574:     my @homeservers;
1.841     albertel 9575: 
                   9576:     my %servers = &get_servers($domain,'library');
                   9577:     foreach my $tryserver (keys(%servers)) {
                   9578: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9579: 	    push(@homeservers,$tryserver);
                   9580: 	}
1.792     raeburn  9581:     }
1.841     albertel 9582: 
1.792     raeburn  9583:     my $response;
1.841     albertel 9584:     foreach my $server (@homeservers) {
1.792     raeburn  9585:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9586:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9587: 	
                   9588: 	foreach my $pair (split(/\&/,$response)) {
                   9589: 	    my ($name,$value)=split(/\=/,$pair);
                   9590: 	    if ($name eq 'code_order') {
                   9591: 		@{$code_order} = split(/\&/,&unescape($value));
                   9592: 	    } else {
                   9593: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9594: 	    }
                   9595: 	}
                   9596: 	return 'ok';
1.792     raeburn  9597:     }
1.841     albertel 9598: 
                   9599:     return $response;
1.1003    raeburn  9600: }
                   9601: 
                   9602: sub auto_possible_instcodes {
1.1007    raeburn  9603:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9604:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9605:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9606:         return;
                   9607:     }
1.1003    raeburn  9608:     my (@homeservers,$uhome);
                   9609:     if (defined(&domain($domain,'primary'))) {
                   9610:         $uhome=&domain($domain,'primary');
                   9611:         push(@homeservers,&domain($domain,'primary'));
                   9612:     } else {
                   9613:         my %servers = &get_servers($domain,'library');
                   9614:         foreach my $tryserver (keys(%servers)) {
                   9615:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9616:                 push(@homeservers,$tryserver);
                   9617:             }
                   9618:         }
                   9619:     }
                   9620:     my $response;
                   9621:     foreach my $server (@homeservers) {
                   9622:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9623:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9624:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9625:             split(':',$response);
                   9626:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9627:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9628:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9629:             my ($name,$value)=split('=',$item);
                   9630:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9631:         }
                   9632:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9633:             my ($name,$value)=split('=',$item);
                   9634:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9635:         }
                   9636:         return 'ok';
                   9637:     }
                   9638:     return $response;
                   9639: }
1.792     raeburn  9640: 
1.1010    raeburn  9641: sub auto_courserequest_checks {
                   9642:     my ($dom) = @_;
1.1020    raeburn  9643:     my ($homeserver,%validations);
                   9644:     if ($dom =~ /^$match_domain$/) {
                   9645:         $homeserver = &domain($dom,'primary');
                   9646:     }
                   9647:     unless ($homeserver eq 'no_host') {
                   9648:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9649:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9650:             my @items = split(/&/,$response);
                   9651:             foreach my $item (@items) {
                   9652:                 my ($key,$value) = split('=',$item);
                   9653:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9654:             }
                   9655:         }
                   9656:     }
1.1010    raeburn  9657:     return %validations; 
                   9658: }
                   9659: 
1.1020    raeburn  9660: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9661:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9662:     my ($homeserver,$response);
                   9663:     if ($dom =~ /^$match_domain$/) {
                   9664:         $homeserver = &domain($dom,'primary');
                   9665:     }
1.1172.2.43  raeburn  9666:     unless ($homeserver eq 'no_host') {
                   9667:         my $customdata;
                   9668:         if (ref($custominfo) eq 'HASH') {
                   9669:             $customdata = &freeze_escape($custominfo);
                   9670:         }
1.1020    raeburn  9671:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9672:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9673:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9674:                                     $customdata,$homeserver));
1.1020    raeburn  9675:     }
                   9676:     return $response;
                   9677: }
                   9678: 
1.777     albertel 9679: sub auto_validate_class_sec {
1.918     raeburn  9680:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9681:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9682:     my $ownerlist;
                   9683:     if (ref($owners) eq 'ARRAY') {
                   9684:         $ownerlist = join(',',@{$owners});
                   9685:     } else {
                   9686:         $ownerlist = $owners;
                   9687:     }
1.773     raeburn  9688:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9689:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9690:     return $response;
                   9691: }
                   9692: 
1.1172.2.141  raeburn  9693: sub auto_instsec_reformat {
                   9694:     my ($cdom,$action,$instsecref) = @_;
                   9695:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
                   9696:     my @homeservers;
                   9697:     if (defined(&domain($cdom,'primary'))) {
                   9698:         push(@homeservers,&domain($cdom,'primary'));
                   9699:     } else {
                   9700:         my %servers = &get_servers($cdom,'library');
                   9701:         foreach my $tryserver (keys(%servers)) {
                   9702:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9703:                 push(@homeservers,$tryserver);
                   9704:             }
                   9705:         }
                   9706:     }
                   9707:     my $response;
                   9708:     my %reformatted = %{$instsecref};
                   9709:     foreach my $server (@homeservers) {
                   9710:         if (ref($instsecref) eq 'HASH') {
                   9711:             my $info = &freeze_escape($instsecref);
                   9712:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
                   9713:                                 $action.':'.$info,$server);
                   9714:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
                   9715:             my @items = split(/&/,$response);
                   9716:             foreach my $item (@items) {
                   9717:                 my ($key,$value) = split(/=/,$item);
                   9718:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
                   9719:             }
                   9720:         }
                   9721:     }
                   9722:     return %reformatted;
                   9723: }
                   9724: 
1.1172.2.94  raeburn  9725: sub auto_validate_instclasses {
                   9726:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9727:     my ($homeserver,%validations);
                   9728:     $homeserver = &homeserver($cnum,$cdom);
                   9729:     unless ($homeserver eq 'no_host') {
                   9730:         my $ownerlist;
                   9731:         if (ref($owners) eq 'ARRAY') {
                   9732:             $ownerlist = join(',',@{$owners});
                   9733:         } else {
                   9734:             $ownerlist = $owners;
                   9735:         }
                   9736:         if (ref($classesref) eq 'HASH') {
                   9737:             my $classes = &freeze_escape($classesref);
                   9738:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9739:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9740:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9741:                 my @items = split(/&/,$response);
                   9742:                 foreach my $item (@items) {
                   9743:                     my ($key,$value) = split('=',$item);
                   9744:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9745:                 }
                   9746:             }
                   9747:         }
                   9748:     }
                   9749:     return %validations;
                   9750: }
                   9751: 
1.1172.2.38  raeburn  9752: sub auto_crsreq_update {
                   9753:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9754:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9755:     my ($homeserver,%crsreqresponse);
                   9756:     if ($cdom =~ /^$match_domain$/) {
                   9757:         $homeserver = &domain($cdom,'primary');
                   9758:     }
                   9759:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9760:         my $info;
                   9761:         if (ref($inbound) eq 'HASH') {
                   9762:             $info = &freeze_escape($inbound);
                   9763:         }
                   9764:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9765:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9766:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9767:                             &escape($title).':'.&escape($code).':'.
                   9768:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9769:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9770:             my @items = split(/&/,$response);
                   9771:             foreach my $item (@items) {
                   9772:                 my ($key,$value) = split('=',$item);
                   9773:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9774:             }
                   9775:         }
                   9776:     }
                   9777:     return \%crsreqresponse;
                   9778: }
                   9779: 
1.1172.2.78  raeburn  9780: sub auto_export_grades {
                   9781:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9782:     my ($homeserver,%exportresponse);
                   9783:     if ($cdom =~ /^$match_domain$/) {
                   9784:         $homeserver = &domain($cdom,'primary');
                   9785:     }
                   9786:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9787:         my $info;
                   9788:         if (ref($inforef) eq 'HASH') {
                   9789:             $info = &freeze_escape($inforef);
                   9790:         }
                   9791:         if (ref($gradesref) eq 'HASH') {
                   9792:             my $grades = &freeze_escape($gradesref);
                   9793:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9794:                                 $info.':'.$grades,$homeserver);
                   9795:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9796:                 my @items = split(/&/,$response);
                   9797:                 foreach my $item (@items) {
                   9798:                     my ($key,$value) = split('=',$item);
                   9799:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9800:                 }
                   9801:             }
                   9802:         }
                   9803:     }
                   9804:     return \%exportresponse;
                   9805: }
                   9806: 
1.1172.2.68  raeburn  9807: sub check_instcode_cloning {
                   9808:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9809:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9810:         return;
                   9811:     }
                   9812:     my $canclone;
                   9813:     if (@{$code_order} > 0) {
                   9814:         my $instcoderegexp ='^';
                   9815:         my @clonecodes = split(/\&/,$cloner);
                   9816:         foreach my $item (@{$code_order}) {
                   9817:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9818:                 foreach my $pair (@clonecodes) {
                   9819:                     my ($key,$val) = split(/\=/,$pair,2);
                   9820:                     $val = &unescape($val);
                   9821:                     if ($key eq $item) {
                   9822:                         $instcoderegexp .= '('.$val.')';
                   9823:                         last;
                   9824:                     }
                   9825:                 }
                   9826:             } else {
                   9827:                 $instcoderegexp .= $codedefaults->{$item};
                   9828:             }
                   9829:         }
                   9830:         $instcoderegexp .= '$';
                   9831:         my (@from,@to);
                   9832:         eval {
                   9833:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9834:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9835:         };
                   9836:         if ((@from > 0) && (@to > 0)) {
                   9837:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9838:             if (!@diffs) {
                   9839:                 $canclone = 1;
                   9840:             }
                   9841:         }
                   9842:     }
                   9843:     return $canclone;
                   9844: }
                   9845: 
                   9846: sub default_instcode_cloning {
                   9847:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9848:     my (%codedefaults,@code_order,$canclone);
                   9849:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9850:         %codedefaults = %{$codedefaultsref};
                   9851:         @code_order = @{$codeorderref};
                   9852:     } elsif ($clonedom) {
                   9853:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9854:     }
                   9855:     if (($domdefclone) && (@code_order)) {
                   9856:         my @clonecodes = split(/\+/,$domdefclone);
                   9857:         my $instcoderegexp ='^';
                   9858:         foreach my $item (@code_order) {
                   9859:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9860:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9861:             } else {
                   9862:                 $instcoderegexp .= $codedefaults{$item};
                   9863:             }
                   9864:         }
                   9865:         $instcoderegexp .= '$';
                   9866:         my (@from,@to);
                   9867:         eval {
                   9868:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9869:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9870:         };
                   9871:         if ((@from > 0) && (@to > 0)) {
                   9872:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9873:             if (!@diffs) {
                   9874:                 $canclone = 1;
                   9875:             }
                   9876:         }
                   9877:     }
                   9878:     return $canclone;
                   9879: }
                   9880: 
1.679     raeburn  9881: # ------------------------------------------------------- Course Group routines
                   9882: 
                   9883: sub get_coursegroups {
1.809     raeburn  9884:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9885:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9886: }
                   9887: 
1.679     raeburn  9888: sub modify_coursegroup {
                   9889:     my ($cdom,$cnum,$groupsettings) = @_;
                   9890:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9891: }
                   9892: 
1.809     raeburn  9893: sub toggle_coursegroup_status {
                   9894:     my ($cdom,$cnum,$group,$action) = @_;
                   9895:     my ($from_namespace,$to_namespace);
                   9896:     if ($action eq 'delete') {
                   9897:         $from_namespace = 'coursegroups';
                   9898:         $to_namespace = 'deleted_groups';
                   9899:     } else {
                   9900:         $from_namespace = 'deleted_groups';
                   9901:         $to_namespace = 'coursegroups';
                   9902:     }
                   9903:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9904:     if (my $tmp = &error(%curr_group)) {
                   9905:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9906:         return ('read error',$tmp);
                   9907:     } else {
                   9908:         my %savedsettings = %curr_group; 
1.809     raeburn  9909:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9910:         my $deloutcome;
                   9911:         if ($result eq 'ok') {
1.809     raeburn  9912:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9913:         } else {
                   9914:             return ('write error',$result);
                   9915:         }
                   9916:         if ($deloutcome eq 'ok') {
                   9917:             return 'ok';
                   9918:         } else {
                   9919:             return ('delete error',$deloutcome);
                   9920:         }
                   9921:     }
                   9922: }
                   9923: 
1.679     raeburn  9924: sub modify_group_roles {
1.957     raeburn  9925:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9926:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9927:     my $role = 'gr/'.&escape($userprivs);
                   9928:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9929:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9930:     if ($result eq 'ok') {
                   9931:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9932:     }
1.679     raeburn  9933:     return $result;
                   9934: }
                   9935: 
                   9936: sub modify_coursegroup_membership {
                   9937:     my ($cdom,$cnum,$membership) = @_;
                   9938:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9939:     return $result;
                   9940: }
                   9941: 
1.682     raeburn  9942: sub get_active_groups {
                   9943:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9944:     my $now = time;
                   9945:     my %groups = ();
                   9946:     foreach my $key (keys(%env)) {
1.811     albertel 9947:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9948:             my ($start,$end) = split(/\./,$env{$key});
                   9949:             if (($end!=0) && ($end<$now)) { next; }
                   9950:             if (($start!=0) && ($start>$now)) { next; }
                   9951:             if ($1 eq $cdom && $2 eq $cnum) {
                   9952:                 $groups{$3} = $env{$key} ;
                   9953:             }
                   9954:         }
                   9955:     }
                   9956:     return %groups;
                   9957: }
                   9958: 
1.683     raeburn  9959: sub get_group_membership {
                   9960:     my ($cdom,$cnum,$group) = @_;
                   9961:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9962: }
                   9963: 
                   9964: sub get_users_groups {
                   9965:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9966:     my @usersgroups;
1.683     raeburn  9967:     my $cachetime=1800;
                   9968: 
                   9969:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9970:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9971:     if (defined($cached)) {
1.734     albertel 9972:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9973:     } else {  
                   9974:         $grouplist = '';
1.816     raeburn  9975:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9976:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9977:         my $access_end = $env{'course.'.$courseid.
                   9978:                               '.default_enrollment_end_date'};
                   9979:         my $now = time;
                   9980:         foreach my $key (keys(%roleshash)) {
                   9981:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9982:                 my $group = $1;
                   9983:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9984:                     my $start = $2;
                   9985:                     my $end = $1;
                   9986:                     if ($start == -1) { next; } # deleted from group
                   9987:                     if (($start!=0) && ($start>$now)) { next; }
                   9988:                     if (($end!=0) && ($end<$now)) {
                   9989:                         if ($access_end && $access_end < $now) {
                   9990:                             if ($access_end - $end < 86400) {
                   9991:                                 push(@usersgroups,$group);
1.733     raeburn  9992:                             }
                   9993:                         }
1.817     raeburn  9994:                         next;
1.733     raeburn  9995:                     }
1.817     raeburn  9996:                     push(@usersgroups,$group);
1.683     raeburn  9997:                 }
                   9998:             }
                   9999:         }
1.817     raeburn  10000:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   10001:         $grouplist = join(':',@usersgroups);
                   10002:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  10003:     }
1.733     raeburn  10004:     return @usersgroups;
1.683     raeburn  10005: }
                   10006: 
                   10007: sub devalidate_getgroups_cache {
                   10008:     my ($udom,$uname,$cdom,$cnum)=@_;
                   10009:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 10010: 
1.683     raeburn  10011:     my $hashid="$udom:$uname:$courseid";
                   10012:     &devalidate_cache_new('getgroups',$hashid);
                   10013: }
                   10014: 
1.12      www      10015: # ------------------------------------------------------------------ Plain Text
                   10016: 
                   10017: sub plaintext {
1.988     raeburn  10018:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  10019:     if ($short =~ m{^cr/}) {
1.758     albertel 10020: 	return (split('/',$short))[-1];
                   10021:     }
1.742     raeburn  10022:     if (!defined($cid)) {
                   10023:         $cid = $env{'request.course.id'};
                   10024:     }
                   10025:     my %rolenames = (
1.1008    raeburn  10026:                       Course    => 'std',
                   10027:                       Community => 'alt1',
1.742     raeburn  10028:                     );
1.1037    raeburn  10029:     if ($cid ne '') {
                   10030:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   10031:             unless ($forcedefault) {
                   10032:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   10033:                 &Apache::lonlocal::mt_escape(\$roletext);
                   10034:                 return &Apache::lonlocal::mt($roletext);
                   10035:             }
                   10036:         }
                   10037:     }
                   10038:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   10039:         (defined($rolenames{$type})) && 
                   10040:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  10041:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  10042:     } elsif ($cid ne '') {
                   10043:         my $crstype = $env{'course.'.$cid.'.type'};
                   10044:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   10045:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   10046:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   10047:         }
1.742     raeburn  10048:     }
1.1037    raeburn  10049:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      10050: }
                   10051: 
                   10052: # ----------------------------------------------------------------- Assign Role
                   10053: 
                   10054: sub assignrole {
1.957     raeburn  10055:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   10056:         $context)=@_;
1.21      www      10057:     my $mrole;
                   10058:     if ($role =~ /^cr\//) {
1.393     www      10059:         my $cwosec=$url;
1.811     albertel 10060:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      10061: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  10062:            my $refused = 1;
                   10063:            if ($context eq 'requestcourses') {
                   10064:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   10065:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   10066:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   10067:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10068:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10069:                            if ($crsenv{'internal.courseowner'} eq
                   10070:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   10071:                                $refused = '';
                   10072:                            }
                   10073:                        }
                   10074:                    }
                   10075:                }
                   10076:            }
                   10077:            if ($refused) {
                   10078:                &logthis('Refused custom assignrole: '.
                   10079:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   10080:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   10081:                return 'refused';
                   10082:            }
1.104     www      10083:         }
1.21      www      10084:         $mrole='cr';
1.678     raeburn  10085:     } elsif ($role =~ /^gr\//) {
                   10086:         my $cwogrp=$url;
1.811     albertel 10087:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  10088:         unless (&allowed('mdg',$cwogrp)) {
                   10089:             &logthis('Refused group assignrole: '.
                   10090:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   10091:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   10092:             return 'refused';
                   10093:         }
                   10094:         $mrole='gr';
1.21      www      10095:     } else {
1.82      www      10096:         my $cwosec=$url;
1.811     albertel 10097:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  10098:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   10099:             my $refused;
                   10100:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   10101:                 if (!(&allowed('c'.$role,$url))) {
                   10102:                     $refused = 1;
                   10103:                 }
                   10104:             } else {
                   10105:                 $refused = 1;
                   10106:             }
1.947     raeburn  10107:             if ($refused) {
1.1045    raeburn  10108:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10109:                 if (!$selfenroll && $context eq 'course') {
                   10110:                     my %crsenv;
                   10111:                     if ($role eq 'cc' || $role eq 'co') {
                   10112:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10113:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   10114:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   10115:                                 if ($crsenv{'internal.courseowner'} eq 
                   10116:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10117:                                     $refused = '';
                   10118:                                 }
                   10119:                             }
                   10120:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   10121:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   10122:                                 if ($crsenv{'internal.courseowner'} eq 
                   10123:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10124:                                     $refused = '';
                   10125:                                 }
                   10126:                             }
                   10127:                         }
                   10128:                     }
                   10129:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  10130:                     $refused = '';
1.1017    raeburn  10131:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  10132:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  10133:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  10134:                         my $wrongcc;
                   10135:                         if ($cnum =~ /^$match_community$/) {
                   10136:                             $wrongcc = 1 if ($role eq 'cc');
                   10137:                         } else {
                   10138:                             $wrongcc = 1 if ($role eq 'co');
                   10139:                         }
                   10140:                         unless ($wrongcc) {
                   10141:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10142:                             if ($crsenv{'internal.courseowner'} eq 
                   10143:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   10144:                                 $refused = '';
                   10145:                             }
1.1017    raeburn  10146:                         }
                   10147:                     }
1.1172.2.9  raeburn  10148:                 } elsif ($context eq 'requestauthor') {
                   10149:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   10150:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   10151:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   10152:                             $refused = '';
                   10153:                         } else {
                   10154:                             my %domdefaults = &get_domain_defaults($udom);
                   10155:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   10156:                                 my $checkbystatus;
                   10157:                                 if ($env{'user.adv'}) {
                   10158:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   10159:                                     if ($disposition eq 'automatic') {
                   10160:                                         $refused = '';
                   10161:                                     } elsif ($disposition eq '') {
                   10162:                                         $checkbystatus = 1;
                   10163:                                     }
                   10164:                                 } else {
                   10165:                                     $checkbystatus = 1;
                   10166:                                 }
                   10167:                                 if ($checkbystatus) {
                   10168:                                     if ($env{'environment.inststatus'}) {
                   10169:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   10170:                                         foreach my $type (@inststatuses) {
                   10171:                                             if (($type ne '') &&
                   10172:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   10173:                                                 $refused = '';
                   10174:                                             }
                   10175:                                         }
                   10176:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   10177:                                         $refused = '';
                   10178:                                     }
                   10179:                                 }
                   10180:                             }
                   10181:                         }
                   10182:                     }
1.1017    raeburn  10183:                 }
                   10184:                 if ($refused) {
1.947     raeburn  10185:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   10186:                              ' '.$role.' '.$end.' '.$start.' by '.
                   10187: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   10188:                     return 'refused';
                   10189:                 }
1.932     raeburn  10190:             }
1.1131    raeburn  10191:         } elsif ($role eq 'au') {
                   10192:             if ($url ne '/'.$udom.'/') {
                   10193:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   10194:                          ' to assign author role for '.$uname.':'.$udom.
                   10195:                          ' in domain: '.$url.' refused (wrong domain).');
                   10196:                 return 'refused';
                   10197:             }
1.104     www      10198:         }
1.21      www      10199:         $mrole=$role;
                   10200:     }
1.620     albertel 10201:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      10202:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      10203:     if ($end) { $command.='_'.$end; }
1.21      www      10204:     if ($start) {
                   10205: 	if ($end) { 
1.81      www      10206:            $command.='_'.$start; 
1.21      www      10207:         } else {
1.81      www      10208:            $command.='_0_'.$start;
1.21      www      10209:         }
                   10210:     }
1.739     raeburn  10211:     my $origstart = $start;
                   10212:     my $origend = $end;
1.957     raeburn  10213:     my $delflag;
1.357     www      10214: # actually delete
                   10215:     if ($deleteflag) {
1.373     www      10216: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      10217: # modify command to delete the role
1.620     albertel 10218:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      10219:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 10220: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      10221: # set start and finish to negative values for userrolelog
                   10222:            $start=-1;
                   10223:            $end=-1;
1.957     raeburn  10224:            $delflag = 1;
1.357     www      10225:         }
                   10226:     }
                   10227: # send command
1.349     www      10228:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      10229: # log new user role if status is ok
1.349     www      10230:     if ($answer eq 'ok') {
1.663     raeburn  10231: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  10232:         if (($role eq 'cc') || ($role eq 'in') ||
                   10233:             ($role eq 'ep') || ($role eq 'ad') ||
                   10234:             ($role eq 'ta') || ($role eq 'st') ||
                   10235:             ($role=~/^cr/) || ($role eq 'gr') ||
                   10236:             ($role eq 'co')) {
1.1172.2.13  raeburn  10237: # for course roles, perform group memberships changes triggered by role change.
                   10238:             unless ($role =~ /^gr/) {
                   10239:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   10240:                                                  $origstart,$selfenroll,$context);
                   10241:             }
1.1172.2.9  raeburn  10242:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10243:                            $selfenroll,$context);
                   10244:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  10245:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   10246:                  ($role eq 'da')) {
1.1172.2.9  raeburn  10247:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10248:                            $context);
                   10249:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   10250:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10251:                              $context);
                   10252:         }
1.1053    raeburn  10253:         if ($role eq 'cc') {
                   10254:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   10255:         }
1.349     www      10256:     }
                   10257:     return $answer;
1.169     harris41 10258: }
                   10259: 
1.1053    raeburn  10260: sub autoupdate_coowners {
                   10261:     my ($url,$end,$start,$uname,$udom) = @_;
                   10262:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   10263:     if (($cdom ne '') && ($cnum ne '')) {
                   10264:         my $now = time;
                   10265:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   10266:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   10267:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   10268:             my $instcode = $coursehash{'internal.coursecode'};
1.1172.2.141  raeburn  10269:             my $xlists = $coursehash{'internal.crosslistings'};
1.1053    raeburn  10270:             if ($instcode ne '') {
1.1056    raeburn  10271:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   10272:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  10273:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  10274:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1172.2.141  raeburn  10275:                         unless ($result eq 'valid') {
                   10276:                             if ($xlists ne '') {
                   10277:                                 foreach my $xlist (split(',',$xlists)) {
                   10278:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
                   10279:                                     $result =
                   10280:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
                   10281:                                                                       $inst_crosslist,$uname.':'.$udom);
                   10282:                                     last if ($result eq 'valid');
                   10283:                                 }
                   10284:                             }
                   10285:                         }
1.1056    raeburn  10286:                         if ($result eq 'valid') {
                   10287:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  10288:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10289:                                     push(@newcoowners,$coowner);
                   10290:                                 }
                   10291:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   10292:                                     push(@newcoowners,$uname.':'.$udom);
                   10293:                                 }
                   10294:                                 @newcoowners = sort(@newcoowners);
                   10295:                             } else {
                   10296:                                 push(@newcoowners,$uname.':'.$udom);
                   10297:                             }
1.1172.2.141  raeburn  10298:                         } elsif ($coursehash{'internal.co-owners'}) {
                   10299:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10300:                                 unless ($coowner eq $uname.':'.$udom) {
                   10301:                                     push(@newcoowners,$coowner);
1.1053    raeburn  10302:                                 }
                   10303:                             }
1.1172.2.141  raeburn  10304:                             unless (@newcoowners > 0) {
                   10305:                                 $delcoowners = 1;
                   10306:                                 $coowners = '';
                   10307:                             }
1.1053    raeburn  10308:                         }
                   10309:                         if (@newcoowners || $delcoowners) {
                   10310:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   10311:                                             $delcoowners,@newcoowners);
                   10312:                         }
                   10313:                     }
                   10314:                 }
                   10315:             }
                   10316:         }
                   10317:     }
                   10318: }
                   10319: 
                   10320: sub store_coowners {
                   10321:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   10322:     my $cid = $cdom.'_'.$cnum;
                   10323:     my ($coowners,$delresult,$putresult);
                   10324:     if (@newcoowners) {
                   10325:         $coowners = join(',',@newcoowners);
                   10326:         my %coownershash = (
                   10327:                             'internal.co-owners' => $coowners,
                   10328:                            );
                   10329:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   10330:         if ($putresult eq 'ok') {
                   10331:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   10332:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   10333:             }
                   10334:         }
                   10335:     }
                   10336:     if ($delcoowners) {
                   10337:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   10338:         if ($delresult eq 'ok') {
                   10339:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   10340:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   10341:             }
                   10342:         }
                   10343:     }
                   10344:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   10345:         my %crsinfo =
                   10346:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   10347:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   10348:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   10349:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   10350:         }
                   10351:     }
                   10352: }
                   10353: 
1.169     harris41 10354: # -------------------------------------------------- Modify user authentication
1.197     www      10355: # Overrides without validation
                   10356: 
1.169     harris41 10357: sub modifyuserauth {
                   10358:     my ($udom,$uname,$umode,$upass)=@_;
                   10359:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  10360:     my $allowed;
                   10361:     if (&allowed('mau',$udom)) {
                   10362:         $allowed = 1;
                   10363:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   10364:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   10365:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   10366:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10367:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10368:         if (($cdom ne '') && ($cnum ne '')) {
                   10369:             my $is_owner = &is_course_owner($cdom,$cnum);
                   10370:             if ($is_owner) {
                   10371:                 $allowed = 1;
                   10372:             }
                   10373:         }
                   10374:     }
                   10375:     unless ($allowed) { return 'refused'; }
1.197     www      10376:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 10377:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10378:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 10379:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10380: 		     &escape($upass),$uhome);
1.1172.2.134  raeburn  10381:     my $ip = &get_requestor_ip();
1.620     albertel 10382:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10383:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.134  raeburn  10384:          '(Remote '.$ip.'): '.$reply);
1.197     www      10385:     &log($udom,,$uname,$uhome,
1.620     albertel 10386:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10387:                                      $env{'user.name'}.', '.$umode.
1.1172.2.134  raeburn  10388:          '(Remote '.$ip.'): '.$reply);
1.169     harris41 10389:     unless ($reply eq 'ok') {
1.197     www      10390:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10391: 	return 'error: '.$reply;
                   10392:     }   
1.170     harris41 10393:     return 'ok';
1.80      www      10394: }
                   10395: 
1.81      www      10396: # --------------------------------------------------------------- Modify a user
1.80      www      10397: 
1.81      www      10398: sub modifyuser {
1.206     matthew  10399:     my ($udom,    $uname, $uid,
                   10400:         $umode,   $upass, $first,
                   10401:         $middle,  $last,  $gene,
1.1058    raeburn  10402:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10403:     $udom= &LONCAPA::clean_domain($udom);
                   10404:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10405:     my $showcandelete = 'none';
                   10406:     if (ref($candelete) eq 'ARRAY') {
                   10407:         if (@{$candelete} > 0) {
                   10408:             $showcandelete = join(', ',@{$candelete});
                   10409:         }
                   10410:     }
1.81      www      10411:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10412:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10413: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10414:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10415:                                      ' desiredhome not specified'). 
1.620     albertel 10416:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10417:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10418:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10419:     my $newuser;
                   10420:     if ($uhome eq 'no_host') {
                   10421:         $newuser = 1;
                   10422:     }
1.80      www      10423: # ----------------------------------------------------------------- Create User
1.406     albertel 10424:     if (($uhome eq 'no_host') && 
                   10425: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      10426:         my $unhome='';
1.844     albertel 10427:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10428:             $unhome = $desiredhome;
1.620     albertel 10429: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10430: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10431:         } else { # load balancing routine for determining $unhome
1.81      www      10432:             my $loadm=10000000;
1.841     albertel 10433: 	    my %servers = &get_servers($udom,'library');
                   10434: 	    foreach my $tryserver (keys(%servers)) {
                   10435: 		my $answer=reply('load',$tryserver);
                   10436: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10437: 		    $loadm=$answer;
                   10438: 		    $unhome=$tryserver;
                   10439: 		}
1.80      www      10440: 	    }
                   10441:         }
                   10442:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10443: 	    return 'error: unable to find a home server for '.$uname.
                   10444:                    ' in domain '.$udom;
1.80      www      10445:         }
                   10446:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10447:                          &escape($upass),$unhome);
                   10448: 	unless ($reply eq 'ok') {
                   10449:             return 'error: '.$reply;
                   10450:         }   
1.230     stredwic 10451:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10452:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10453: 	    return 'error: unable verify users home machine.';
1.80      www      10454:         }
1.209     matthew  10455:     }   # End of creation of new user
1.80      www      10456: # ---------------------------------------------------------------------- Add ID
                   10457:     if ($uid) {
                   10458:        $uid=~tr/A-Z/a-z/;
                   10459:        my %uidhash=&idrget($udom,$uname);
1.196     www      10460:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10461:          && (!$forceid)) {
1.80      www      10462: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10463: 	      return 'error: user id "'.$uid.'" does not match '.
                   10464:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10465:           }
                   10466:        } else {
                   10467: 	  &idput($udom,($uname => $uid));
                   10468:        }
                   10469:     }
                   10470: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10471:     my @tmp=&get('environment',
1.899     raeburn  10472: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10473:                     'permanentemail','inststatus'],
1.134     albertel 10474: 		   $udom,$uname);
1.1075    raeburn  10475:     my (%names,%oldnames);
1.313     matthew  10476:     if ($tmp[0] =~ m/^error:.*/) { 
                   10477:         %names=(); 
                   10478:     } else {
                   10479:         %names = @tmp;
1.1075    raeburn  10480:         %oldnames = %names;
1.313     matthew  10481:     }
1.388     www      10482: #
1.1058    raeburn  10483: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10484: # of users did not contain them), do not overwrite existing values
                   10485: # unless field is in $candelete array ref.  
                   10486: #
                   10487: 
                   10488:     my @fields = ('firstname','middlename','lastname','generation',
                   10489:                   'permanentemail','id');
                   10490:     my %newvalues;
                   10491:     if (ref($candelete) eq 'ARRAY') {
                   10492:         foreach my $field (@fields) {
                   10493:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10494:                 if ($field eq 'firstname') {
                   10495:                     $names{$field} = $first;
                   10496:                 } elsif ($field eq 'middlename') {
                   10497:                     $names{$field} = $middle;
                   10498:                 } elsif ($field eq 'lastname') {
                   10499:                     $names{$field} = $last;
                   10500:                 } elsif ($field eq 'generation') { 
                   10501:                     $names{$field} = $gene;
                   10502:                 } elsif ($field eq 'permanentemail') {
                   10503:                     $names{$field} = $email;
                   10504:                 } elsif ($field eq 'id') {
                   10505:                     $names{$field}  = $uid;
                   10506:                 }
                   10507:             }
                   10508:         }
                   10509:     }
1.388     www      10510:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10511:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10512:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10513:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10514:     if ($email) {
                   10515:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10516:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10517:     }
1.899     raeburn  10518:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10519:     if (defined($inststatus)) {
                   10520:         $names{'inststatus'} = '';
                   10521:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10522:         if (ref($usertypes) eq 'HASH') {
                   10523:             my @okstatuses; 
                   10524:             foreach my $item (split(/:/,$inststatus)) {
                   10525:                 if (defined($usertypes->{$item})) {
                   10526:                     push(@okstatuses,$item);  
                   10527:                 }
                   10528:             }
                   10529:             if (@okstatuses) {
                   10530:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10531:             }
                   10532:         }
                   10533:     }
1.1075    raeburn  10534:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10535:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10536:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10537:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10538:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10539:     } else {
                   10540:         $logmsg .= ' during self creation';
                   10541:     }
1.1075    raeburn  10542:     my $changed;
                   10543:     if ($newuser) {
                   10544:         $changed = 1;
                   10545:     } else {
                   10546:         foreach my $field (@fields) {
                   10547:             if ($names{$field} ne $oldnames{$field}) {
                   10548:                 $changed = 1;
                   10549:                 last;
                   10550:             }
                   10551:         }
                   10552:     }
                   10553:     unless ($changed) {
                   10554:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10555:         &logthis($logmsg);
                   10556:         return 'ok';
                   10557:     }
                   10558:     my $reply = &put('environment', \%names, $udom,$uname);
                   10559:     if ($reply ne 'ok') { 
                   10560:         return 'error: '.$reply;
                   10561:     }
1.1087    raeburn  10562:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10563:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10564:     }
1.1075    raeburn  10565:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10566:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10567:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10568:     &logthis($logmsg);
1.134     albertel 10569:     return 'ok';
1.80      www      10570: }
                   10571: 
1.81      www      10572: # -------------------------------------------------------------- Modify student
1.80      www      10573: 
1.81      www      10574: sub modifystudent {
                   10575:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10576:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10577:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10578:     if (!$cid) {
1.620     albertel 10579: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10580: 	    return 'not_in_class';
                   10581: 	}
1.80      www      10582:     }
                   10583: # --------------------------------------------------------------- Make the user
1.81      www      10584:     my $reply=&modifyuser
1.209     matthew  10585: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10586:          $desiredhome,$email,$inststatus);
1.80      www      10587:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10588:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10589:     # student's environment
1.297     matthew  10590:     $uid = undef if (!$forceid);
1.455     albertel 10591:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10592: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10593:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10594:     return $reply;
                   10595: }
                   10596: 
                   10597: sub modify_student_enrollment {
1.1172.2.23  raeburn  10598:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10599:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10600:     my ($cdom,$cnum,$chome);
                   10601:     if (!$cid) {
1.620     albertel 10602: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10603: 	    return 'not_in_class';
                   10604: 	}
1.620     albertel 10605: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10606: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10607:     } else {
                   10608: 	($cdom,$cnum)=split(/_/,$cid);
                   10609:     }
1.620     albertel 10610:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10611:     if (!$chome) {
1.457     raeburn  10612: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10613:     }
1.455     albertel 10614:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10615:     # Make sure the user exists
1.81      www      10616:     my $uhome=&homeserver($uname,$udom);
                   10617:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10618: 	return 'error: no such user';
                   10619:     }
1.297     matthew  10620:     # Get student data if we were not given enough information
                   10621:     if (!defined($first)  || $first  eq '' || 
                   10622:         !defined($last)   || $last   eq '' || 
                   10623:         !defined($uid)    || $uid    eq '' || 
                   10624:         !defined($middle) || $middle eq '' || 
                   10625:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10626:         # They did not supply us with enough data to enroll the student, so
                   10627:         # we need to pick up more information.
1.297     matthew  10628:         my %tmp = &get('environment',
1.294     matthew  10629:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10630:                        ,$udom,$uname);
                   10631: 
1.800     albertel 10632:         #foreach my $key (keys(%tmp)) {
                   10633:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10634:         #}
1.294     matthew  10635:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10636:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10637:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10638:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10639:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10640:     }
1.556     albertel 10641:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10642:     my $user = "$uname:$udom";
                   10643:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10644:     my $reply=cput('classlist',
1.1148    raeburn  10645: 		   {$user => 
1.1172.2.76  raeburn  10646: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10647: 		   $cdom,$cnum);
1.1148    raeburn  10648:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10649:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10650:     } else { 
1.81      www      10651: 	return 'error: '.$reply;
                   10652:     }
1.297     matthew  10653:     # Add student role to user
1.83      www      10654:     my $uurl='/'.$cid;
1.81      www      10655:     $uurl=~s/\_/\//g;
                   10656:     if ($usec) {
                   10657: 	$uurl.='/'.$usec;
                   10658:     }
1.1148    raeburn  10659:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10660:                              $selfenroll,$context);
                   10661:     if ($result ne 'ok') {
                   10662:         if ($old_entry{$user} ne '') {
                   10663:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10664:         } else {
                   10665:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10666:         }
                   10667:     }
                   10668:     return $result; 
1.21      www      10669: }
                   10670: 
1.556     albertel 10671: sub format_name {
                   10672:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10673:     my $name;
                   10674:     if ($first ne 'lastname') {
                   10675: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10676:     } else {
                   10677: 	if ($lastname=~/\S/) {
                   10678: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10679: 	    $name=~s/\s+,/,/;
                   10680: 	} else {
                   10681: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10682: 	}
                   10683:     }
                   10684:     $name=~s/^\s+//;
                   10685:     $name=~s/\s+$//;
                   10686:     $name=~s/\s+/ /g;
                   10687:     return $name;
                   10688: }
                   10689: 
1.84      www      10690: # ------------------------------------------------- Write to course preferences
                   10691: 
                   10692: sub writecoursepref {
                   10693:     my ($courseid,%prefs)=@_;
                   10694:     $courseid=~s/^\///;
                   10695:     $courseid=~s/\_/\//g;
                   10696:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10697:     my $chome=homeserver($cnum,$cdomain);
                   10698:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10699: 	return 'error: no such course';
                   10700:     }
                   10701:     my $cstring='';
1.800     albertel 10702:     foreach my $pref (keys(%prefs)) {
                   10703: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10704:     }
1.84      www      10705:     $cstring=~s/\&$//;
                   10706:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10707: }
                   10708: 
                   10709: # ---------------------------------------------------------- Make/modify course
                   10710: 
                   10711: sub createcourse {
1.741     raeburn  10712:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1172.2.146.  .1(raebu 10713:22):         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      10714:     $url=&declutter($url);
                   10715:     my $cid='';
1.1028    raeburn  10716:     if ($context eq 'requestcourses') {
                   10717:         my $can_create = 0;
                   10718:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10719:         if ($udom eq $ownerdom) {
1.1172.2.146.  .1(raebu 10720:22):             my $reload;
                   10721:22):             if (($callercontext eq 'auto') &&
                   10722:22):                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   10723:22):                 $reload = 'reload';
                   10724:22):             }
                   10725:22):             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  10726:                                   $context)) {
                   10727:                 $can_create = 1;
                   10728:             }
                   10729:         } else {
                   10730:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10731:                                            $category);
                   10732:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10733:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10734:                 if (@curr > 0) {
                   10735:                     my @options = qw(approval validate autolimit);
                   10736:                     my $optregex = join('|',@options);
                   10737:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10738:                         $can_create = 1;
                   10739:                     }
                   10740:                 }
                   10741:             }
                   10742:         }
                   10743:         if ($can_create) {
                   10744:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10745:                 unless (&allowed('ccc',$udom)) {
                   10746:                     return 'refused'; 
                   10747:                 }
1.1017    raeburn  10748:             }
                   10749:         } else {
                   10750:             return 'refused';
                   10751:         }
1.1028    raeburn  10752:     } elsif (!&allowed('ccc',$udom)) {
                   10753:         return 'refused';
1.84      www      10754:     }
1.1011    raeburn  10755: # --------------------------------------------------------------- Get Unique ID
                   10756:     my $uname;
                   10757:     if ($cnum =~ /^$match_courseid$/) {
                   10758:         my $chome=&homeserver($cnum,$udom,'true');
                   10759:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10760:             $uname = $cnum;
                   10761:         } else {
1.1038    raeburn  10762:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10763:         }
                   10764:     } else {
1.1038    raeburn  10765:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10766:     }
                   10767:     return $uname if ($uname =~ /^error/);
                   10768: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10769:     if (!defined($course_server)) {
                   10770:         if (defined(&domain($udom,'primary'))) {
                   10771:             $course_server = &domain($udom,'primary');
                   10772:         } else {
                   10773:             $course_server = $env{'user.home'}; 
                   10774:         }
                   10775:     }
                   10776:     my %host_servers =
                   10777:         &Apache::lonnet::get_servers($udom,'library');
                   10778:     unless ($host_servers{$course_server}) {
                   10779:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10780:     }
1.84      www      10781: # ------------------------------------------------------------- Make the course
                   10782:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10783:                       $course_server);
1.84      www      10784:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10785:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10786:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10787: 	return 'error: no such course';
                   10788:     }
1.271     www      10789: # ----------------------------------------------------------------- Course made
1.516     raeburn  10790: # log existence
1.1029    raeburn  10791:     my $now = time;
1.918     raeburn  10792:     my $newcourse = {
                   10793:                     $udom.'_'.$uname => {
1.921     raeburn  10794:                                      description => $description,
                   10795:                                      inst_code   => $inst_code,
                   10796:                                      owner       => $course_owner,
                   10797:                                      type        => $crstype,
1.1029    raeburn  10798:                                      creator     => $env{'user.name'}.':'.
                   10799:                                                     $env{'user.domain'},
                   10800:                                      created     => $now,
                   10801:                                      context     => $context,
1.918     raeburn  10802:                                                 },
                   10803:                     };
1.921     raeburn  10804:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10805: # set toplevel url
1.271     www      10806:     my $topurl=$url;
                   10807:     unless ($nonstandard) {
                   10808: # ------------------------------------------ For standard courses, make top url
                   10809:         my $mapurl=&clutter($url);
1.278     www      10810:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10811:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10812: <map>
                   10813: <resource id="1" type="start"></resource>
                   10814: <resource id="2" src="$mapurl"></resource>
                   10815: <resource id="3" type="finish"></resource>
                   10816: <link index="1" from="1" to="2"></link>
                   10817: <link index="2" from="2" to="3"></link>
                   10818: </map>
                   10819: ENDINITMAP
                   10820:         $topurl=&declutter(
1.638     albertel 10821:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10822:                           );
                   10823:     }
                   10824: # ----------------------------------------------------------- Write preferences
1.84      www      10825:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10826:                      ('description'              => $description,
                   10827:                       'url'                      => $topurl,
                   10828:                       'internal.creator'         => $env{'user.name'}.':'.
                   10829:                                                     $env{'user.domain'},
                   10830:                       'internal.created'         => $now,
                   10831:                       'internal.creationcontext' => $context)
                   10832:                     );
1.84      www      10833:     return '/'.$udom.'/'.$uname;
                   10834: }
                   10835: 
1.1011    raeburn  10836: # ------------------------------------------------------------------- Create ID
                   10837: sub generate_coursenum {
1.1038    raeburn  10838:     my ($udom,$crstype) = @_;
1.1011    raeburn  10839:     my $domdesc = &domain($udom);
                   10840:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10841:     my $first;
                   10842:     if ($crstype eq 'Community') {
                   10843:         $first = '0';
                   10844:     } else {
                   10845:         $first = int(1+rand(9)); 
                   10846:     } 
                   10847:     my $uname=$first.
1.1011    raeburn  10848:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10849:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10850:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10851: # ----------------------------------------------- Make sure that does not exist
                   10852:     my $uhome=&homeserver($uname,$udom,'true');
                   10853:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10854:         if ($crstype eq 'Community') {
                   10855:             $first = '0';
                   10856:         } else {
                   10857:             $first = int(1+rand(9));
                   10858:         }
                   10859:         $uname=$first.
1.1011    raeburn  10860:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10861:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10862:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10863:         $uhome=&homeserver($uname,$udom,'true');
                   10864:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10865:             return 'error: unable to generate unique course-ID';
                   10866:         }
                   10867:     }
                   10868:     return $uname;
                   10869: }
                   10870: 
1.813     albertel 10871: sub is_course {
1.1167    droeschl 10872:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10873:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10874:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10875:     my $uhome=&homeserver($cnum,$cdom);
                   10876:     my $iscourse;
                   10877:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10878:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10879:     } else {
                   10880:         my $hashid = $cdom.':'.$cnum;
                   10881:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10882:         unless (defined($cached)) {
                   10883:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10884:                                         $cnum,undef,undef,'.');
                   10885:             $iscourse = 0;
                   10886:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10887:                 $iscourse = 1;
                   10888:             }
                   10889:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10890:         }
                   10891:     }
                   10892:     return unless($iscourse);
1.1167    droeschl 10893:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10894: }
                   10895: 
1.1015    raeburn  10896: sub store_userdata {
                   10897:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10898:     my $result;
1.1016    raeburn  10899:     if ($datakey ne '') {
1.1013    raeburn  10900:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10901:             if ($udom eq '' || $uname eq '') {
                   10902:                 $udom = $env{'user.domain'};
                   10903:                 $uname = $env{'user.name'};
                   10904:             }
                   10905:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10906:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10907:                 $result = 'error: no_host';
                   10908:             } else {
1.1172.2.138  raeburn  10909:                 $storehash->{'ip'} = &get_requestor_ip();
1.1013    raeburn  10910:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10911: 
                   10912:                 my $namevalue='';
                   10913:                 foreach my $key (keys(%{$storehash})) {
                   10914:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10915:                 }
                   10916:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10917:                 unless ($namespace eq 'courserequests') {
                   10918:                     $datakey = &escape($datakey);
                   10919:                 }
1.1105    raeburn  10920:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10921:                                   $namevalue,$uhome);
1.1013    raeburn  10922:             }
                   10923:         } else {
                   10924:             $result = 'error: data to store was not a hash reference'; 
                   10925:         }
                   10926:     } else {
                   10927:         $result= 'error: invalid requestkey'; 
                   10928:     }
                   10929:     return $result;
                   10930: }
                   10931: 
1.21      www      10932: # ---------------------------------------------------------- Assign Custom Role
                   10933: 
                   10934: sub assigncustomrole {
1.957     raeburn  10935:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10936:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10937:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10938: }
                   10939: 
                   10940: # ----------------------------------------------------------------- Revoke Role
                   10941: 
                   10942: sub revokerole {
1.957     raeburn  10943:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10944:     my $now=time;
1.965     raeburn  10945:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10946: }
                   10947: 
                   10948: # ---------------------------------------------------------- Revoke Custom Role
                   10949: 
                   10950: sub revokecustomrole {
1.957     raeburn  10951:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10952:     my $now=time;
1.357     www      10953:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10954:            $deleteflag,$selfenroll,$context);
1.17      www      10955: }
                   10956: 
1.533     banghart 10957: # ------------------------------------------------------------ Disk usage
1.535     albertel 10958: sub diskusage {
1.955     raeburn  10959:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10960:     $directorypath =~ s/\/$//;
                   10961:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10962:                        .&escape($getpropath).':'.&escape($uname).':'
                   10963:                        .&escape($udom),homeserver($uname,$udom));
                   10964:     if ($listing eq 'unknown_cmd') {
                   10965:         if ($getpropath) {
                   10966:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10967:         }
                   10968:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10969:     }
1.514     albertel 10970:     return $listing;
1.512     banghart 10971: }
                   10972: 
1.566     banghart 10973: sub is_locked {
1.1096    raeburn  10974:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10975:     my @check;
                   10976:     my $is_locked;
1.1093    raeburn  10977:     push (@check,$file_name);
1.613     albertel 10978:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10979: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10980:     my ($tmp)=keys(%locked);
                   10981:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10982:     
1.566     banghart 10983:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10984:         $is_locked = 'false';
                   10985:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10986:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10987:                $is_locked = 'true';
1.1096    raeburn  10988:                if (ref($which) eq 'ARRAY') {
                   10989:                    push(@{$which},$entry);
                   10990:                } else {
                   10991:                    last;
                   10992:                }
1.745     raeburn  10993:            }
                   10994:        }
1.566     banghart 10995:     } else {
                   10996:         $is_locked = 'false';
                   10997:     }
1.1093    raeburn  10998:     return $is_locked;
1.566     banghart 10999: }
                   11000: 
1.759     albertel 11001: sub declutter_portfile {
                   11002:     my ($file) = @_;
1.833     albertel 11003:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 11004:     return $file;
                   11005: }
                   11006: 
1.559     banghart 11007: # ------------------------------------------------------------- Mark as Read Only
                   11008: 
                   11009: sub mark_as_readonly {
                   11010:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 11011:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11012:     my ($tmp)=keys(%current_permissions);
                   11013:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 11014:     foreach my $file (@{$files}) {
1.759     albertel 11015: 	$file = &declutter_portfile($file);
1.561     banghart 11016:         push(@{$current_permissions{$file}},$what);
1.559     banghart 11017:     }
1.613     albertel 11018:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11019:     return;
                   11020: }
                   11021: 
1.572     banghart 11022: # ------------------------------------------------------------Save Selected Files
                   11023: 
                   11024: sub save_selected_files {
                   11025:     my ($user, $path, @files) = @_;
                   11026:     my $filename = $user."savedfiles";
1.573     banghart 11027:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  11028:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 11029:     foreach my $file (@files) {
1.620     albertel 11030:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 11031:     }
                   11032:     foreach my $file (@other_files) {
1.574     banghart 11033:         print (OUT $file."\n");
1.572     banghart 11034:     }
1.574     banghart 11035:     close (OUT);
1.572     banghart 11036:     return 'ok';
                   11037: }
                   11038: 
1.574     banghart 11039: sub clear_selected_files {
                   11040:     my ($user) = @_;
                   11041:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  11042:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 11043:     print (OUT undef);
                   11044:     close (OUT);
                   11045:     return ("ok");    
                   11046: }
                   11047: 
1.572     banghart 11048: sub files_in_path {
                   11049:     my ($user, $path) = @_;
                   11050:     my $filename = $user."savedfiles";
                   11051:     my %return_files;
1.1172.2.96  raeburn  11052:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 11053:     while (my $line_in = <IN>) {
1.574     banghart 11054:         chomp ($line_in);
                   11055:         my @paths_and_file = split (m!/!, $line_in);
                   11056:         my $file_part = pop (@paths_and_file);
                   11057:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 11058:         $path_part.='/';
                   11059:         my $path_and_file = $path_part.$file_part;
                   11060:         if ($path_part eq $path) {
                   11061:             $return_files{$file_part}= 'selected';
                   11062:         }
                   11063:     }
1.574     banghart 11064:     close (IN);
                   11065:     return (\%return_files);
1.572     banghart 11066: }
                   11067: 
                   11068: # called in portfolio select mode, to show files selected NOT in current directory
                   11069: sub files_not_in_path {
                   11070:     my ($user, $path) = @_;
                   11071:     my $filename = $user."savedfiles";
                   11072:     my @return_files;
                   11073:     my $path_part;
1.1172.2.96  raeburn  11074:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 11075:     while (my $line = <IN>) {
1.572     banghart 11076:         #ok, I know it's clunky, but I want it to work
1.800     albertel 11077:         my @paths_and_file = split(m|/|, $line);
                   11078:         my $file_part = pop(@paths_and_file);
                   11079:         chomp($file_part);
                   11080:         my $path_part = join('/', @paths_and_file);
1.572     banghart 11081:         $path_part .= '/';
                   11082:         my $path_and_file = $path_part.$file_part;
                   11083:         if ($path_part ne $path) {
1.800     albertel 11084:             push(@return_files, ($path_and_file));
1.572     banghart 11085:         }
                   11086:     }
1.800     albertel 11087:     close(OUT);
1.574     banghart 11088:     return (@return_files);
1.572     banghart 11089: }
                   11090: 
1.745     raeburn  11091: #----------------------------------------------Get portfolio file permissions
1.629     banghart 11092: 
1.745     raeburn  11093: sub get_portfile_permissions {
                   11094:     my ($domain,$user) = @_;
1.613     albertel 11095:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11096:     my ($tmp)=keys(%current_permissions);
                   11097:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11098:     return \%current_permissions;
                   11099: }
                   11100: 
                   11101: #---------------------------------------------Get portfolio file access controls
                   11102: 
1.749     raeburn  11103: sub get_access_controls {
1.745     raeburn  11104:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 11105:     my %access;
                   11106:     my $real_file = $file;
                   11107:     $file =~ s/\.meta$//;
1.745     raeburn  11108:     if (defined($file)) {
1.749     raeburn  11109:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   11110:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 11111:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  11112:             }
                   11113:         }
1.745     raeburn  11114:     } else {
1.749     raeburn  11115:         foreach my $key (keys(%{$current_permissions})) {
                   11116:             if ($key =~ /\0accesscontrol$/) {
                   11117:                 if (defined($group)) {
                   11118:                     if ($key !~ m-^\Q$group\E/-) {
                   11119:                         next;
                   11120:                     }
                   11121:                 }
                   11122:                 my ($fullpath) = split(/\0/,$key);
                   11123:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   11124:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   11125:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   11126:                     }
                   11127:                 }
                   11128:             }
                   11129:         }
                   11130:     }
                   11131:     return %access;
                   11132: }
                   11133: 
                   11134: sub modify_access_controls {
                   11135:     my ($file_name,$changes,$domain,$user)=@_;
                   11136:     my ($outcome,$deloutcome);
                   11137:     my %store_permissions;
                   11138:     my %new_values;
                   11139:     my %new_control;
                   11140:     my %translation;
                   11141:     my @deletions = ();
                   11142:     my $now = time;
                   11143:     if (exists($$changes{'activate'})) {
                   11144:         if (ref($$changes{'activate'}) eq 'HASH') {
                   11145:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   11146:             my $numnew = scalar(@newitems);
                   11147:             for (my $i=0; $i<$numnew; $i++) {
                   11148:                 my $newkey = $newitems[$i];
                   11149:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  11150:                 if ($newkey =~ /^\d+:/) { 
                   11151:                     $newkey =~ s/^(\d+)/$newid/;
                   11152:                     $translation{$1} = $newid;
                   11153:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   11154:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   11155:                     $translation{$1} = $newid;
                   11156:                 }
1.749     raeburn  11157:                 $new_values{$file_name."\0".$newkey} = 
                   11158:                                           $$changes{'activate'}{$newitems[$i]};
                   11159:                 $new_control{$newkey} = $now;
                   11160:             }
                   11161:         }
                   11162:     }
                   11163:     my %todelete;
                   11164:     my %changed_items;
                   11165:     foreach my $action ('delete','update') {
                   11166:         if (exists($$changes{$action})) {
                   11167:             if (ref($$changes{$action}) eq 'HASH') {
                   11168:                 foreach my $key (keys(%{$$changes{$action}})) {
                   11169:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   11170:                     if ($action eq 'delete') { 
                   11171:                         $todelete{$itemnum} = 1;
                   11172:                     } else {
                   11173:                         $changed_items{$itemnum} = $key;
                   11174:                     }
                   11175:                 }
1.745     raeburn  11176:             }
                   11177:         }
1.749     raeburn  11178:     }
                   11179:     # get lock on access controls for file.
                   11180:     my $lockhash = {
                   11181:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   11182:                                                        ':'.$env{'user.domain'},
                   11183:                    }; 
                   11184:     my $tries = 0;
                   11185:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11186:    
1.1172.2.79  raeburn  11187:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  11188:         $tries ++;
1.1172.2.79  raeburn  11189:         sleep(0.1);
1.749     raeburn  11190:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11191:     }
                   11192:     if ($gotlock eq 'ok') {
                   11193:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   11194:         my ($tmp)=keys(%curr_permissions);
                   11195:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   11196:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   11197:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   11198:             if (ref($curr_controls) eq 'HASH') {
                   11199:                 foreach my $control_item (keys(%{$curr_controls})) {
                   11200:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   11201:                     if (defined($todelete{$itemnum})) {
                   11202:                         push(@deletions,$file_name."\0".$control_item);
                   11203:                     } else {
                   11204:                         if (defined($changed_items{$itemnum})) {
                   11205:                             $new_control{$changed_items{$itemnum}} = $now;
                   11206:                             push(@deletions,$file_name."\0".$control_item);
                   11207:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   11208:                         } else {
                   11209:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   11210:                         }
                   11211:                     }
1.745     raeburn  11212:                 }
                   11213:             }
                   11214:         }
1.970     raeburn  11215:         my ($group);
                   11216:         if (&is_course($domain,$user)) {
                   11217:             ($group,my $file) = split(/\//,$file_name,2);
                   11218:         }
1.749     raeburn  11219:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   11220:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   11221:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   11222:         #  remove lock
                   11223:         my @del_lock = ($file_name."\0".'locked_access_records');
                   11224:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  11225:         my $sqlresult =
1.970     raeburn  11226:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  11227:                                     $group);
1.749     raeburn  11228:     } else {
                   11229:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  11230:     }
1.749     raeburn  11231:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  11232: }
                   11233: 
1.827     raeburn  11234: sub make_public_indefinitely {
                   11235:     my ($requrl) = @_;
                   11236:     my $now = time;
                   11237:     my $action = 'activate';
                   11238:     my $aclnum = 0;
                   11239:     if (&is_portfolio_url($requrl)) {
                   11240:         my (undef,$udom,$unum,$file_name,$group) =
                   11241:             &parse_portfolio_url($requrl);
                   11242:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   11243:         my %access_controls = &get_access_controls($current_perms,
                   11244:                                                    $group,$file_name);
                   11245:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   11246:             my ($num,$scope,$end,$start) = 
                   11247:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   11248:             if ($scope eq 'public') {
                   11249:                 if ($start <= $now && $end == 0) {
                   11250:                     $action = 'none';
                   11251:                 } else {
                   11252:                     $action = 'update';
                   11253:                     $aclnum = $num;
                   11254:                 }
                   11255:                 last;
                   11256:             }
                   11257:         }
                   11258:         if ($action eq 'none') {
                   11259:              return 'ok';
                   11260:         } else {
                   11261:             my %changes;
                   11262:             my $newend = 0;
                   11263:             my $newstart = $now;
                   11264:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   11265:             $changes{$action}{$newkey} = {
                   11266:                 type => 'public',
                   11267:                 time => {
                   11268:                     start => $newstart,
                   11269:                     end   => $newend,
                   11270:                 },
                   11271:             };
                   11272:             my ($outcome,$deloutcome,$new_values,$translation) =
                   11273:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   11274:             return $outcome;
                   11275:         }
                   11276:     } else {
                   11277:         return 'invalid';
                   11278:     }
                   11279: }
                   11280: 
1.745     raeburn  11281: #------------------------------------------------------Get Marked as Read Only
                   11282: 
                   11283: sub get_marked_as_readonly {
                   11284:     my ($domain,$user,$what,$group) = @_;
                   11285:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 11286:     my @readonly_files;
1.629     banghart 11287:     my $cmp1=$what;
                   11288:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  11289:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11290:         if (defined($group)) {
                   11291:             if ($file_name !~ m-^\Q$group\E/-) {
                   11292:                 next;
                   11293:             }
                   11294:         }
1.561     banghart 11295:         if (ref($value) eq "ARRAY"){
                   11296:             foreach my $stored_what (@{$value}) {
1.629     banghart 11297:                 my $cmp2=$stored_what;
1.759     albertel 11298:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  11299:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  11300:                 }
1.629     banghart 11301:                 if ($cmp1 eq $cmp2) {
1.561     banghart 11302:                     push(@readonly_files, $file_name);
1.745     raeburn  11303:                     last;
1.563     banghart 11304:                 } elsif (!defined($what)) {
                   11305:                     push(@readonly_files, $file_name);
1.745     raeburn  11306:                     last;
1.561     banghart 11307:                 }
                   11308:             }
1.745     raeburn  11309:         }
1.561     banghart 11310:     }
                   11311:     return @readonly_files;
                   11312: }
1.577     banghart 11313: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 11314: 
1.577     banghart 11315: sub get_marked_as_readonly_hash {
1.745     raeburn  11316:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 11317:     my %readonly_files;
1.745     raeburn  11318:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11319:         if (defined($group)) {
                   11320:             if ($file_name !~ m-^\Q$group\E/-) {
                   11321:                 next;
                   11322:             }
                   11323:         }
1.577     banghart 11324:         if (ref($value) eq "ARRAY"){
                   11325:             foreach my $stored_what (@{$value}) {
1.745     raeburn  11326:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 11327:                     foreach my $lock_descriptor(@{$stored_what}) {
                   11328:                         if ($lock_descriptor eq 'graded') {
                   11329:                             $readonly_files{$file_name} = 'graded';
                   11330:                         } elsif ($lock_descriptor eq 'handback') {
                   11331:                             $readonly_files{$file_name} = 'handback';
                   11332:                         } else {
                   11333:                             if (!exists($readonly_files{$file_name})) {
                   11334:                                 $readonly_files{$file_name} = 'locked';
                   11335:                             }
                   11336:                         }
1.745     raeburn  11337:                     }
1.750     banghart 11338:                 } 
1.577     banghart 11339:             }
                   11340:         } 
                   11341:     }
                   11342:     return %readonly_files;
                   11343: }
1.559     banghart 11344: # ------------------------------------------------------------ Unmark as Read Only
                   11345: 
                   11346: sub unmark_as_readonly {
1.629     banghart 11347:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   11348:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  11349:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 11350:     $file_name = &declutter_portfile($file_name);
1.634     albertel 11351:     my $symb_crs = $what;
                   11352:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  11353:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 11354:     my ($tmp)=keys(%current_permissions);
                   11355:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11356:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 11357:     foreach my $file (@readonly_files) {
1.759     albertel 11358: 	my $clean_file = &declutter_portfile($file);
                   11359: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 11360: 	my $current_locks = $current_permissions{$file};
1.563     banghart 11361:         my @new_locks;
                   11362:         my @del_keys;
                   11363:         if (ref($current_locks) eq "ARRAY"){
                   11364:             foreach my $locker (@{$current_locks}) {
1.632     albertel 11365:                 my $compare=$locker;
1.749     raeburn  11366:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  11367:                     $compare=join('',@{$locker});
1.746     raeburn  11368:                     if ($compare ne $symb_crs) {
                   11369:                         push(@new_locks, $locker);
                   11370:                     }
1.563     banghart 11371:                 }
                   11372:             }
1.650     albertel 11373:             if (scalar(@new_locks) > 0) {
1.563     banghart 11374:                 $current_permissions{$file} = \@new_locks;
                   11375:             } else {
                   11376:                 push(@del_keys, $file);
1.613     albertel 11377:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11378:                 delete($current_permissions{$file});
1.563     banghart 11379:             }
                   11380:         }
1.561     banghart 11381:     }
1.613     albertel 11382:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11383:     return;
                   11384: }
1.512     banghart 11385: 
1.17      www      11386: # ------------------------------------------------------------ Directory lister
                   11387: 
                   11388: sub dirlist {
1.955     raeburn  11389:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11390:     $uri=~s/^\///;
                   11391:     $uri=~s/\/$//;
1.253     stredwic 11392:     my ($udom, $uname);
1.955     raeburn  11393:     if ($getuserdir) {
1.253     stredwic 11394:         $udom = $userdomain;
                   11395:         $uname = $username;
1.955     raeburn  11396:     } else {
                   11397:         (undef,$udom,$uname)=split(/\//,$uri);
                   11398:         if(defined($userdomain)) {
                   11399:             $udom = $userdomain;
                   11400:         }
                   11401:         if(defined($username)) {
                   11402:             $uname = $username;
                   11403:         }
1.253     stredwic 11404:     }
1.955     raeburn  11405:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11406: 
1.955     raeburn  11407:     $dirRoot = $perlvar{'lonDocRoot'};
                   11408:     if (defined($getpropath)) {
                   11409:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11410:         $dirRoot =~ s/\/$//;
1.955     raeburn  11411:     } elsif (defined($getuserdir)) {
                   11412:         my $subdir=$uname.'__';
                   11413:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11414:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11415:                    ."/$udom/$subdir/$uname";
                   11416:     } elsif (defined($alternateRoot)) {
                   11417:         $dirRoot = $alternateRoot;
1.751     banghart 11418:     }
1.253     stredwic 11419: 
                   11420:     if($udom) {
                   11421:         if($uname) {
1.1135    raeburn  11422:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11423:             if ($uhome eq 'no_host') {
                   11424:                 return ([],'no_host');
                   11425:             }
1.955     raeburn  11426:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11427:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11428:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11429:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11430:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11431:             } else {
                   11432:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11433:             }
1.605     matthew  11434:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11435:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11436:                 @listing_results = split(/:/,$listing);
                   11437:             } else {
                   11438:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11439:             }
1.1135    raeburn  11440:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11441:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11442:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11443:                 return ([],$listing);
                   11444:             } else {
                   11445:                 return (\@listing_results);
1.1135    raeburn  11446:             }
1.955     raeburn  11447:         } elsif(!$alternateRoot) {
1.1136    raeburn  11448:             my (%allusers,%listerror);
1.841     albertel 11449: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11450:  	    foreach my $tryserver (keys(%servers)) {
                   11451:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11452:                                   &escape($udom),$tryserver);
                   11453:                 if ($listing eq 'unknown_cmd') {
                   11454: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11455: 				      $udom, $tryserver);
                   11456:                 } else {
                   11457:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11458:                 }
1.841     albertel 11459: 		if ($listing eq 'unknown_cmd') {
                   11460: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11461: 				      $udom, $tryserver);
                   11462: 		    @listing_results = split(/:/,$listing);
                   11463: 		} else {
                   11464: 		    @listing_results =
                   11465: 			map { &unescape($_); } split(/:/,$listing);
                   11466: 		}
1.1136    raeburn  11467:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11468:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11469:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11470:                     $listerror{$tryserver} = $listing;
                   11471:                 } else {
1.841     albertel 11472: 		    foreach my $line (@listing_results) {
                   11473: 			my ($entry) = split(/&/,$line,2);
                   11474: 			$allusers{$entry} = 1;
                   11475: 		    }
                   11476: 		}
1.253     stredwic 11477:             }
1.1136    raeburn  11478:             my @alluserslist=();
1.800     albertel 11479:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11480:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11481:             }
1.1172.2.80  raeburn  11482:             if (!%listerror) {
                   11483:                 # no errors
                   11484:                 return (\@alluserslist);
                   11485:             } elsif (scalar(keys(%servers)) == 1) {
                   11486:                 # one library server, one error
                   11487:                 my ($key) = keys(%listerror);
                   11488:                 return (\@alluserslist, $listerror{$key});
                   11489:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11490:                 # con_lost indicates that we might miss data from at least one
                   11491:                 # library server
                   11492:                 return (\@alluserslist, 'con_lost');
                   11493:             } else {
                   11494:                 # multiple library servers and no con_lost -> data should be
                   11495:                 # complete.
                   11496:                 return (\@alluserslist);
                   11497:             }
                   11498: 
1.253     stredwic 11499:         } else {
1.1136    raeburn  11500:             return ([],'missing username');
1.253     stredwic 11501:         }
1.955     raeburn  11502:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11503:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11504:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11505:         return (\@all_domains);
1.955     raeburn  11506:     } else {
1.1136    raeburn  11507:         return ([],'missing domain');
1.275     stredwic 11508:     }
                   11509: }
                   11510: 
                   11511: # --------------------------------------------- GetFileTimestamp
                   11512: # This function utilizes dirlist and returns the date stamp for
                   11513: # when it was last modified.  It will also return an error of -1
                   11514: # if an error occurs
                   11515: 
                   11516: sub GetFileTimestamp {
1.955     raeburn  11517:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11518:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11519:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11520:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11521:                                     undef,$getuserdir);
                   11522:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11523:         return -1;
                   11524:     }
                   11525:     if (ref($fileref) eq 'ARRAY') {
                   11526:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11527:         # @stats contains first the filename, then the stat output
                   11528:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11529:     } else {
                   11530:         return -1;
1.253     stredwic 11531:     }
1.26      www      11532: }
                   11533: 
1.712     albertel 11534: sub stat_file {
                   11535:     my ($uri) = @_;
1.787     albertel 11536:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11537: 
1.955     raeburn  11538:     my ($udom,$uname,$file);
1.712     albertel 11539:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11540: 	($udom,$uname,$file) =
1.811     albertel 11541: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11542: 	$file = 'userfiles/'.$file;
                   11543:     }
                   11544:     if ($uri =~ m-^/res/-) {
                   11545: 	($udom,$uname) = 
1.807     albertel 11546: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11547: 	$file = $uri;
                   11548:     }
                   11549: 
                   11550:     if (!$udom || !$uname || !$file) {
                   11551: 	# unable to handle the uri
                   11552: 	return ();
                   11553:     }
1.956     raeburn  11554:     my $getpropath;
                   11555:     if ($file =~ /^userfiles\//) {
                   11556:         $getpropath = 1;
                   11557:     }
1.1136    raeburn  11558:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11559:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11560:         return ();
                   11561:     } else {
                   11562:         if (ref($listref) eq 'ARRAY') {
                   11563:             my @stats = split('&',$listref->[0]);
                   11564: 	    shift(@stats); #filename is first
                   11565: 	    return @stats;
                   11566:         }
1.712     albertel 11567:     }
                   11568:     return ();
                   11569: }
                   11570: 
1.26      www      11571: # -------------------------------------------------------- Value of a Condition
                   11572: 
1.713     albertel 11573: # gets the value of a specific preevaluated condition
                   11574: #    stored in the string  $env{user.state.<cid>}
                   11575: # or looks up a condition reference in the bighash and if if hasn't
                   11576: # already been evaluated recurses into docondval to get the value of
                   11577: # the condition, then memoizing it to 
                   11578: #   $env{user.state.<cid>.<condition>}
1.40      www      11579: sub directcondval {
                   11580:     my $number=shift;
1.620     albertel 11581:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11582: 	&Apache::lonuserstate::evalstate();
                   11583:     }
1.713     albertel 11584:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11585: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11586:     } elsif ($number =~ /^_/) {
                   11587: 	my $sub_condition;
                   11588: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11589: 		&GDBM_READER(),0640)) {
                   11590: 	    $sub_condition=$bighash{'conditions'.$number};
                   11591: 	    untie(%bighash);
                   11592: 	}
                   11593: 	my $value = &docondval($sub_condition);
1.949     raeburn  11594: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11595: 	return $value;
                   11596:     }
1.620     albertel 11597:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11598:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11599:     } else {
                   11600:        return 2;
                   11601:     }
                   11602: }
                   11603: 
1.713     albertel 11604: # get the collection of conditions for this resource
1.26      www      11605: sub condval {
                   11606:     my $condidx=shift;
1.54      www      11607:     my $allpathcond='';
1.713     albertel 11608:     foreach my $cond (split(/\|/,$condidx)) {
                   11609: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11610: 	    $allpathcond.=
                   11611: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11612: 	}
1.191     harris41 11613:     }
1.54      www      11614:     $allpathcond=~s/\|$//;
1.713     albertel 11615:     return &docondval($allpathcond);
                   11616: }
                   11617: 
                   11618: #evaluates an expression of conditions
                   11619: sub docondval {
                   11620:     my ($allpathcond) = @_;
                   11621:     my $result=0;
                   11622:     if ($env{'request.course.id'}
                   11623: 	&& defined($allpathcond)) {
                   11624: 	my $operand='|';
                   11625: 	my @stack;
                   11626: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11627: 	    if ($chunk eq '(') {
                   11628: 		push @stack,($operand,$result);
                   11629: 	    } elsif ($chunk eq ')') {
                   11630: 		my $before=pop @stack;
                   11631: 		if (pop @stack eq '&') {
                   11632: 		    $result=$result>$before?$before:$result;
                   11633: 		} else {
                   11634: 		    $result=$result>$before?$result:$before;
                   11635: 		}
                   11636: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11637: 		$operand=$chunk;
                   11638: 	    } else {
                   11639: 		my $new=directcondval($chunk);
                   11640: 		if ($operand eq '&') {
                   11641: 		    $result=$result>$new?$new:$result;
                   11642: 		} else {
                   11643: 		    $result=$result>$new?$result:$new;
                   11644: 		}
                   11645: 	    }
                   11646: 	}
1.26      www      11647:     }
                   11648:     return $result;
1.421     albertel 11649: }
                   11650: 
                   11651: # ---------------------------------------------------- Devalidate courseresdata
                   11652: 
                   11653: sub devalidatecourseresdata {
                   11654:     my ($coursenum,$coursedomain)=@_;
                   11655:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11656:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11657: }
                   11658: 
1.763     www      11659: 
1.200     www      11660: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11661: #
                   11662: #  Parameters:
                   11663: #      $coursenum    - Number of the course.
                   11664: #      $coursedomain - Domain at which the course was created.
                   11665: #  Returns:
                   11666: #     A hash of the course parameters along (I think) with timestamps
                   11667: #     and version info.
1.877     foxr     11668: 
1.624     albertel 11669: sub get_courseresdata {
                   11670:     my ($coursenum,$coursedomain)=@_;
1.200     www      11671:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11672:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11673:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11674:     my %dumpreply;
1.417     albertel 11675:     unless (defined($cached)) {
1.624     albertel 11676: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11677: 	$result=\%dumpreply;
1.251     albertel 11678: 	my ($tmp) = keys(%dumpreply);
                   11679: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11680: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11681: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11682: 	    return $tmp;
1.416     albertel 11683: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11684: 	    $result=undef;
1.599     albertel 11685: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11686: 	}
                   11687:     }
1.624     albertel 11688:     return $result;
                   11689: }
                   11690: 
1.633     albertel 11691: sub devalidateuserresdata {
                   11692:     my ($uname,$udom)=@_;
                   11693:     my $hashid="$udom:$uname";
                   11694:     &devalidate_cache_new('userres',$hashid);
                   11695: }
                   11696: 
1.624     albertel 11697: sub get_userresdata {
                   11698:     my ($uname,$udom)=@_;
                   11699:     #most student don\'t have any data set, check if there is some data
                   11700:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11701: 
                   11702:     my $hashid="$udom:$uname";
                   11703:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11704:     if (!defined($cached)) {
                   11705: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11706: 	$result=\%resourcedata;
                   11707: 	&do_cache_new('userres',$hashid,$result,600);
                   11708:     }
                   11709:     my ($tmp)=keys(%$result);
                   11710:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11711: 	return $result;
                   11712:     }
                   11713:     #error 2 occurs when the .db doesn't exist
                   11714:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11715:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11716: 	    &logthis("<font color=\"blue\">WARNING:".
                   11717: 		     " Trying to get resource data for ".
                   11718: 		     $uname." at ".$udom.": ".
                   11719: 		     $tmp."</font>");
                   11720:         }
1.624     albertel 11721:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11722: 	#&EXT_cache_set($udom,$uname);
                   11723: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11724: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11725:     }
                   11726:     return $tmp;
                   11727: }
1.879     foxr     11728: #----------------------------------------------- resdata - return resource data
                   11729: #  Purpose:
                   11730: #    Return resource data for either users or for a course.
                   11731: #  Parameters:
                   11732: #     $name      - Course/user name.
                   11733: #     $domain    - Name of the domain the user/course is registered on.
                   11734: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   11735: #     @which     - Array of names of resources desired.
                   11736: #  Returns:
                   11737: #     The value of the first reasource in @which that is found in the
                   11738: #     resource hash.
                   11739: #  Exceptional Conditions:
                   11740: #     If the $type passed in is not valid (not the string 'course' or 
                   11741: #     'user', an undefined  reference is returned.
                   11742: #     If none of the resources are found, an undef is returned
1.624     albertel 11743: sub resdata {
                   11744:     my ($name,$domain,$type,@which)=@_;
                   11745:     my $result;
                   11746:     if ($type eq 'course') {
                   11747: 	$result=&get_courseresdata($name,$domain);
                   11748:     } elsif ($type eq 'user') {
                   11749: 	$result=&get_userresdata($name,$domain);
                   11750:     }
                   11751:     if (!ref($result)) { return $result; }    
1.251     albertel 11752:     foreach my $item (@which) {
1.927     albertel 11753: 	if (defined($result->{$item->[0]})) {
                   11754: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11755: 	}
1.250     albertel 11756:     }
1.291     albertel 11757:     return undef;
1.200     www      11758: }
                   11759: 
1.1172.2.146.  .1(raebu 11760:22): sub get_domain_lti {
                   11761:22):     my ($cdom,$context) = @_;
          .4(raebu 11762:22):     my ($name,$cachename,%lti);
          .1(raebu 11763:22):     if ($context eq 'consumer') {
                   11764:22):         $name = 'ltitools';
                   11765:22):     } elsif ($context eq 'provider') {
                   11766:22):         $name = 'lti';
          .4(raebu 11767:22):     } elsif ($context eq 'linkprot') {
                   11768:22):         $name = 'ltisec';
          .1(raebu 11769:22):     } else {
                   11770:22):         return %lti;
                   11771:22):     }
          .4(raebu 11772:22): 
                   11773:22):     if ($context eq 'linkprot') {
                   11774:22):         $cachename = $context;
                   11775:22):     } else {
                   11776:22):         $cachename = $name;
                   11777:22):     }
                   11778:22): 
                   11779:22):     my ($result,$cached)=&is_cached_new($cachename,$cdom);
          .1(raebu 11780:22):     if (defined($cached)) {
                   11781:22):         if (ref($result) eq 'HASH') {
                   11782:22):             %lti = %{$result};
                   11783:22):         }
                   11784:22):     } else {
                   11785:22):         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   11786:22):         if (ref($domconfig{$name}) eq 'HASH') {
          .4(raebu 11787:22):             if ($context eq 'linkprot') {
                   11788:22):                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
                   11789:22):                     %lti = %{$domconfig{$name}{'linkprot'}};
                   11790:22):                 }
                   11791:22):             } else {
                   11792:22):                 %lti = %{$domconfig{$name}};
                   11793:22):             }
                   11794:22):             if (($context eq 'consumer') && (keys(%lti))) {
                   11795:22):                 my %encdomconfig = &get_dom('encconfig',[$name],$cdom,undef,1);
                   11796:22):                 if (ref($encdomconfig{$name}) eq 'HASH') {
                   11797:22):                     foreach my $id (keys(%lti)) {
                   11798:22):                         if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
                   11799:22):                             foreach my $item ('key','secret') {
                   11800:22):                                 $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
                   11801:22):                             }
          .1(raebu 11802:22):                         }
                   11803:22):                     }
                   11804:22):                 }
                   11805:22):             }
                   11806:22):         }
                   11807:22):         my $cachetime = 24*60*60;
          .4(raebu 11808:22):         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
          .1(raebu 11809:22):     }
                   11810:22):     return %lti;
                   11811:22): }
                   11812:22): 
                   11813:22): sub get_course_lti {
                   11814:22):     my ($cnum,$cdom) = @_;
                   11815:22):     my $hashid=$cdom.'_'.$cnum;
                   11816:22):     my %courselti;
                   11817:22):     my ($result,$cached)=&is_cached_new('courselti',$hashid);
                   11818:22):     if (defined($cached)) {
                   11819:22):         if (ref($result) eq 'HASH') {
                   11820:22):             %courselti = %{$result};
                   11821:22):         }
                   11822:22):     } else {
                   11823:22):         %courselti = &dump('lti',$cdom,$cnum,undef,undef,undef,1);
                   11824:22):         my $cachetime = 24*60*60;
                   11825:22):         &do_cache_new('courselti',$hashid,\%courselti,$cachetime);
                   11826:22):     }
                   11827:22):     return %courselti;
                   11828:22): }
                   11829:22): 
          .3(raebu 11830:22): sub courselti_itemid {
                   11831:22):     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
                   11832:22):     my ($chome,$itemid);
                   11833:22):     $chome = &homeserver($cnum,$cdom);
                   11834:22):     return if ($chome eq 'no_host');
                   11835:22):     if (ref($params) eq 'HASH') {
                   11836:22):         my $items = &freeze_escape($params);
                   11837:22):         my $rep;
                   11838:22):         if (grep { $_ eq $chome } current_machine_ids()) {
                   11839:22):             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
                   11840:22):         } else {
                   11841:22):             my $escurl = &escape($url);
                   11842:22):             my $escmethod = &escape($method);
                   11843:22):             my $items = &freeze_escape($params);
                   11844:22):             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
                   11845:22):         }
                   11846:22):         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   11847:22):                 ($rep eq 'unknown_cmd')) {
                   11848:22):             $itemid = $rep;
                   11849:22):         }
                   11850:22):     }
                   11851:22):     return $itemid;
                   11852:22): }
                   11853:22): 
                   11854:22): sub domainlti_itemid {
                   11855:22):     my ($cdom,$url,$method,$params,$context) = @_;
                   11856:22):     my ($primary_id,$itemid);
                   11857:22):     $primary_id = &domain($cdom,'primary');
                   11858:22):     return if ($primary_id eq '');
                   11859:22):     if (ref($params) eq 'HASH') {
                   11860:22):         my $items = &freeze_escape($params);
                   11861:22):         my $rep;
                   11862:22):         if (grep { $_ eq $primary_id } current_machine_ids()) {
                   11863:22):             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
                   11864:22):         } else {
                   11865:22):             my $cnum = '';
                   11866:22):             my $escurl = &escape($url);
                   11867:22):             my $escmethod = &escape($method);
                   11868:22):             my $items = &freeze_escape($params);
                   11869:22):             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
                   11870:22):         }
                   11871:22):         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   11872:22):                 ($rep eq 'unknown_cmd')) {
                   11873:22):             $itemid = $rep;
                   11874:22):         }
                   11875:22):     }
                   11876:22):     return $itemid;
                   11877:22): }
                   11878:22): 
1.1172.2.31  raeburn  11879: sub get_numsuppfiles {
                   11880:     my ($cnum,$cdom,$ignorecache)=@_;
                   11881:     my $hashid=$cnum.':'.$cdom;
                   11882:     my ($suppcount,$cached);
                   11883:     unless ($ignorecache) {
                   11884:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11885:     }
                   11886:     unless (defined($cached)) {
                   11887:         my $chome=&homeserver($cnum,$cdom);
                   11888:         unless ($chome eq 'no_host') {
                   11889:             ($suppcount,my $errors) = (0,0);
                   11890:             my $suppmap = 'supplemental.sequence';
                   11891:             ($suppcount,$errors) =
                   11892:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11893:         }
                   11894:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11895:     }
                   11896:     return $suppcount;
                   11897: }
                   11898: 
1.379     matthew  11899: #
                   11900: # EXT resource caching routines
                   11901: #
                   11902: 
1.1172.2.146.  .1(raebu 11903:22): {
                   11904:22): # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   11905:22): #
                   11906:22): # The course for which we cache
                   11907:22): my $cachedmapkey='';
                   11908:22): # The cached recursive maps for this course
                   11909:22): my %cachedmaps=();
                   11910:22): # When this was last done
                   11911:22): my $cachedmaptime='';
                   11912:22): 
1.379     matthew  11913: sub clear_EXT_cache_status {
1.383     albertel 11914:     &delenv('cache.EXT.');
1.379     matthew  11915: }
                   11916: 
                   11917: sub EXT_cache_status {
                   11918:     my ($target_domain,$target_user) = @_;
1.383     albertel 11919:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11920:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11921:         # We know already the user has no data
                   11922:         return 1;
                   11923:     } else {
                   11924:         return 0;
                   11925:     }
                   11926: }
                   11927: 
                   11928: sub EXT_cache_set {
                   11929:     my ($target_domain,$target_user) = @_;
1.383     albertel 11930:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11931:     #&appenv({$cachename => time});
1.379     matthew  11932: }
                   11933: 
1.28      www      11934: # --------------------------------------------------------- Value of a Variable
1.58      www      11935: sub EXT {
1.715     albertel 11936: 
1.1172.2.28  raeburn  11937:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11938:     unless ($varname) { return ''; }
1.218     albertel 11939:     #get real user name/domain, courseid and symb
                   11940:     my $courseid;
1.359     albertel 11941:     my $publicuser;
1.427     www      11942:     if ($symbparm) {
                   11943: 	$symbparm=&get_symb_from_alias($symbparm);
                   11944:     }
1.218     albertel 11945:     if (!($uname && $udom)) {
1.790     albertel 11946:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11947:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11948:     } else {
1.620     albertel 11949: 	$courseid=$env{'request.course.id'};
1.218     albertel 11950:     }
1.48      www      11951:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11952:     my $rest;
1.320     albertel 11953:     if (defined($therest[0])) {
1.48      www      11954:        $rest=join('.',@therest);
                   11955:     } else {
                   11956:        $rest='';
                   11957:     }
1.320     albertel 11958: 
1.57      www      11959:     my $qualifierrest=$qualifier;
                   11960:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11961:     my $spacequalifierrest=$space;
                   11962:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11963:     if ($realm eq 'user') {
1.48      www      11964: # --------------------------------------------------------------- user.resource
                   11965: 	if ($space eq 'resource') {
1.651     albertel 11966: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11967: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11968: 		 &&
1.1172.2.142  raeburn  11969: 		 ($symbparm eq &symbread()) ) {
1.744     albertel 11970: 		# if we are in the middle of processing the resource the
                   11971: 		# get the value we are planning on committing
                   11972:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11973:                     return $Apache::lonhomework::results{$qualifierrest};
                   11974:                 } else {
                   11975:                     return $Apache::lonhomework::history{$qualifierrest};
                   11976:                 }
1.335     albertel 11977: 	    } else {
1.359     albertel 11978: 		my %restored;
1.620     albertel 11979: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11980: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11981: 		} else {
                   11982: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11983: 		}
1.335     albertel 11984: 		return $restored{$qualifierrest};
                   11985: 	    }
1.48      www      11986: # ----------------------------------------------------------------- user.access
                   11987:         } elsif ($space eq 'access') {
1.218     albertel 11988: 	    # FIXME - not supporting calls for a specific user
1.48      www      11989:             return &allowed($qualifier,$rest);
                   11990: # ------------------------------------------ user.preferences, user.environment
                   11991:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11992: 	    if (($uname eq $env{'user.name'}) &&
                   11993: 		($udom eq $env{'user.domain'})) {
                   11994: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11995: 	    } else {
1.359     albertel 11996: 		my %returnhash;
                   11997: 		if (!$publicuser) {
                   11998: 		    %returnhash=&userenvironment($udom,$uname,
                   11999: 						 $qualifierrest);
                   12000: 		}
1.218     albertel 12001: 		return $returnhash{$qualifierrest};
                   12002: 	    }
1.48      www      12003: # ----------------------------------------------------------------- user.course
                   12004:         } elsif ($space eq 'course') {
1.218     albertel 12005: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12006:             return $env{join('.',('request.course',$qualifier))};
1.48      www      12007: # ------------------------------------------------------------------- user.role
                   12008:         } elsif ($space eq 'role') {
1.218     albertel 12009: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12010:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      12011:             if ($qualifier eq 'value') {
                   12012: 		return $role;
                   12013:             } elsif ($qualifier eq 'extent') {
                   12014:                 return $where;
                   12015:             }
                   12016: # ----------------------------------------------------------------- user.domain
                   12017:         } elsif ($space eq 'domain') {
1.218     albertel 12018:             return $udom;
1.48      www      12019: # ------------------------------------------------------------------- user.name
                   12020:         } elsif ($space eq 'name') {
1.218     albertel 12021:             return $uname;
1.48      www      12022: # ---------------------------------------------------- Any other user namespace
1.29      www      12023:         } else {
1.359     albertel 12024: 	    my %reply;
                   12025: 	    if (!$publicuser) {
                   12026: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   12027: 	    }
                   12028: 	    return $reply{$qualifierrest};
1.48      www      12029:         }
1.236     www      12030:     } elsif ($realm eq 'query') {
                   12031: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 12032:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   12033: 						[$spacequalifierrest]);
1.620     albertel 12034: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      12035:    } elsif ($realm eq 'request') {
1.48      www      12036: # ------------------------------------------------------------- request.browser
                   12037:         if ($space eq 'browser') {
1.1145    bisitz   12038:             return $env{'browser.'.$qualifier};
1.57      www      12039: # ------------------------------------------------------------ request.filename
                   12040:         } else {
1.620     albertel 12041:             return $env{'request.'.$spacequalifierrest};
1.29      www      12042:         }
1.28      www      12043:     } elsif ($realm eq 'course') {
1.48      www      12044: # ---------------------------------------------------------- course.description
1.620     albertel 12045:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      12046:     } elsif ($realm eq 'resource') {
1.165     www      12047: 
1.620     albertel 12048: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 12049: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   12050: 	}
1.693     albertel 12051: 
1.1172.2.30  raeburn  12052:         if ($qualifier eq '') {
                   12053: 	    if ($space eq 'title') {
                   12054: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   12055: 	        return &gettitle($symbparm);
                   12056: 	    }
1.693     albertel 12057: 	
1.1172.2.30  raeburn  12058: 	    if ($space eq 'map') {
                   12059: 	        my ($map) = &decode_symb($symbparm);
                   12060: 	        return &symbread($map);
                   12061: 	    }
                   12062:             if ($space eq 'maptitle') {
                   12063:                 my ($map) = &decode_symb($symbparm);
                   12064:                 return &gettitle($map);
                   12065:             }
                   12066: 	    if ($space eq 'filename') {
                   12067: 	        if ($symbparm) {
                   12068: 		    return &clutter((&decode_symb($symbparm))[2]);
                   12069: 	        }
                   12070: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 12071: 	    }
1.1172.2.30  raeburn  12072: 
                   12073:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   12074:                 if ($space eq 'visibleparts') {
                   12075:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   12076:                     my $item;
                   12077:                     if (ref($navmap)) {
                   12078:                         my $res = $navmap->getBySymb($symbparm);
                   12079:                         my $parts = $res->parts();
                   12080:                         if (ref($parts) eq 'ARRAY') {
                   12081:                             $item = join(',',@{$parts});
                   12082:                         }
                   12083:                         undef($navmap);
                   12084:                     }
                   12085:                     return $item;
                   12086:                 }
                   12087:             }
                   12088:         }
1.693     albertel 12089: 
                   12090: 	my ($section, $group, @groups);
1.593     albertel 12091: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  12092:         if (($courseid eq '') && ($cid)) {
                   12093:             $courseid = $cid;
                   12094:         }
                   12095: 	if (($symbparm && $courseid) && 
                   12096: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      12097: 
1.218     albertel 12098: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      12099: 
1.60      www      12100: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 12101: 	    my $symbp=$symbparm;
1.735     albertel 12102: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 12103: 
                   12104: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   12105: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   12106: 
1.620     albertel 12107: 	    if (($env{'user.name'} eq $uname) &&
                   12108: 		($env{'user.domain'} eq $udom)) {
                   12109: 		$section=$env{'request.course.sec'};
1.733     raeburn  12110:                 @groups = split(/:/,$env{'request.course.groups'});  
                   12111:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 12112: 	    } else {
1.539     albertel 12113: 		if (! defined($usection)) {
1.551     albertel 12114: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 12115: 		} else {
                   12116: 		    $section = $usection;
                   12117: 		}
1.733     raeburn  12118:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 12119: 	    }
                   12120: 
                   12121: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   12122: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   12123: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   12124: 
1.593     albertel 12125: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 12126: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 12127: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      12128: 
1.60      www      12129: # ----------------------------------------------------------- first, check user
1.624     albertel 12130: 
                   12131: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 12132: 				       ([$courselevelr,'resource'],
                   12133: 					[$courselevelm,'map'     ],
                   12134: 					[$courselevel, 'course'  ]));
1.931     albertel 12135: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      12136: 
1.594     albertel 12137: # ------------------------------------------------ second, check some of course
1.684     raeburn  12138:             my $coursereply;
1.691     raeburn  12139:             if (@groups > 0) {
                   12140:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   12141:                                        $mapparm,$spacequalifierrest);
1.927     albertel 12142:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  12143:             }
1.96      www      12144: 
1.684     raeburn  12145: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 12146: 				  $env{'course.'.$courseid.'.domain'},
                   12147: 				  'course',
                   12148: 				  ([$seclevelr,   'resource'],
                   12149: 				   [$seclevelm,   'map'     ],
                   12150: 				   [$seclevel,    'course'  ],
                   12151: 				   [$courselevelr,'resource']));
                   12152: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      12153: 
1.60      www      12154: # ------------------------------------------------------ third, check map parms
1.218     albertel 12155: 	    my %parmhash=();
                   12156: 	    my $thisparm='';
                   12157: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 12158: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 12159: 		    &GDBM_READER(),0640)) {
1.218     albertel 12160: 		$thisparm=$parmhash{$symbparm};
                   12161: 		untie(%parmhash);
                   12162: 	    }
1.927     albertel 12163: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 12164: 	}
1.594     albertel 12165: # ------------------------------------------ fourth, look in resource metadata
1.71      www      12166: 
1.218     albertel 12167: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 12168: 	my $filename;
                   12169: 	if (!$symbparm) { $symbparm=&symbread(); }
                   12170: 	if ($symbparm) {
1.409     www      12171: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 12172: 	} else {
1.620     albertel 12173: 	    $filename=$env{'request.filename'};
1.282     albertel 12174: 	}
                   12175: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 12176: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 12177: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 12178: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      12179: 
1.927     albertel 12180: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 12181: 	if ($symbparm && defined($courseid) && 
1.620     albertel 12182: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 12183: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   12184: 				     $env{'course.'.$courseid.'.domain'},
                   12185: 				     'course',
1.927     albertel 12186: 				     ([$courselevelm,'map'   ],
                   12187: 				      [$courselevel, 'course']));
                   12188: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 12189: 	}
1.145     www      12190: # ------------------------------------------------------------------ Cascade up
1.218     albertel 12191: 	unless ($space eq '0') {
1.336     albertel 12192: 	    my @parts=split(/_/,$space);
                   12193: 	    my $id=pop(@parts);
                   12194: 	    my $part=join('_',@parts);
                   12195: 	    if ($part eq '') { $part='0'; }
1.927     albertel 12196: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 12197: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  12198: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 12199: 	}
1.395     albertel 12200: 	if ($recurse) { return undef; }
                   12201: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 12202: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      12203: # ---------------------------------------------------- Any other user namespace
                   12204:     } elsif ($realm eq 'environment') {
                   12205: # ----------------------------------------------------------------- environment
1.620     albertel 12206: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   12207: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 12208: 	} else {
1.770     albertel 12209: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   12210: 		return '';
                   12211: 	    }
1.219     albertel 12212: 	    my %returnhash=&userenvironment($udom,$uname,
                   12213: 					    $spacequalifierrest);
                   12214: 	    return $returnhash{$spacequalifierrest};
                   12215: 	}
1.28      www      12216:     } elsif ($realm eq 'system') {
1.48      www      12217: # ----------------------------------------------------------------- system.time
                   12218: 	if ($space eq 'time') {
                   12219: 	    return time;
                   12220:         }
1.696     albertel 12221:     } elsif ($realm eq 'server') {
                   12222: # ----------------------------------------------------------------- system.time
                   12223: 	if ($space eq 'name') {
                   12224: 	    return $ENV{'SERVER_NAME'};
                   12225:         }
1.1172.2.146.  .1(raebu 12226:22):     } elsif ($realm eq 'client') {
                   12227:22):         if ($space eq 'remote_addr') {
                   12228:22):             return &get_requestor_ip();
                   12229:22):         }
1.28      www      12230:     }
1.48      www      12231:     return '';
1.61      www      12232: }
                   12233: 
1.927     albertel 12234: sub get_reply {
                   12235:     my ($reply_value) = @_;
1.940     raeburn  12236:     if (ref($reply_value) eq 'ARRAY') {
                   12237:         if (wantarray) {
                   12238: 	    return @$reply_value;
                   12239:         }
                   12240:         return $reply_value->[0];
                   12241:     } else {
                   12242:         return $reply_value;
1.927     albertel 12243:     }
                   12244: }
                   12245: 
1.691     raeburn  12246: sub check_group_parms {
                   12247:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   12248:     my @groupitems = ();
                   12249:     my $resultitem;
1.927     albertel 12250:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  12251:     foreach my $group (@{$groups}) {
                   12252:         foreach my $level (@levels) {
1.927     albertel 12253:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   12254:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  12255:         }
                   12256:     }
                   12257:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   12258:                             $env{'course.'.$courseid.'.domain'},
                   12259:                                      'course',@groupitems);
                   12260:     return $coursereply;
                   12261: }
                   12262: 
1.1172.2.146.  .1(raebu 12263:22): sub get_map_hierarchy {
                   12264:22):     my ($mapname,$courseid) = @_;
                   12265:22):     my @recurseup = ();
                   12266:22):     if ($mapname) {
                   12267:22):         if (($cachedmapkey eq $courseid) &&
                   12268:22):             (abs($cachedmaptime-time)<5)) {
                   12269:22):             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   12270:22):                 return @{$cachedmaps{$mapname}};
                   12271:22):             }
                   12272:22):         }
                   12273:22):         my $navmap = Apache::lonnavmaps::navmap->new();
                   12274:22):         if (ref($navmap)) {
                   12275:22):             @recurseup = $navmap->recurseup_maps($mapname);
                   12276:22):             undef($navmap);
                   12277:22):             $cachedmaps{$mapname} = \@recurseup;
                   12278:22):             $cachedmaptime=time;
                   12279:22):             $cachedmapkey=$courseid;
                   12280:22):         }
                   12281:22):     }
                   12282:22):     return @recurseup;
                   12283:22): }
                   12284:22): 
          .2(raebu 12285:22): }
          .1(raebu 12286:22): 
1.691     raeburn  12287: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  12288:     my ($courseid,@groups) = @_;
                   12289:     @groups = sort(@groups);
1.691     raeburn  12290:     return @groups;
                   12291: }
                   12292: 
1.395     albertel 12293: sub packages_tab_default {
                   12294:     my ($uri,$varname)=@_;
                   12295:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 12296: 
                   12297:     my (@extension,@specifics,$do_default);
                   12298:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 12299: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 12300: 	if ($pack_type eq 'default') {
                   12301: 	    $do_default=1;
                   12302: 	} elsif ($pack_type eq 'extension') {
                   12303: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 12304: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 12305: 	    # only look at packages defaults for packages that this id is
1.738     albertel 12306: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   12307: 	}
                   12308:     }
                   12309:     # first look for a package that matches the requested part id
                   12310:     foreach my $package (@specifics) {
                   12311: 	my (undef,$pack_type,$pack_part)=@{$package};
                   12312: 	next if ($pack_part ne $part);
                   12313: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12314: 	    return $packagetab{"$pack_type&$name&default"};
                   12315: 	}
                   12316:     }
                   12317:     # look for any possible matching non extension_ package
                   12318:     foreach my $package (@specifics) {
                   12319: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 12320: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12321: 	    return $packagetab{"$pack_type&$name&default"};
                   12322: 	}
1.585     albertel 12323: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 12324: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   12325: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 12326: 	}
                   12327:     }
1.738     albertel 12328:     # look for any posible extension_ match
                   12329:     foreach my $package (@extension) {
                   12330: 	my ($package,$pack_type)=@{$package};
                   12331: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12332: 	    return $packagetab{"$pack_type&$name&default"};
                   12333: 	}
                   12334: 	if (defined($packagetab{$package."&$name&default"})) {
                   12335: 	    return $packagetab{$package."&$name&default"};
                   12336: 	}
                   12337:     }
                   12338:     # look for a global default setting
                   12339:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   12340: 	return $packagetab{"default&$name&default"};
                   12341:     }
1.395     albertel 12342:     return undef;
                   12343: }
                   12344: 
1.334     albertel 12345: sub add_prefix_and_part {
                   12346:     my ($prefix,$part)=@_;
                   12347:     my $keyroot;
                   12348:     if (defined($prefix) && $prefix !~ /^__/) {
                   12349: 	# prefix that has a part already
                   12350: 	$keyroot=$prefix;
                   12351:     } elsif (defined($prefix)) {
                   12352: 	# prefix that is missing a part
                   12353: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   12354:     } else {
                   12355: 	# no prefix at all
                   12356: 	if (defined($part)) { $keyroot='_'.$part; }
                   12357:     }
                   12358:     return $keyroot;
                   12359: }
                   12360: 
1.71      www      12361: # ---------------------------------------------------------------- Get metadata
                   12362: 
1.599     albertel 12363: my %metaentry;
1.1070    www      12364: my %importedpartids;
1.1172.2.99  raeburn  12365: my %importedrespids;
1.71      www      12366: sub metadata {
1.176     www      12367:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      12368:     $uri=&declutter($uri);
1.288     albertel 12369:     # if it is a non metadata possible uri return quickly
1.529     albertel 12370:     if (($uri eq '') || 
                   12371: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.146.  .1(raebu 12372:22): 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  12373:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 12374: 	return undef;
                   12375:     }
1.1172.2.49  raeburn  12376:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 12377: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 12378: 	return undef;
1.288     albertel 12379:     }
1.73      www      12380:     my $filename=$uri;
                   12381:     $uri=~s/\.meta$//;
1.172     www      12382: #
                   12383: # Is the metadata already cached?
1.177     www      12384: # Look at timestamp of caching
1.172     www      12385: # Everything is cached by the main uri, libraries are never directly cached
                   12386: #
1.428     albertel 12387:     if (!defined($liburi)) {
1.599     albertel 12388: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 12389: 	if (defined($cached)) { return $result->{':'.$what}; }
                   12390:     }
                   12391:     {
1.1069    www      12392: # Imported parts would go here
1.1172.2.99  raeburn  12393:         my @origfiletagids=();
1.1069    www      12394:         my $importedparts=0;
1.1172.2.99  raeburn  12395: 
                   12396: # Imported responseids would go here
                   12397:         my $importedresponses=0;
1.172     www      12398: #
                   12399: # Is this a recursive call for a library?
                   12400: #
1.599     albertel 12401: #	if (! exists($metacache{$uri})) {
                   12402: #	    $metacache{$uri}={};
                   12403: #	}
1.924     albertel 12404: 	my $cachetime = 60*60;
1.171     www      12405:         if ($liburi) {
                   12406: 	    $liburi=&declutter($liburi);
                   12407:             $filename=$liburi;
1.401     bowersj2 12408:         } else {
1.599     albertel 12409: 	    &devalidate_cache_new('meta',$uri);
                   12410: 	    undef(%metaentry);
1.401     bowersj2 12411: 	}
1.140     www      12412:         my %metathesekeys=();
1.73      www      12413:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 12414: 	my $metastring;
1.1140    www      12415: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 12416: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 12417: 	    $metastring = 
1.929     albertel 12418: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 12419: 					  ('grade_target' => 'meta'));
                   12420: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  12421: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   12422:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 12423: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 12424: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 12425: 	    $metastring=&getfile($file);
1.489     albertel 12426: 	}
1.208     albertel 12427:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      12428:         my $token;
1.140     www      12429:         undef %metathesekeys;
1.71      www      12430:         while ($token=$parser->get_token) {
1.339     albertel 12431: 	    if ($token->[0] eq 'S') {
                   12432: 		if (defined($token->[2]->{'package'})) {
1.172     www      12433: #
                   12434: # This is a package - get package info
                   12435: #
1.339     albertel 12436: 		    my $package=$token->[2]->{'package'};
                   12437: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12438: 		    if (defined($token->[2]->{'id'})) { 
                   12439: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12440: 		    }
1.599     albertel 12441: 		    if ($metaentry{':packages'}) {
                   12442: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12443: 		    } else {
1.599     albertel 12444: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12445: 		    }
1.736     albertel 12446: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12447: 			my $part=$keyroot;
                   12448: 			$part=~s/^\_//;
1.736     albertel 12449: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12450: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12451: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12452: 			    # ignore package.tab specified default values
                   12453:                             # here &package_tab_default() will fetch those
                   12454: 			    if ($subp eq 'default') { next; }
1.736     albertel 12455: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12456: 			    my $unikey;
                   12457: 			    if ($pack =~ /_0$/) {
                   12458: 				$unikey='parameter_0_'.$name;
                   12459: 				$part=0;
                   12460: 			    } else {
                   12461: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12462: 			    }
1.339     albertel 12463: 			    if ($subp eq 'display') {
                   12464: 				$value.=' [Part: '.$part.']';
                   12465: 			    }
1.599     albertel 12466: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12467: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12468: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12469: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12470: 			    }
1.599     albertel 12471: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12472: 				$metaentry{':'.$unikey}=
                   12473: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12474: 			    }
1.339     albertel 12475: 			}
                   12476: 		    }
                   12477: 		} else {
1.172     www      12478: #
                   12479: # This is not a package - some other kind of start tag
1.339     albertel 12480: #
                   12481: 		    my $entry=$token->[1];
1.1068    www      12482: 		    my $unikey='';
1.175     www      12483: 
1.339     albertel 12484: 		    if ($entry eq 'import') {
1.175     www      12485: #
                   12486: # Importing a library here
1.339     albertel 12487: #
1.1067    www      12488:                         my $location=$parser->get_text('/import');
                   12489:                         my $dir=$filename;
                   12490:                         $dir=~s|[^/]*$||;
                   12491:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  12492: 
                   12493:                         my $importid=$token->[2]->{'id'};
1.1068    www      12494:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  12495: #
                   12496: # Check metadata for imported file to
                   12497: # see if it contained response items
                   12498: #
                   12499:                         my %currmetaentry = %metaentry;
                   12500:                         my $libresponseorder = &metadata($location,'responseorder');
                   12501:                         my $origfile;
                   12502:                         if ($libresponseorder ne '') {
                   12503:                             if ($#origfiletagids<0) {
                   12504:                                 undef(%importedrespids);
                   12505:                                 undef(%importedpartids);
                   12506:                             }
                   12507:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   12508:                             if (@{$importedrespids{$importid}} > 0) {
                   12509:                                 $importedresponses = 1;
                   12510: # We need to get the original file and the imported file to get the response order correct
                   12511: # Load and inspect original file
                   12512:                                 if ($#origfiletagids<0) {
                   12513:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12514:                                     $origfile=&getfile($origfilelocation);
                   12515:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12516:                                 }
                   12517:                             }
                   12518:                         }
                   12519: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12520: # hash populated for imported library file
                   12521:                         %metaentry = %currmetaentry;
                   12522:                         undef(%currmetaentry);
1.1068    www      12523:                         if ($importmode eq 'problem') {
1.1069    www      12524: # Import as problem/response
1.1068    www      12525:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12526:                         } elsif ($importmode eq 'part') {
                   12527: # Import as part(s)
1.1069    www      12528:                            $importedparts=1;
                   12529: # We need to get the original file and the imported file to get the part order correct
                   12530: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  12531: # Load and inspect original file if we didn't do that already
                   12532:                            if ($#origfiletagids<0) {
                   12533:                                undef(%importedrespids);
                   12534:                                undef(%importedpartids);
                   12535:                                if ($origfile eq '') {
                   12536:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12537:                                    $origfile=&getfile($origfilelocation);
                   12538:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12539:                                }
1.1070    www      12540:                            }
                   12541: 
1.1069    www      12542: # Load and inspect imported file
                   12543:                            my $impfile=&getfile($location);
                   12544:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12545:                            if ($#impfilepartids>=0) {
                   12546: # This problem had parts
1.1070    www      12547:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12548:                            } else {
                   12549: # Importing by turning a single problem into a problem part
                   12550: # It gets the import-tags ID as part-ID
                   12551:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12552:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12553:                            }
1.1068    www      12554:                         } else {
                   12555: # Normal import
                   12556:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12557:                            if (defined($token->[2]->{'id'})) {
                   12558:                               $unikey.='_'.$token->[2]->{'id'};
                   12559:                            }
1.1067    www      12560:                         }
                   12561: 
1.339     albertel 12562: 			if ($depthcount<20) {
1.736     albertel 12563: 			    my $metadata = 
                   12564: 				&metadata($uri,'keys', $location,$unikey,
                   12565: 					  $depthcount+1);
                   12566: 			    foreach my $meta (split(',',$metadata)) {
                   12567: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12568: 				$metathesekeys{$meta}=1;
1.339     albertel 12569: 			    }
1.1068    www      12570: 			
                   12571:                         }
1.1067    www      12572: 		    } else {
                   12573: #
                   12574: # Not importing, some other kind of non-package, non-library start tag
                   12575: # 
                   12576:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12577:                         if (defined($token->[2]->{'id'})) {
                   12578:                             $unikey.='_'.$token->[2]->{'id'};
                   12579:                         }
1.339     albertel 12580: 			if (defined($token->[2]->{'name'})) { 
                   12581: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12582: 			}
                   12583: 			$metathesekeys{$unikey}=1;
1.736     albertel 12584: 			foreach my $param (@{$token->[3]}) {
                   12585: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12586: 				$token->[2]->{$param};
1.339     albertel 12587: 			}
                   12588: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12589: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12590: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12591: 		 # only ws inside the tag, and not in default, so use default
                   12592: 		 # as value
1.599     albertel 12593: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12594: 			} elsif ( $internaltext =~ /\S/ ) {
                   12595: 		  # something interesting inside the tag
                   12596: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12597: 			} else {
1.908     albertel 12598: 		  # no interesting values, don't set a default
1.339     albertel 12599: 			}
1.172     www      12600: # end of not-a-package not-a-library import
1.339     albertel 12601: 		    }
1.172     www      12602: # end of not-a-package start tag
1.339     albertel 12603: 		}
1.172     www      12604: # the next is the end of "start tag"
1.339     albertel 12605: 	    }
                   12606: 	}
1.483     albertel 12607: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12608: 	$extension = lc($extension);
                   12609: 	if ($extension eq 'htm') { $extension='html'; }
                   12610: 
1.737     albertel 12611: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12612: 	    #no specific packages #how's our extension
                   12613: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12614: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12615: 					 \%metathesekeys);
                   12616: 	}
1.883     albertel 12617: 
                   12618: 	if (!exists($metaentry{':packages'})
                   12619: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12620: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12621: 		#no specific packages well let's get default then
                   12622: 		if ($key!~/^default&/) { next; }
1.488     albertel 12623: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12624: 					     \%metathesekeys);
                   12625: 	    }
                   12626: 	}
1.338     www      12627: # are there custom rights to evaluate
1.599     albertel 12628: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12629: 
1.338     www      12630:     #
                   12631:     # Importing a rights file here
1.339     albertel 12632:     #
                   12633: 	    unless ($depthcount) {
1.599     albertel 12634: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12635: 		my $dir=$filename;
                   12636: 		$dir=~s|[^/]*$||;
                   12637: 		$location=&filelocation($dir,$location);
1.736     albertel 12638: 		my $rights_metadata =
                   12639: 		    &metadata($uri,'keys',$location,'_rights',
                   12640: 			      $depthcount+1);
                   12641: 		foreach my $rights (split(',',$rights_metadata)) {
                   12642: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12643: 		    $metathesekeys{$rights}=1;
1.339     albertel 12644: 		}
                   12645: 	    }
                   12646: 	}
1.737     albertel 12647: 	# uniqifiy package listing
                   12648: 	my %seen;
                   12649: 	my @uniq_packages =
                   12650: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12651: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12652: 
1.1172.2.99  raeburn  12653:         if (($importedresponses) || ($importedparts)) {
                   12654:             if ($importedparts) {
1.1070    www      12655: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  12656:                 $metaentry{':partorder'}='';
                   12657:                 $metathesekeys{'partorder'}=1;
                   12658:             }
                   12659:             if ($importedresponses) {
                   12660: # We had imported responses and need to rebuild responseorder
                   12661:                 $metaentry{':responseorder'}='';
                   12662:                 $metathesekeys{'responseorder'}=1;
                   12663:             }
                   12664:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12665:                 my $origid = $origfiletagids[$index+1];
                   12666:                 if ($origfiletagids[$index] eq 'part') {
                   12667: # Original part, part of the problem
                   12668:                     if ($importedparts) {
                   12669:                         $metaentry{':partorder'}.=','.$origid;
                   12670:                     }
                   12671:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12672:                     if ($importedparts) {
                   12673: # We have imported parts at this position
                   12674:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12675:                     }
                   12676:                     if ($importedresponses) {
                   12677: # We have imported responses at this position
                   12678:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   12679:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   12680:                         }
                   12681:                     }
                   12682:                 } else {
                   12683: # Original response item, part of the problem
                   12684:                     if ($importedresponses) {
                   12685:                         $metaentry{':responseorder'}.=','.$origid;
                   12686:                     }
                   12687:                 }
                   12688:             }
                   12689:             if ($importedparts) {
                   12690:                 $metaentry{':partorder'}=~s/^\,//;
                   12691:             }
                   12692:             if ($importedresponses) {
                   12693:                 $metaentry{':responseorder'}=~s/^\,//;
                   12694:             }
1.1070    www      12695:         }
                   12696: 
1.737     albertel 12697: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12698: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  12699: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 12700: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      12701: # this is the end of "was not already recently cached
1.71      www      12702:     }
1.599     albertel 12703:     return $metaentry{':'.$what};
1.261     albertel 12704: }
                   12705: 
1.488     albertel 12706: sub metadata_create_package_def {
1.483     albertel 12707:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12708:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12709:     if ($subp eq 'default') { next; }
                   12710:     
1.599     albertel 12711:     if (defined($metaentry{':packages'})) {
                   12712: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12713:     } else {
1.599     albertel 12714: 	$metaentry{':packages'}=$package;
1.483     albertel 12715:     }
                   12716:     my $value=$packagetab{$key};
                   12717:     my $unikey;
                   12718:     $unikey='parameter_0_'.$name;
1.599     albertel 12719:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12720:     $$metathesekeys{$unikey}=1;
1.599     albertel 12721:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12722: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12723:     }
1.599     albertel 12724:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12725: 	$metaentry{':'.$unikey}=
                   12726: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12727:     }
                   12728: }
                   12729: 
1.261     albertel 12730: sub metadata_generate_part0 {
                   12731:     my ($metadata,$metacache,$uri) = @_;
                   12732:     my %allnames;
1.737     albertel 12733:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12734: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12735: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12736: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12737: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12738: 	    $allnames{$name}=$part;
                   12739: 	  }
                   12740: 	}
                   12741:     }
                   12742:     foreach my $name (keys(%allnames)) {
                   12743:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12744:       my $key=":parameter_0_$name";
1.261     albertel 12745:       $$metacache{"$key.part"}='0';
                   12746:       $$metacache{"$key.name"}=$name;
1.428     albertel 12747:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12748: 					   $allnames{$name}.'_'.$name.
                   12749: 					   '.type'};
1.428     albertel 12750:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12751: 			     '.display'};
1.644     www      12752:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12753:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12754:       $$metacache{"$key.display"}=$olddis;
                   12755:     }
1.71      www      12756: }
                   12757: 
1.764     albertel 12758: # ------------------------------------------------------ Devalidate title cache
                   12759: 
                   12760: sub devalidate_title_cache {
                   12761:     my ($url)=@_;
                   12762:     if (!$env{'request.course.id'}) { return; }
                   12763:     my $symb=&symbread($url);
                   12764:     if (!$symb) { return; }
                   12765:     my $key=$env{'request.course.id'}."\0".$symb;
                   12766:     &devalidate_cache_new('title',$key);
                   12767: }
                   12768: 
1.1014    droeschl 12769: # ------------------------------------------------- Get the title of a course
                   12770: 
                   12771: sub current_course_title {
                   12772:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12773: }
1.301     www      12774: # ------------------------------------------------- Get the title of a resource
                   12775: 
                   12776: sub gettitle {
                   12777:     my $urlsymb=shift;
                   12778:     my $symb=&symbread($urlsymb);
1.534     albertel 12779:     if ($symb) {
1.620     albertel 12780: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12781: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12782: 	if (defined($cached)) { 
                   12783: 	    return $result;
                   12784: 	}
1.534     albertel 12785: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12786: 	my $title='';
1.907     albertel 12787: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12788: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12789: 	} else {
                   12790: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12791: 		    &GDBM_READER(),0640)) {
                   12792: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12793: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12794: 		untie(%bighash);
                   12795: 	    }
1.534     albertel 12796: 	}
                   12797: 	$title=~s/\&colon\;/\:/gs;
                   12798: 	if ($title) {
1.1159    www      12799: # Remember both $symb and $title for dynamic metadata
                   12800:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12801:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12802: # Cache this title and then return it
1.599     albertel 12803: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12804: 	}
                   12805: 	$urlsymb=$url;
                   12806:     }
                   12807:     my $title=&metadata($urlsymb,'title');
                   12808:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12809:     return $title;
1.301     www      12810: }
1.613     albertel 12811: 
1.614     albertel 12812: sub get_slot {
                   12813:     my ($which,$cnum,$cdom)=@_;
                   12814:     if (!$cnum || !$cdom) {
1.790     albertel 12815: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12816: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12817: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12818:     }
1.703     albertel 12819:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12820:     my %slotinfo;
                   12821:     if (exists($remembered{$key})) {
                   12822: 	$slotinfo{$which} = $remembered{$key};
                   12823:     } else {
                   12824: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12825: 	&Apache::lonhomework::showhash(%slotinfo);
                   12826: 	my ($tmp)=keys(%slotinfo);
                   12827: 	if ($tmp=~/^error:/) { return (); }
                   12828: 	$remembered{$key} = $slotinfo{$which};
                   12829:     }
1.616     albertel 12830:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12831: 	return %{$slotinfo{$which}};
                   12832:     }
                   12833:     return $slotinfo{$which};
1.614     albertel 12834: }
1.1150    raeburn  12835: 
                   12836: sub get_reservable_slots {
                   12837:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12838:     my $now = time;
                   12839:     my $reservable_info;
                   12840:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12841:     if (exists($remembered{$key})) {
                   12842:         $reservable_info = $remembered{$key};
                   12843:     } else {
                   12844:         my %resv;
                   12845:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12846:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12847:         $reservable_info = \%resv;
                   12848:         $remembered{$key} = $reservable_info;
                   12849:     }
                   12850:     return $reservable_info;
                   12851: }
                   12852: 
                   12853: sub get_course_slots {
                   12854:     my ($cnum,$cdom) = @_;
                   12855:     my $hashid=$cnum.':'.$cdom;
                   12856:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12857:     if (defined($cached)) {
                   12858:         if (ref($result) eq 'HASH') {
                   12859:             return %{$result};
                   12860:         }
                   12861:     } else {
                   12862:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12863:         my ($tmp) = keys(%slots);
                   12864:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12865:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12866:             return %slots;
                   12867:         }
                   12868:     }
                   12869:     return;
                   12870: }
                   12871: 
                   12872: sub devalidate_slots_cache {
                   12873:     my ($cnum,$cdom)=@_;
                   12874:     my $hashid=$cnum.':'.$cdom;
                   12875:     &devalidate_cache_new('allslots',$hashid);
                   12876: }
                   12877: 
1.1172.2.8  raeburn  12878: sub get_coursechange {
                   12879:     my ($cdom,$cnum) = @_;
                   12880:     if ($cdom eq '' || $cnum eq '') {
                   12881:         return unless ($env{'request.course.id'});
                   12882:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12883:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12884:     }
                   12885:     my $hashid=$cdom.'_'.$cnum;
                   12886:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12887:     if ((defined($cached)) && ($change ne '')) {
                   12888:         return $change;
                   12889:     } else {
                   12890:         my %crshash;
                   12891:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12892:         if ($crshash{'internal.contentchange'} eq '') {
                   12893:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12894:             if ($change eq '') {
                   12895:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12896:                 $change = $crshash{'internal.created'};
                   12897:             }
                   12898:         } else {
                   12899:             $change = $crshash{'internal.contentchange'};
                   12900:         }
                   12901:         my $cachetime = 600;
                   12902:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12903:     }
                   12904:     return $change;
                   12905: }
                   12906: 
                   12907: sub devalidate_coursechange_cache {
                   12908:     my ($cnum,$cdom)=@_;
                   12909:     my $hashid=$cnum.':'.$cdom;
                   12910:     &devalidate_cache_new('crschange',$hashid);
                   12911: }
                   12912: 
1.31      www      12913: # ------------------------------------------------- Update symbolic store links
                   12914: 
                   12915: sub symblist {
                   12916:     my ($mapname,%newhash)=@_;
1.438     www      12917:     $mapname=&deversion(&declutter($mapname));
1.31      www      12918:     my %hash;
1.620     albertel 12919:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12920:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12921:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12922: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12923: 		next if ($url eq 'last_known'
                   12924: 			 && $env{'form.no_update_last_known'});
                   12925: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12926: 						    $newhash{$url}->[1],
                   12927: 						    $newhash{$url}->[0]);
1.191     harris41 12928:             }
1.31      www      12929:             if (untie(%hash)) {
                   12930: 		return 'ok';
                   12931:             }
                   12932:         }
                   12933:     }
                   12934:     return 'error';
1.212     www      12935: }
                   12936: 
                   12937: # --------------------------------------------------------------- Verify a symb
                   12938: 
                   12939: sub symbverify {
1.1172.2.11  raeburn  12940:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12941:     my $thisfn=$thisurl;
1.439     www      12942:     $thisfn=&declutter($thisfn);
1.215     www      12943: # direct jump to resource in page or to a sequence - will construct own symbs
                   12944:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12945: # check URL part
1.409     www      12946:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12947: 
1.431     www      12948:     unless ($url eq $thisfn) { return 0; }
1.213     www      12949: 
1.216     www      12950:     $symb=&symbclean($symb);
1.510     www      12951:     $thisurl=&deversion($thisurl);
1.439     www      12952:     $thisfn=&deversion($thisfn);
1.213     www      12953: 
                   12954:     my %bighash;
                   12955:     my $okay=0;
1.431     www      12956: 
1.620     albertel 12957:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12958:                             &GDBM_READER(),0640)) {
1.1032    raeburn  12959:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12960:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  12961:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12962:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12963:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12964:             }
                   12965:         }
                   12966:         my $ids;
1.1172.2.122  raeburn  12967:         if ($map =~ m{^uploaded/.+\.page$}) {
                   12968:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13  raeburn  12969:         } else {
                   12970:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12971:         }
1.1102    raeburn  12972:         unless ($ids) {
1.1172.2.13  raeburn  12973:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  12974:             $ids=$bighash{$idkey};
1.216     www      12975:         }
                   12976:         if ($ids) {
                   12977: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  12978:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   12979:                 $symb =~ s/\?.+$//;
                   12980:             }
1.800     albertel 12981: 	    foreach my $id (split(/\,/,$ids)) {
                   12982: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12983:                if (
                   12984:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  12985:    eq $symb) {
1.1172.2.11  raeburn  12986:                    if (ref($encstate)) {
                   12987:                        $$encstate = $bighash{'encrypted_'.$id};
                   12988:                    }
1.1172.2.13  raeburn  12989:                    if (($env{'request.role.adv'}) ||
                   12990:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  12991:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  12992:                        $okay=1;
                   12993:                        last;
                   12994:                    }
                   12995:                }
                   12996:            }
1.216     www      12997:         }
1.213     www      12998: 	untie(%bighash);
                   12999:     }
                   13000:     return $okay;
1.31      www      13001: }
                   13002: 
1.210     www      13003: # --------------------------------------------------------------- Clean-up symb
                   13004: 
                   13005: sub symbclean {
                   13006:     my $symb=shift;
1.568     albertel 13007:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      13008: # remove version from map
                   13009:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      13010: 
1.210     www      13011: # remove version from URL
                   13012:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      13013: 
1.507     www      13014: # remove wrapper
                   13015: 
1.510     www      13016:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 13017:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      13018:     return $symb;
1.409     www      13019: }
                   13020: 
                   13021: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 13022: 
                   13023: sub encode_symb {
                   13024:     my ($map,$resid,$url)=@_;
                   13025:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   13026: }
1.409     www      13027: 
                   13028: sub decode_symb {
1.568     albertel 13029:     my $symb=shift;
                   13030:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   13031:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      13032:     return (&fixversion($map),$resid,&fixversion($url));
                   13033: }
                   13034: 
                   13035: sub fixversion {
                   13036:     my $fn=shift;
1.609     banghart 13037:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      13038:     my %bighash;
                   13039:     my $uri=&clutter($fn);
1.620     albertel 13040:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      13041: # is this cached?
1.599     albertel 13042:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      13043:     if (defined($cached)) { return $result; }
                   13044: # unfortunately not cached, or expired
1.620     albertel 13045:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      13046: 	    &GDBM_READER(),0640)) {
                   13047:  	if ($bighash{'version_'.$uri}) {
                   13048:  	    my $version=$bighash{'version_'.$uri};
1.444     www      13049:  	    unless (($version eq 'mostrecent') || 
                   13050: 		    ($version==&getversion($uri))) {
1.440     www      13051:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   13052:  	    }
                   13053:  	}
                   13054:  	untie %bighash;
1.413     www      13055:     }
1.599     albertel 13056:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      13057: }
                   13058: 
                   13059: sub deversion {
                   13060:     my $url=shift;
                   13061:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   13062:     return $url;
1.210     www      13063: }
                   13064: 
1.31      www      13065: # ------------------------------------------------------ Return symb list entry
                   13066: 
                   13067: sub symbread {
1.1172.2.126  raeburn  13068:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128  raeburn  13069:         $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54  raeburn  13070:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128  raeburn  13071:     if (defined($env{$cache_str})) {
1.1172.2.126  raeburn  13072:         unless (ref($possibles) eq 'HASH') {
                   13073:             if ($ignorecachednull) {
                   13074:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   13075:             } else {
                   13076:                 return $env{$cache_str};
                   13077:             }
1.1172.2.66  raeburn  13078:         }
                   13079:     }
1.242     www      13080: # no filename provided? try from environment
1.1172.2.54  raeburn  13081:     unless ($thisfn) {
1.620     albertel 13082:         if ($env{'request.symb'}) {
1.1172.2.128  raeburn  13083:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13  raeburn  13084:         }
                   13085:         $thisfn=$env{'request.filename'};
1.44      www      13086:     }
1.569     albertel 13087:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      13088: # is that filename actually a symb? Verify, clean, and return
                   13089:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 13090: 	if (&symbverify($thisfn,$1)) {
1.1172.2.128  raeburn  13091: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 13092: 	}
1.242     www      13093:     }
1.44      www      13094:     $thisfn=declutter($thisfn);
1.31      www      13095:     my %hash;
1.37      www      13096:     my %bighash;
                   13097:     my $syval='';
1.620     albertel 13098:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  13099:         my $targetfn = $thisfn;
1.609     banghart 13100:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  13101:             $targetfn = 'adm/wrapper/'.$thisfn;
                   13102:         }
1.687     albertel 13103: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   13104: 	    $targetfn=$1;
                   13105: 	}
1.1172.2.128  raeburn  13106:         unless ($ignoresymbdb) {
1.1172.2.126  raeburn  13107:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   13108:                           &GDBM_READER(),0640)) {
                   13109: 	        $syval=$hash{$targetfn};
                   13110:                 untie(%hash);
                   13111:             }
1.1172.2.128  raeburn  13112:             if ($syval && $checkforblock) {
                   13113:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126  raeburn  13114:                 if (@blockers) {
                   13115:                     $syval='';
                   13116:                 }
                   13117:             }
1.37      www      13118:         }
                   13119: # ---------------------------------------------------------- There was an entry
                   13120:         if ($syval) {
1.601     albertel 13121: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 13122: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  13123: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13124: 		    #return $env{$cache_str}='';
1.601     albertel 13125: 		#}    
                   13126: 		#$syval.=$1;
                   13127: 	    #}
1.37      www      13128:         } else {
                   13129: # ------------------------------------------------------- Was not in symb table
1.620     albertel 13130:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13131:                             &GDBM_READER(),0640)) {
1.37      www      13132: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      13133:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      13134:               unless ($ids) { 
                   13135:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      13136:               }
                   13137:               unless ($ids) {
                   13138: # alias?
                   13139: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      13140:               }
1.37      www      13141:               if ($ids) {
                   13142: # ------------------------------------------------------------------- Has ID(s)
                   13143:                  my @possibilities=split(/\,/,$ids);
1.39      www      13144:                  if ($#possibilities==0) {
                   13145: # ----------------------------------------------- There is only one possibility
1.37      www      13146: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 13147: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13148: 						    $resid,$thisfn);
1.1172.2.66  raeburn  13149:                      if (ref($possibles) eq 'HASH') {
1.1172.2.126  raeburn  13150:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   13151:                              $possibles->{$syval} = 1;
                   13152:                          }
1.1172.2.66  raeburn  13153:                      }
                   13154:                      if ($checkforblock) {
1.1172.2.126  raeburn  13155:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127  raeburn  13156:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126  raeburn  13157:                              if (@blockers) {
                   13158:                                  $syval = '';
                   13159:                                  untie(%bighash);
                   13160:                                  return $env{$cache_str}='';
                   13161:                              }
1.1172.2.66  raeburn  13162:                          }
                   13163:                      }
                   13164:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      13165: # ------------------------------------------ There is more than one possibility
                   13166:                      my $realpossible=0;
1.800     albertel 13167:                      foreach my $id (@possibilities) {
                   13168: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  13169:                          my $canaccess;
                   13170:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   13171:                              $canaccess = 1;
                   13172:                          } else {
                   13173:                              $canaccess = &allowed('bre',$file);
                   13174:                          }
                   13175:                          if ($canaccess) {
                   13176:          		     my ($mapid,$resid)=split(/\./,$id);
                   13177:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   13178:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13179:                                                              $resid,$thisfn);
1.1172.2.126  raeburn  13180:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127  raeburn  13181:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66  raeburn  13182:                                  if ($checkforblock) {
1.1172.2.127  raeburn  13183:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126  raeburn  13184:                                      if (@blockers > 0) {
                   13185:                                          $syval = '';
                   13186:                                      } else {
1.1172.2.66  raeburn  13187:                                          $syval = $poss_syval;
                   13188:                                          $realpossible++;
                   13189:                                      }
                   13190:                                  } else {
                   13191:                                      $syval = $poss_syval;
                   13192:                                      $realpossible++;
                   13193:                                  }
1.1172.2.126  raeburn  13194:                                  if ($syval) {
                   13195:                                      if (ref($possibles) eq 'HASH') {
                   13196:                                          $possibles->{$syval} = 1;
                   13197:                                      }
                   13198:                                  }
1.1172.2.66  raeburn  13199:                              }
1.39      www      13200: 			 }
1.191     harris41 13201:                      }
1.39      www      13202: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      13203:                  } else {
                   13204:                      $syval='';
1.37      www      13205:                  }
                   13206: 	      }
1.1172.2.66  raeburn  13207:               untie(%bighash);
1.481     raeburn  13208:            }
1.31      www      13209:         }
1.62      www      13210:         if ($syval) {
1.1172.2.128  raeburn  13211: 	    return $env{$cache_str}=$syval;
1.62      www      13212:         }
1.31      www      13213:     }
1.949     raeburn  13214:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13215:     return $env{$cache_str}='';
1.31      www      13216: }
                   13217: 
                   13218: # ---------------------------------------------------------- Return random seed
                   13219: 
1.32      www      13220: sub numval {
                   13221:     my $txt=shift;
                   13222:     $txt=~tr/A-J/0-9/;
                   13223:     $txt=~tr/a-j/0-9/;
                   13224:     $txt=~tr/K-T/0-9/;
                   13225:     $txt=~tr/k-t/0-9/;
                   13226:     $txt=~tr/U-Z/0-5/;
                   13227:     $txt=~tr/u-z/0-5/;
                   13228:     $txt=~s/\D//g;
1.564     albertel 13229:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      13230:     return int($txt);
1.368     albertel 13231: }
                   13232: 
1.484     albertel 13233: sub numval2 {
                   13234:     my $txt=shift;
                   13235:     $txt=~tr/A-J/0-9/;
                   13236:     $txt=~tr/a-j/0-9/;
                   13237:     $txt=~tr/K-T/0-9/;
                   13238:     $txt=~tr/k-t/0-9/;
                   13239:     $txt=~tr/U-Z/0-5/;
                   13240:     $txt=~tr/u-z/0-5/;
                   13241:     $txt=~s/\D//g;
                   13242:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13243:     my $total;
                   13244:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 13245:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 13246:     return int($total);
                   13247: }
                   13248: 
1.575     albertel 13249: sub numval3 {
                   13250:     use integer;
                   13251:     my $txt=shift;
                   13252:     $txt=~tr/A-J/0-9/;
                   13253:     $txt=~tr/a-j/0-9/;
                   13254:     $txt=~tr/K-T/0-9/;
                   13255:     $txt=~tr/k-t/0-9/;
                   13256:     $txt=~tr/U-Z/0-5/;
                   13257:     $txt=~tr/u-z/0-5/;
                   13258:     $txt=~s/\D//g;
                   13259:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13260:     my $total;
                   13261:     foreach my $val (@txts) { $total+=$val; }
                   13262:     if ($_64bit) { $total=(($total<<32)>>32); }
                   13263:     return $total;
                   13264: }
                   13265: 
1.675     albertel 13266: sub digest {
                   13267:     my ($data)=@_;
                   13268:     my $digest=&Digest::MD5::md5($data);
                   13269:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   13270:     my ($e,$f);
                   13271:     {
                   13272:         use integer;
                   13273:         $e=($a+$b);
                   13274:         $f=($c+$d);
                   13275:         if ($_64bit) {
                   13276:             $e=(($e<<32)>>32);
                   13277:             $f=(($f<<32)>>32);
                   13278:         }
                   13279:     }
                   13280:     if (wantarray) {
                   13281: 	return ($e,$f);
                   13282:     } else {
                   13283: 	my $g;
                   13284: 	{
                   13285: 	    use integer;
                   13286: 	    $g=($e+$f);
                   13287: 	    if ($_64bit) {
                   13288: 		$g=(($g<<32)>>32);
                   13289: 	    }
                   13290: 	}
                   13291: 	return $g;
                   13292:     }
                   13293: }
                   13294: 
1.368     albertel 13295: sub latest_rnd_algorithm_id {
1.675     albertel 13296:     return '64bit5';
1.366     albertel 13297: }
1.32      www      13298: 
1.503     albertel 13299: sub get_rand_alg {
                   13300:     my ($courseid)=@_;
1.790     albertel 13301:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 13302:     if ($courseid) {
1.620     albertel 13303: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 13304:     }
                   13305:     return &latest_rnd_algorithm_id();
                   13306: }
                   13307: 
1.562     albertel 13308: sub validCODE {
                   13309:     my ($CODE)=@_;
                   13310:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   13311:     return 0;
                   13312: }
                   13313: 
1.491     albertel 13314: sub getCODE {
1.620     albertel 13315:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 13316:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   13317: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   13318: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 13319: 	return $Apache::lonhomework::history{'resource.CODE'};
                   13320:     }
                   13321:     return undef;
                   13322: }
1.1133    foxr     13323: #
                   13324: #  Determines the random seed for a specific context:
                   13325: #
                   13326: # parameters:
                   13327: #   symb      - in course context the symb for the seed.
                   13328: #   course_id - The course id of the form domain_coursenum.
                   13329: #   domain    - Domain for the user.
                   13330: #   course    - Course for the user.
                   13331: #   cenv      - environment of the course.
                   13332: #
                   13333: # NOTE:
                   13334: #   All parameters are picked out of the environment if missing
                   13335: #   or not defined.
                   13336: #   If a symb cannot be determined the current time is used instead.
                   13337: #
                   13338: #  For a given well defined symb, courside, domain, username,
                   13339: #  and course environment, the seed is reproducible.
                   13340: #
1.31      www      13341: sub rndseed {
1.1133    foxr     13342:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 13343:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 13344:     if (!defined($symb)) {
1.366     albertel 13345: 	unless ($symb=$wsymb) { return time; }
                   13346:     }
1.1146    foxr     13347:     if (!defined $courseid) { 
                   13348: 	$courseid=$wcourseid; 
                   13349:     }
                   13350:     if (!defined $domain) { $domain=$wdomain; }
                   13351:     if (!defined $username) { $username=$wusername }
1.1133    foxr     13352: 
                   13353:     my $which;
                   13354:     if (defined($cenv->{'rndseed'})) {
                   13355: 	$which = $cenv->{'rndseed'};
                   13356:     } else {
                   13357: 	$which =&get_rand_alg($courseid);
                   13358:     }
1.491     albertel 13359:     if (defined(&getCODE())) {
1.675     albertel 13360: 	if ($which eq '64bit5') {
                   13361: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   13362: 	} elsif ($which eq '64bit4') {
1.575     albertel 13363: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   13364: 	} else {
                   13365: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   13366: 	}
1.675     albertel 13367:     } elsif ($which eq '64bit5') {
                   13368: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 13369:     } elsif ($which eq '64bit4') {
                   13370: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 13371:     } elsif ($which eq '64bit3') {
                   13372: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 13373:     } elsif ($which eq '64bit2') {
                   13374: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 13375:     } elsif ($which eq '64bit') {
                   13376: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   13377:     }
                   13378:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   13379: }
                   13380: 
                   13381: sub rndseed_32bit {
                   13382:     my ($symb,$courseid,$domain,$username)=@_;
                   13383:     {
                   13384: 	use integer;
                   13385: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   13386: 	my $symbseed=numval($symb) << 22;
                   13387: 	my $namechck=unpack("%32C*",$username) << 17;
                   13388: 	my $nameseed=numval($username) << 12;
                   13389: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   13390: 	my $courseseed=unpack("%32C*",$courseid);
                   13391: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 13392: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13393: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13394: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 13395: 	return $num;
                   13396:     }
                   13397: }
                   13398: 
                   13399: sub rndseed_64bit {
                   13400:     my ($symb,$courseid,$domain,$username)=@_;
                   13401:     {
                   13402: 	use integer;
                   13403: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   13404: 	my $symbseed=numval($symb) << 10;
                   13405: 	my $namechck=unpack("%32S*",$username);
                   13406: 	
                   13407: 	my $nameseed=numval($username) << 21;
                   13408: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   13409: 	my $courseseed=unpack("%32S*",$courseid);
                   13410: 	
                   13411: 	my $num1=$symbchck+$symbseed+$namechck;
                   13412: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13413: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13414: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13415: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 13416: 	return "$num1,$num2";
1.155     albertel 13417:     }
1.366     albertel 13418: }
                   13419: 
1.443     albertel 13420: sub rndseed_64bit2 {
                   13421:     my ($symb,$courseid,$domain,$username)=@_;
                   13422:     {
                   13423: 	use integer;
                   13424: 	# strings need to be an even # of cahracters long, it it is odd the
                   13425:         # last characters gets thrown away
                   13426: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13427: 	my $symbseed=numval($symb) << 10;
                   13428: 	my $namechck=unpack("%32S*",$username.' ');
                   13429: 	
                   13430: 	my $nameseed=numval($username) << 21;
1.501     albertel 13431: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13432: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13433: 	
                   13434: 	my $num1=$symbchck+$symbseed+$namechck;
                   13435: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13436: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13437: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13438: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13439: 	return "$num1,$num2";
                   13440:     }
                   13441: }
                   13442: 
                   13443: sub rndseed_64bit3 {
                   13444:     my ($symb,$courseid,$domain,$username)=@_;
                   13445:     {
                   13446: 	use integer;
                   13447: 	# strings need to be an even # of cahracters long, it it is odd the
                   13448:         # last characters gets thrown away
                   13449: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13450: 	my $symbseed=numval2($symb) << 10;
                   13451: 	my $namechck=unpack("%32S*",$username.' ');
                   13452: 	
                   13453: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13454: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13455: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13456: 	
                   13457: 	my $num1=$symbchck+$symbseed+$namechck;
                   13458: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13459: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13460: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13461: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13462: 	
1.503     albertel 13463: 	return "$num1:$num2";
1.443     albertel 13464:     }
                   13465: }
                   13466: 
1.575     albertel 13467: sub rndseed_64bit4 {
                   13468:     my ($symb,$courseid,$domain,$username)=@_;
                   13469:     {
                   13470: 	use integer;
                   13471: 	# strings need to be an even # of cahracters long, it it is odd the
                   13472:         # last characters gets thrown away
                   13473: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13474: 	my $symbseed=numval3($symb) << 10;
                   13475: 	my $namechck=unpack("%32S*",$username.' ');
                   13476: 	
                   13477: 	my $nameseed=numval3($username) << 21;
                   13478: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13479: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13480: 	
                   13481: 	my $num1=$symbchck+$symbseed+$namechck;
                   13482: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13483: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13484: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13485: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13486: 	
1.575     albertel 13487: 	return "$num1:$num2";
                   13488:     }
                   13489: }
                   13490: 
1.675     albertel 13491: sub rndseed_64bit5 {
                   13492:     my ($symb,$courseid,$domain,$username)=@_;
                   13493:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13494:     return "$num1:$num2";
                   13495: }
                   13496: 
1.366     albertel 13497: sub rndseed_CODE_64bit {
                   13498:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13499:     {
1.366     albertel 13500: 	use integer;
1.443     albertel 13501: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13502: 	my $symbseed=numval2($symb);
1.491     albertel 13503: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13504: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13505: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13506: 	my $num1=$symbseed+$CODEchck;
                   13507: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13508: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13509: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13510: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13511: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13512: 	return "$num1:$num2";
1.366     albertel 13513:     }
                   13514: }
                   13515: 
1.575     albertel 13516: sub rndseed_CODE_64bit4 {
                   13517:     my ($symb,$courseid,$domain,$username)=@_;
                   13518:     {
                   13519: 	use integer;
                   13520: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13521: 	my $symbseed=numval3($symb);
                   13522: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13523: 	my $CODEseed=numval3(&getCODE());
                   13524: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13525: 	my $num1=$symbseed+$CODEchck;
                   13526: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13527: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13528: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13529: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13530: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13531: 	return "$num1:$num2";
                   13532:     }
                   13533: }
                   13534: 
1.675     albertel 13535: sub rndseed_CODE_64bit5 {
                   13536:     my ($symb,$courseid,$domain,$username)=@_;
                   13537:     my $code = &getCODE();
                   13538:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13539:     return "$num1:$num2";
                   13540: }
                   13541: 
1.366     albertel 13542: sub setup_random_from_rndseed {
                   13543:     my ($rndseed)=@_;
1.503     albertel 13544:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  13545: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13546:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13547:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13548:         } else {
                   13549:             &Math::Random::random_set_seed($num1,$num2);
                   13550:         }
1.366     albertel 13551:     } else {
                   13552: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13553:     }
1.36      albertel 13554: }
                   13555: 
1.474     albertel 13556: sub latest_receipt_algorithm_id {
1.835     albertel 13557:     return 'receipt3';
1.474     albertel 13558: }
                   13559: 
1.480     www      13560: sub recunique {
                   13561:     my $fucourseid=shift;
                   13562:     my $unique;
1.835     albertel 13563:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13564: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13565: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13566:     } else {
                   13567: 	$unique=$perlvar{'lonReceipt'};
                   13568:     }
                   13569:     return unpack("%32C*",$unique);
                   13570: }
                   13571: 
                   13572: sub recprefix {
                   13573:     my $fucourseid=shift;
                   13574:     my $prefix;
1.835     albertel 13575:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13576: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13577: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13578:     } else {
                   13579: 	$prefix=$perlvar{'lonHostID'};
                   13580:     }
                   13581:     return unpack("%32C*",$prefix);
                   13582: }
                   13583: 
1.76      www      13584: sub ireceipt {
1.474     albertel 13585:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13586: 
                   13587:     my $return =&recprefix($fucourseid).'-';
                   13588: 
                   13589:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13590: 	$env{'request.state'} eq 'construct') {
                   13591: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13592: 	return $return;
                   13593:     }
                   13594: 
1.76      www      13595:     my $cuname=unpack("%32C*",$funame);
                   13596:     my $cudom=unpack("%32C*",$fudom);
                   13597:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13598:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13599:     my $cunique=&recunique($fucourseid);
1.474     albertel 13600:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13601:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13602: 
1.790     albertel 13603: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13604: 			       
                   13605: 	$return.= ($cunique%$cuname+
                   13606: 		   $cunique%$cudom+
                   13607: 		   $cusymb%$cuname+
                   13608: 		   $cusymb%$cudom+
                   13609: 		   $cucourseid%$cuname+
                   13610: 		   $cucourseid%$cudom+
                   13611: 		   $cpart%$cuname+
                   13612: 		   $cpart%$cudom);
                   13613:     } else {
                   13614: 	$return.= ($cunique%$cuname+
                   13615: 		   $cunique%$cudom+
                   13616: 		   $cusymb%$cuname+
                   13617: 		   $cusymb%$cudom+
                   13618: 		   $cucourseid%$cuname+
                   13619: 		   $cucourseid%$cudom);
                   13620:     }
                   13621:     return $return;
1.76      www      13622: }
                   13623: 
                   13624: sub receipt {
1.474     albertel 13625:     my ($part)=@_;
1.790     albertel 13626:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13627:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13628: }
1.260     ng       13629: 
1.790     albertel 13630: sub whichuser {
                   13631:     my ($passedsymb)=@_;
                   13632:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13633:     if (defined($env{'form.grade_symb'})) {
                   13634: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13635: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13636: 	if (!$allowed &&
                   13637: 	    exists($env{'request.course.sec'}) &&
                   13638: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13639: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13640: 			      '/'.$env{'request.course.sec'});
                   13641: 	}
                   13642: 	if ($allowed) {
                   13643: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13644: 	    $courseid=$tmp_courseid;
                   13645: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13646: 	    ($name)=&get_env_multiple('form.grade_username');
                   13647: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13648: 	}
                   13649:     }
                   13650:     if (!$passedsymb) {
                   13651: 	$symb=&symbread();
                   13652:     } else {
                   13653: 	$symb=$passedsymb;
                   13654:     }
                   13655:     $courseid=$env{'request.course.id'};
                   13656:     $domain=$env{'user.domain'};
                   13657:     $name=$env{'user.name'};
                   13658:     if ($name eq 'public' && $domain eq 'public') {
                   13659: 	if (!defined($env{'form.username'})) {
                   13660: 	    $env{'form.username'}.=time.rand(10000000);
                   13661: 	}
                   13662: 	$name.=$env{'form.username'};
                   13663:     }
                   13664:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13665: 
                   13666: }
                   13667: 
1.36      albertel 13668: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13669: # returns either the contents of the file or 
                   13670: # -1 if the file doesn't exist
1.481     raeburn  13671: #
                   13672: # if the target is a file that was uploaded via DOCS, 
                   13673: # a check will be made to see if a current copy exists on the local server,
                   13674: # if it does this will be served, otherwise a copy will be retrieved from
                   13675: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13676: # the local server.   
1.472     albertel 13677: 
1.36      albertel 13678: sub getfile {
1.538     albertel 13679:     my ($file) = @_;
1.609     banghart 13680:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13681:     &repcopy($file);
                   13682:     return &readfile($file);
                   13683: }
                   13684: 
                   13685: sub repcopy_userfile {
                   13686:     my ($file)=@_;
1.1142    raeburn  13687:     my $londocroot = $perlvar{'lonDocRoot'};
                   13688:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13689:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13690:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13691: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13692:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13693:     if (-e "$file") {
1.828     www      13694: # we already have a local copy, check it out
1.538     albertel 13695: 	my @fileinfo = stat($file);
1.828     www      13696: 	my $rtncode;
                   13697: 	my $info;
1.538     albertel 13698: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13699: 	if ($lwpresp ne 'ok') {
1.828     www      13700: # there is no such file anymore, even though we had a local copy
1.482     albertel 13701: 	    if ($rtncode eq '404') {
1.538     albertel 13702: 		unlink($file);
1.482     albertel 13703: 	    }
                   13704: 	    return -1;
                   13705: 	}
                   13706: 	if ($info < $fileinfo[9]) {
1.828     www      13707: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13708: 	    return 'ok';
1.828     www      13709: 	} else {
                   13710: # the file is outdated, get rid of it
                   13711: 	    unlink($file);
1.482     albertel 13712: 	}
1.828     www      13713:     }
                   13714: # one way or the other, at this point, we don't have the file
                   13715: # construct the correct path for the file
                   13716:     my @parts = ($cdom,$cnum); 
                   13717:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13718: 	push @parts, split(/\//,$1);
                   13719:     }
                   13720:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13721:     foreach my $part (@parts) {
                   13722: 	$path .= '/'.$part;
                   13723: 	if (!-e $path) {
                   13724: 	    mkdir($path,0770);
1.482     albertel 13725: 	}
                   13726:     }
1.828     www      13727: # now the path exists for sure
                   13728: # get a user agent
                   13729:     my $ua=new LWP::UserAgent;
                   13730:     my $transferfile=$file.'.in.transfer';
                   13731: # FIXME: this should flock
                   13732:     if (-e $transferfile) { return 'ok'; }
                   13733:     my $request;
                   13734:     $uri=~s/^\///;
1.980     raeburn  13735:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13736:     my $hostname = &hostname($homeserver);
1.980     raeburn  13737:     my $protocol = $protocol{$homeserver};
                   13738:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13739:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      13740:     my $response=$ua->request($request,$transferfile);
                   13741: # did it work?
                   13742:     if ($response->is_error()) {
                   13743: 	unlink($transferfile);
                   13744: 	&logthis("Userfile repcopy failed for $uri");
                   13745: 	return -1;
                   13746:     }
                   13747: # worked, rename the transfer file
                   13748:     rename($transferfile,$file);
1.607     raeburn  13749:     return 'ok';
1.481     raeburn  13750: }
                   13751: 
1.517     albertel 13752: sub tokenwrapper {
                   13753:     my $uri=shift;
1.980     raeburn  13754:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13755:     $uri=~s|^/||;
1.620     albertel 13756:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13757:     my $token=$1;
1.552     albertel 13758:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13759:     if ($udom && $uname && $file) {
                   13760: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13761:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13762:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.120  raeburn  13763:         my $hostname = &hostname($homeserver);
1.980     raeburn  13764:         my $protocol = $protocol{$homeserver};
                   13765:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13766:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13767:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13768:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13769:     } else {
                   13770:         return '/adm/notfound.html';
                   13771:     }
                   13772: }
                   13773: 
1.828     www      13774: # call with reqtype HEAD: get last modification time
                   13775: # call with reqtype GET: get the file contents
                   13776: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13777: #
1.481     raeburn  13778: sub getuploaded {
                   13779:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13780:     $uri=~s/^\///;
1.980     raeburn  13781:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13782:     my $hostname = &hostname($homeserver);
1.980     raeburn  13783:     my $protocol = $protocol{$homeserver};
                   13784:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13785:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13786:     my $ua=new LWP::UserAgent;
                   13787:     my $request=new HTTP::Request($reqtype,$uri);
                   13788:     my $response=$ua->request($request);
                   13789:     $$rtncode = $response->code;
1.482     albertel 13790:     if (! $response->is_success()) {
                   13791: 	return 'failed';
                   13792:     }      
                   13793:     if ($reqtype eq 'HEAD') {
1.486     www      13794: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13795:     } elsif ($reqtype eq 'GET') {
                   13796: 	$$info = $response->content;
1.472     albertel 13797:     }
1.482     albertel 13798:     return 'ok';
1.36      albertel 13799: }
                   13800: 
1.481     raeburn  13801: sub readfile {
                   13802:     my $file = shift;
                   13803:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13804:     my $fh;
1.1172.2.96  raeburn  13805:     open($fh,"<",$file);
1.481     raeburn  13806:     my $a='';
1.800     albertel 13807:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13808:     return $a;
                   13809: }
                   13810: 
1.36      albertel 13811: sub filelocation {
1.590     banghart 13812:     my ($dir,$file) = @_;
                   13813:     my $location;
                   13814:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13815: 
                   13816:     if ($file =~ m-^/adm/-) {
                   13817: 	$file=~s-^/adm/wrapper/-/-;
                   13818: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13819:     }
1.882     albertel 13820: 
1.1139    www      13821:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13822:         $location = $file;
1.609     banghart 13823:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13824:         my ($udom,$uname,$filename)=
1.811     albertel 13825:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13826:         my $home=&homeserver($uname,$udom);
                   13827:         my $is_me=0;
                   13828:         my @ids=&current_machine_ids();
                   13829:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13830:         if ($is_me) {
1.1117    foxr     13831:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13832:         } else {
                   13833:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13834:   	      $udom.'/'.$uname.'/'.$filename;
                   13835:         }
1.882     albertel 13836:     } elsif ($file =~ m-^/adm/-) {
                   13837: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13838:     } else {
                   13839:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13840:         $file=~s:^/(res|priv)/:/:;
                   13841:         my $space=$1;
1.590     banghart 13842:         if ( !( $file =~ m:^/:) ) {
                   13843:             $location = $dir. '/'.$file;
                   13844:         } else {
1.1142    raeburn  13845:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13846:         }
1.59      albertel 13847:     }
1.590     banghart 13848:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13849:     while ($location=~m{/\.\./}) {
                   13850: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13851: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13852: 	} else {
                   13853: 	    $location=~ s{/\.\./}{/}g;
                   13854: 	}
                   13855:     } #remove dir/..
1.590     banghart 13856:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13857:     return $location;
1.46      www      13858: }
1.36      albertel 13859: 
1.46      www      13860: sub hreflocation {
                   13861:     my ($dir,$file)=@_;
1.980     raeburn  13862:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13863: 	$file=filelocation($dir,$file);
1.700     albertel 13864:     } elsif ($file=~m-^/adm/-) {
                   13865: 	$file=~s-^/adm/wrapper/-/-;
                   13866: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13867:     }
                   13868:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13869: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13870:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13871: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13872: 	        {/uploaded/$1/$2/}x;
1.46      www      13873:     }
1.913     albertel 13874:     if ($file=~ m{^/userfiles/}) {
                   13875: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13876:     }
1.462     albertel 13877:     return $file;
1.465     albertel 13878: }
                   13879: 
1.1139    www      13880: 
                   13881: 
                   13882: 
                   13883: 
1.465     albertel 13884: sub current_machine_domains {
1.853     albertel 13885:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13886: }
                   13887: 
                   13888: sub machine_domains {
                   13889:     my ($hostname) = @_;
1.465     albertel 13890:     my @domains;
1.838     albertel 13891:     my %hostname = &all_hostnames();
1.465     albertel 13892:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13893: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13894: 	if ($hostname eq $name) {
1.844     albertel 13895: 	    push(@domains,&host_domain($id));
1.465     albertel 13896: 	}
                   13897:     }
                   13898:     return @domains;
                   13899: }
                   13900: 
                   13901: sub current_machine_ids {
1.853     albertel 13902:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13903: }
                   13904: 
                   13905: sub machine_ids {
                   13906:     my ($hostname) = @_;
                   13907:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13908:     my @ids;
1.888     albertel 13909:     my %name_to_host = &all_names();
1.889     albertel 13910:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13911: 	return @{ $name_to_host{$hostname} };
                   13912:     }
                   13913:     return;
1.31      www      13914: }
                   13915: 
1.824     raeburn  13916: sub additional_machine_domains {
                   13917:     my @domains;
1.1172.2.142  raeburn  13918:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
                   13919:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
                   13920:             while( my $line = <$fh>) {
                   13921:                 chomp($line);
                   13922:                 $line =~ s/\s//g;
                   13923:                 push(@domains,$line);
                   13924:             }
                   13925:             close($fh);
                   13926:         }
1.824     raeburn  13927:     }
                   13928:     return @domains;
                   13929: }
                   13930: 
                   13931: sub default_login_domain {
                   13932:     my $domain = $perlvar{'lonDefDomain'};
                   13933:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13934:     foreach my $posdom (&current_machine_domains(),
                   13935:                         &additional_machine_domains()) {
                   13936:         if (lc($posdom) eq lc($testdomain)) {
                   13937:             $domain=$posdom;
                   13938:             last;
                   13939:         }
                   13940:     }
                   13941:     return $domain;
                   13942: }
                   13943: 
1.1172.2.106  raeburn  13944: sub shared_institution {
1.1172.2.136  raeburn  13945:     my ($dom,$lonhost) = @_;
                   13946:     if ($lonhost eq '') {
                   13947:         $lonhost = $perlvar{'lonHostID'};
                   13948:     }
1.1172.2.106  raeburn  13949:     my $same_intdom;
1.1172.2.136  raeburn  13950:     my $hostintdom = &internet_dom($lonhost);
1.1172.2.106  raeburn  13951:     if ($hostintdom ne '') {
                   13952:         my %iphost = &get_iphost();
                   13953:         my $primary_id = &domain($dom,'primary');
                   13954:         my $primary_ip = &get_host_ip($primary_id);
                   13955:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   13956:             foreach my $id (@{$iphost{$primary_ip}}) {
                   13957:                 my $intdom = &internet_dom($id);
                   13958:                 if ($intdom eq $hostintdom) {
                   13959:                     $same_intdom = 1;
                   13960:                     last;
                   13961:                 }
                   13962:             }
                   13963:         }
                   13964:     }
                   13965:     return $same_intdom;
                   13966: }
                   13967: 
1.1172.2.120  raeburn  13968: sub uses_sts {
                   13969:     my ($ignore_cache) = @_;
                   13970:     my $lonhost = $perlvar{'lonHostID'};
                   13971:     my $hostname = &hostname($lonhost);
                   13972:     my $sts_on;
                   13973:     if ($protocol{$lonhost} eq 'https') {
                   13974:         my $cachetime = 12*3600;
                   13975:         if (!$ignore_cache) {
                   13976:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   13977:             if (defined($cached)) {
                   13978:                 return $sts_on;
                   13979:             }
                   13980:         }
1.1172.2.121  raeburn  13981:         my $ua=new LWP::UserAgent;
1.1172.2.120  raeburn  13982:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   13983:         my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121  raeburn  13984:         my $response=$ua->request($request);
1.1172.2.120  raeburn  13985:         if ($response->is_success) {
                   13986:             my $has_sts = $response->header('Strict-Transport-Security');
                   13987:             if ($has_sts eq '') {
                   13988:                 $sts_on = 0;
                   13989:             } else {
                   13990:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   13991:                     my $maxage = $1;
                   13992:                     if ($maxage) {
                   13993:                         $sts_on = 1;
                   13994:                     } else {
                   13995:                         $sts_on = 0;
                   13996:                     }
                   13997:                 } else {
                   13998:                     $sts_on = 0;
                   13999:                 }
                   14000:             }
                   14001:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   14002:         }
                   14003:     }
                   14004:     return;
                   14005: }
                   14006: 
1.1172.2.142  raeburn  14007: sub waf_allssl {
                   14008:     my ($host_name) = @_;
                   14009:     my $alias = &get_proxy_alias();
                   14010:     if ($host_name eq '') {
                   14011:         $host_name = $ENV{'SERVER_NAME'};
                   14012:     }
                   14013:     if (($host_name ne '') && ($alias eq $host_name)) {
                   14014:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
                   14015:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   14016:         if ($defdomdefaults{'waf_sslopt'}) {
                   14017:             return $defdomdefaults{'waf_sslopt'};
                   14018:         }
                   14019:     }
                   14020:     return;
                   14021: }
                   14022: 
1.1172.2.134  raeburn  14023: sub get_requestor_ip {
                   14024:     my ($r,$nolookup,$noproxy) = @_;
                   14025:     my $from_ip;
                   14026:     if (ref($r)) {
1.1172.2.142  raeburn  14027:         if ($r->can('useragent_ip')) {
                   14028:             if ($noproxy && $r->can('client_ip')) {
                   14029:                 $from_ip = $r->client_ip();
                   14030:             } else {
                   14031:                 $from_ip = $r->useragent_ip();
                   14032:             }
                   14033:         } elsif ($r->connection->can('remote_ip')) {
                   14034:             $from_ip = $r->connection->remote_ip();
                   14035:         } else {
                   14036:             $from_ip = $r->get_remote_host($nolookup);
                   14037:         }
1.1172.2.134  raeburn  14038:     } else {
                   14039:         $from_ip = $ENV{'REMOTE_ADDR'};
                   14040:     }
1.1172.2.142  raeburn  14041:     return $from_ip if ($noproxy);
                   14042:    # Who controls proxy settings for server
                   14043:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14044:     my $proxyinfo = &get_proxy_settings($dom_in_use);
                   14045:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
                   14046:         if ($proxyinfo->{'vpnint'}) {
                   14047:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
                   14048:                 return $from_ip;
                   14049:             }
                   14050:         }
                   14051:         if ($proxyinfo->{'trusted'}) {
                   14052:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
                   14053:                 my $ipheader = $proxyinfo->{'ipheader'};
                   14054:                 my ($ip,$xfor);
                   14055:                 if (ref($r)) {
                   14056:                     if ($ipheader) {
                   14057:                         $ip = $r->headers_in->{$ipheader};
                   14058:                     }
                   14059:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
                   14060:                 } else {
                   14061:                     if ($ipheader) {
                   14062:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
                   14063:                     }
                   14064:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
                   14065:                 }
                   14066:                 if (($ip eq '') && ($xfor ne '')) {
                   14067:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
                   14068:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
                   14069:                             $ip = $poss_ip;
                   14070:                             last;
                   14071:                         }
                   14072:                     }
                   14073:                 }
                   14074:                 if ($ip ne '') {
                   14075:                     return $ip;
                   14076:                 }
                   14077:             }
                   14078:         }
                   14079:     }
1.1172.2.134  raeburn  14080:     return $from_ip;
                   14081: }
                   14082: 
1.1172.2.142  raeburn  14083: sub get_proxy_settings {
                   14084:     my ($dom_in_use) = @_;
                   14085:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   14086:     my $proxyinfo = {
                   14087:                        ipheader => $domdefaults{'waf_ipheader'},
                   14088:                        trusted  => $domdefaults{'waf_trusted'},
                   14089:                        vpnint   => $domdefaults{'waf_vpnint'},
                   14090:                        vpnext   => $domdefaults{'waf_vpnext'},
                   14091:                        sslopt   => $domdefaults{'waf_sslopt'},
                   14092:                     };
                   14093:     return $proxyinfo;
                   14094: }
                   14095: 
                   14096: sub ip_match {
                   14097:     my ($ip,$pattern_str) = @_;
                   14098:     $ip=Net::CIDR::cidrvalidate($ip);
                   14099:     if ($ip) {
                   14100:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
                   14101:     }
                   14102:     return;
                   14103: }
                   14104: 
                   14105: sub get_proxy_alias {
                   14106:     my ($lonid) = @_;
                   14107:     if ($lonid eq '') {
                   14108:         $lonid = $perlvar{'lonHostID'};
                   14109:     }
                   14110:     if (!defined(&hostname($lonid))) {
                   14111:         return;
                   14112:     }
                   14113:     if ($lonid ne '') {
                   14114:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
                   14115:         if ($cached) {
                   14116:             return $alias;
                   14117:         }
                   14118:         my $dom = &Apache::lonnet::host_domain($lonid);
                   14119:         if ($dom ne '') {
                   14120:             my $cachetime = 60*60*24;
                   14121:             my %domconfig =
                   14122:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14123:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14124:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
                   14125:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
                   14126:                 }
                   14127:             }
                   14128:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
                   14129:         }
                   14130:     }
                   14131:     return;
                   14132: }
                   14133: 
                   14134: sub use_proxy_alias {
                   14135:     my ($r,$lonid) = @_;
                   14136:     my $alias = &get_proxy_alias($lonid);
                   14137:     if ($alias) {
                   14138:         my $dom = &host_domain($lonid);
                   14139:         if ($dom ne '') {
                   14140:             my $proxyinfo = &get_proxy_settings($dom);
                   14141:             my ($vpnint,$remote_ip);
                   14142:             if (ref($proxyinfo) eq 'HASH') {
                   14143:                 $vpnint = $proxyinfo->{'vpnint'};
                   14144:                 if ($vpnint) {
                   14145:                     $remote_ip = &get_requestor_ip($r,1,1);
                   14146:                 }
                   14147:             }
                   14148:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
                   14149:                 return $alias;
                   14150:             }
                   14151:         }
                   14152:     }
                   14153:     return;
                   14154: }
                   14155: 
                   14156: sub alias_sso {
                   14157:     my ($lonid) = @_;
                   14158:     if ($lonid eq '') {
                   14159:         $lonid = $perlvar{'lonHostID'};
                   14160:     }
                   14161:     if (!defined(&hostname($lonid))) {
                   14162:         return;
                   14163:     }
                   14164:     if ($lonid ne '') {
                   14165:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
                   14166:         if ($cached) {
                   14167:             return $use_alias;
                   14168:         }
                   14169:         my $dom = &Apache::lonnet::host_domain($lonid);
                   14170:         if ($dom ne '') {
                   14171:             my $cachetime = 60*60*24;
                   14172:             my %domconfig =
                   14173:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14174:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14175:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
                   14176:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
                   14177:                 }
                   14178:             }
                   14179:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
                   14180:         }
                   14181:     }
                   14182:     return;
                   14183: }
                   14184: 
                   14185: sub get_saml_landing {
                   14186:     my ($lonid) = @_;
                   14187:     if ($lonid eq '') {
                   14188:         my $defdom = &default_login_domain();
                   14189:         my @hosts = &current_machine_ids();
                   14190:         if (@hosts > 1) {
                   14191:             foreach my $hostid (@hosts) {
                   14192:                 if (&host_domain($hostid) eq $defdom) {
                   14193:                     $lonid = $hostid;
                   14194:                     last;
                   14195:                 }
                   14196:             }
                   14197:         } else {
                   14198:             $lonid = $perlvar{'lonHostID'};
                   14199:         }
                   14200:         if ($lonid) {
                   14201:             unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
                   14202:                 return;
                   14203:             }
                   14204:         } else {
                   14205:             return;
                   14206:         }
                   14207:     } elsif (!defined(&hostname($lonid))) {
                   14208:         return;
                   14209:     }
                   14210:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
                   14211:     if ($cached) {
                   14212:         return $landing;
                   14213:     }
                   14214:     my $dom = &Apache::lonnet::host_domain($lonid);
                   14215:     if ($dom ne '') {
                   14216:         my $cachetime = 60*60*24;
                   14217:         my %domconfig =
                   14218:             &Apache::lonnet::get_dom('configuration',['login'],$dom);
                   14219:         if (ref($domconfig{'login'}) eq 'HASH') {
                   14220:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
                   14221:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
                   14222:                     $landing = 1;
                   14223:                 }
                   14224:             }
                   14225:         }
                   14226:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
                   14227:     }
                   14228:     return;
                   14229: }
                   14230: 
1.31      www      14231: # ------------------------------------------------------------- Declutters URLs
                   14232: 
                   14233: sub declutter {
                   14234:     my $thisfn=shift;
1.569     albertel 14235:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  14236:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   14237:         $thisfn=~s{^/home/httpd/html}{};
                   14238:     }
1.31      www      14239:     $thisfn=~s/^\///;
1.697     albertel 14240:     $thisfn=~s|^adm/wrapper/||;
                   14241:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      14242:     $thisfn=~s/^res\///;
1.1172    bisitz   14243:     $thisfn=~s/^priv\///;
1.1032    raeburn  14244:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   14245:         $thisfn=~s/\?.+$//;
                   14246:     }
1.268     www      14247:     return $thisfn;
                   14248: }
                   14249: 
                   14250: # ------------------------------------------------------------- Clutter up URLs
                   14251: 
                   14252: sub clutter {
                   14253:     my $thisfn='/'.&declutter(shift);
1.887     albertel 14254:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 14255: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      14256:        $thisfn='/res'.$thisfn; 
                   14257:     }
1.1031    raeburn  14258:     if ($thisfn !~m|^/adm|) {
                   14259: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 14260: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 14261: 	} else {
                   14262: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   14263: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 14264: 	    if ($embstyle eq 'ssi'
                   14265: 		|| ($embstyle eq 'hdn')
                   14266: 		|| ($embstyle eq 'rat')
                   14267: 		|| ($embstyle eq 'prv')
                   14268: 		|| ($embstyle eq 'ign')) {
                   14269: 		#do nothing with these
                   14270: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 14271: 		|| ($embstyle eq 'emb')
                   14272: 		|| ($embstyle eq 'wrp')) {
                   14273: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 14274: 	    } elsif ($embstyle eq 'unk'
                   14275: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 14276: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 14277: 	    } else {
1.718     www      14278: #		&logthis("Got a blank emb style");
1.695     albertel 14279: 	    }
1.694     albertel 14280: 	}
1.1172.2.146.  .1(raebu 14281:22):     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
                   14282:22):         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 14283:     }
1.31      www      14284:     return $thisfn;
1.12      www      14285: }
                   14286: 
1.787     albertel 14287: sub clutter_with_no_wrapper {
                   14288:     my $uri = &clutter(shift);
                   14289:     if ($uri =~ m-^/adm/-) {
                   14290: 	$uri =~ s-^/adm/wrapper/-/-;
                   14291: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   14292:     }
                   14293:     return $uri;
                   14294: }
                   14295: 
1.557     albertel 14296: sub freeze_escape {
                   14297:     my ($value)=@_;
                   14298:     if (ref($value)) {
                   14299: 	$value=&nfreeze($value);
                   14300: 	return '__FROZEN__'.&escape($value);
                   14301:     }
                   14302:     return &escape($value);
                   14303: }
                   14304: 
1.11      www      14305: 
1.557     albertel 14306: sub thaw_unescape {
                   14307:     my ($value)=@_;
                   14308:     if ($value =~ /^__FROZEN__/) {
                   14309: 	substr($value,0,10,undef);
                   14310: 	$value=&unescape($value);
                   14311: 	return &thaw($value);
                   14312:     }
                   14313:     return &unescape($value);
                   14314: }
                   14315: 
1.436     albertel 14316: sub correct_line_ends {
                   14317:     my ($result)=@_;
                   14318:     $$result =~s/\r\n/\n/mg;
                   14319:     $$result =~s/\r/\n/mg;
1.415     albertel 14320: }
1.1       albertel 14321: # ================================================================ Main Program
                   14322: 
1.184     www      14323: sub goodbye {
1.204     albertel 14324:    &logthis("Starting Shut down");
1.443     albertel 14325: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 14326:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 14327: #converted
1.599     albertel 14328: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 14329:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   14330: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   14331: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 14332: #1.1 only
1.870     albertel 14333: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   14334: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   14335: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   14336: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   14337:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 14338:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   14339:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      14340:    &flushcourselogs();
                   14341:    &logthis("Shutting down");
                   14342: }
                   14343: 
1.852     albertel 14344: sub get_dns {
1.1172.2.17  raeburn  14345:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 14346:     if (!$ignore_cache) {
                   14347: 	my ($content,$cached)=
                   14348: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   14349: 	if ($cached) {
1.1172.2.17  raeburn  14350: 	    &$func($content,$hashref);
1.869     albertel 14351: 	    return;
                   14352: 	}
                   14353:     }
                   14354: 
                   14355:     my %alldns;
1.1172.2.96  raeburn  14356:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   14357:         foreach my $dns (<$config>) {
                   14358: 	    next if ($dns !~ /^\^(\S*)/x);
                   14359:             my $line = $1;
                   14360:             my ($host,$protocol) = split(/:/,$line);
                   14361:             if ($protocol ne 'https') {
                   14362:                 $protocol = 'http';
                   14363:             }
                   14364: 	    $alldns{$host} = $protocol;
1.979     raeburn  14365:         }
1.1172.2.96  raeburn  14366:         close($config);
1.869     albertel 14367:     }
                   14368:     while (%alldns) {
1.1172.2.52  raeburn  14369: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1172.2.142  raeburn  14370:         my @content;
                   14371:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
                   14372:             my $command = (split('/',$url))[3];
                   14373:             my ($dir,$file) = &parse_getdns_url($command,$url);
                   14374:             delete($alldns{$dns});
                   14375:             next if (($dir eq '') || ($file eq ''));
                   14376:             if (open(my $config,'<',"$dir/$file")) {
                   14377:                 @content = <$config>;
                   14378:                 close($config);
                   14379:             }
                   14380:         } else {
                   14381: 	    my $ua=new LWP::UserAgent;
                   14382:             $ua->timeout(30);
                   14383: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
                   14384: 	    my $response=$ua->request($request);
                   14385:             delete($alldns{$dns});
                   14386: 	    next if ($response->is_error());
                   14387: 	    @content = split("\n",$response->content);
                   14388:         }
1.1172.2.17  raeburn  14389:         unless ($nocache) {
1.1172.2.23  raeburn  14390: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  14391:         }
                   14392: 	&$func(\@content,$hashref);
1.869     albertel 14393: 	return;
1.852     albertel 14394:     }
1.871     albertel 14395:     my $which = (split('/',$url))[3];
                   14396:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  14397:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   14398:         my @content = <$config>;
                   14399:         &$func(\@content,$hashref);
                   14400:     }
1.1172.2.17  raeburn  14401:     return;
                   14402: }
                   14403: 
                   14404: # ------------------------------------------------------Get DNS checksums file
                   14405: sub parse_dns_checksums_tab {
                   14406:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  14407:     my $lonhost = $perlvar{'lonHostID'};
                   14408:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  14409:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  14410:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   14411:     my $webconfdir = '/etc/httpd/conf';
                   14412:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   14413:         $webconfdir = '/etc/apache2';
                   14414:     } elsif ($distro =~ /^sles(\d+)$/) {
                   14415:         if ($1 >= 10) {
                   14416:             $webconfdir = '/etc/apache2';
                   14417:         }
                   14418:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   14419:         if ($1 >= 10.0) {
                   14420:             $webconfdir = '/etc/apache2';
                   14421:         }
                   14422:     }
1.1172.2.17  raeburn  14423:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14424:     my (%chksum,%revnum);
                   14425:     if (ref($lines) eq 'ARRAY') {
                   14426:         chomp(@{$lines});
1.1172.2.34  raeburn  14427:         my $version = shift(@{$lines});
                   14428:         if ($version eq $release) {
1.1172.2.17  raeburn  14429:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  14430:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  14431:                 if ($file =~ m{^/etc/httpd/conf}) {
                   14432:                     if ($webconfdir eq '/etc/apache2') {
                   14433:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   14434:                     }
                   14435:                 }
1.1172.2.34  raeburn  14436:                 $chksum{$file} = $shasum;
                   14437:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  14438:             }
                   14439:             if (ref($hashref) eq 'HASH') {
                   14440:                 %{$hashref} = (
                   14441:                                 sums     => \%chksum,
                   14442:                                 versions => \%revnum,
                   14443:                               );
                   14444:             }
                   14445:         }
                   14446:     }
1.869     albertel 14447:     return;
1.852     albertel 14448: }
1.1172.2.17  raeburn  14449: 
                   14450: sub fetch_dns_checksums {
                   14451:     my %checksums;
1.1172.2.34  raeburn  14452:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  14453:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  14454:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14455:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  14456:              \%checksums);
                   14457:     return \%checksums;
                   14458: }
                   14459: 
1.1172.2.142  raeburn  14460: sub parse_getdns_url {
                   14461:     my ($command,$url) = @_;
                   14462:     my $dir = $perlvar{'lonTabDir'};
                   14463:     my $file;
                   14464:     if ($command eq 'hosts') {
                   14465:         $file = 'dns_hosts.tab';
                   14466:     } elsif ($command eq 'domain') {
                   14467:         $file = 'dns_domain.tab';
                   14468:     } elsif ($command eq 'checksums') {
                   14469:         my $version = (split('/',$url))[4];
                   14470:         $file = "dns_checksums/$version.tab",
                   14471:     }
                   14472:     return ($dir,$file);
                   14473: }
                   14474: 
1.327     albertel 14475: # ------------------------------------------------------------ Read domain file
                   14476: {
1.852     albertel 14477:     my $loaded;
1.846     albertel 14478:     my %domain;
                   14479: 
1.852     albertel 14480:     sub parse_domain_tab {
                   14481: 	my ($lines) = @_;
                   14482: 	foreach my $line (@$lines) {
                   14483: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      14484: 
1.846     albertel 14485: 	    chomp($line);
1.852     albertel 14486: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 14487: 	    my %this_domain;
                   14488: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   14489: 			       'lang_def', 'city', 'longi', 'lati',
                   14490: 			       'primary') {
                   14491: 		$this_domain{$field} = shift(@elements);
                   14492: 	    }
                   14493: 	    $domain{$name} = \%this_domain;
1.852     albertel 14494: 	}
                   14495:     }
1.864     albertel 14496: 
                   14497:     sub reset_domain_info {
                   14498: 	undef($loaded);
                   14499: 	undef(%domain);
                   14500:     }
                   14501: 
1.852     albertel 14502:     sub load_domain_tab {
1.1172.2.70  raeburn  14503: 	my ($ignore_cache,$nocache) = @_;
                   14504: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 14505: 	my $fh;
1.1172.2.96  raeburn  14506: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 14507: 	    my @lines = <$fh>;
                   14508: 	    &parse_domain_tab(\@lines);
1.448     albertel 14509: 	}
1.852     albertel 14510: 	close($fh);
                   14511: 	$loaded = 1;
1.327     albertel 14512:     }
1.846     albertel 14513: 
                   14514:     sub domain {
1.852     albertel 14515: 	&load_domain_tab() if (!$loaded);
                   14516: 
1.846     albertel 14517: 	my ($name,$what) = @_;
                   14518: 	return if ( !exists($domain{$name}) );
                   14519: 
                   14520: 	if (!$what) {
                   14521: 	    return $domain{$name}{'description'};
                   14522: 	}
                   14523: 	return $domain{$name}{$what};
                   14524:     }
1.974     raeburn  14525: 
                   14526:     sub domain_info {
                   14527:         &load_domain_tab() if (!$loaded);
                   14528:         return %domain;
                   14529:     }
                   14530: 
1.327     albertel 14531: }
                   14532: 
                   14533: 
1.1       albertel 14534: # ------------------------------------------------------------- Read hosts file
                   14535: {
1.838     albertel 14536:     my %hostname;
1.844     albertel 14537:     my %hostdom;
1.845     albertel 14538:     my %libserv;
1.852     albertel 14539:     my $loaded;
1.888     albertel 14540:     my %name_to_host;
1.1074    raeburn  14541:     my %internetdom;
1.1107    raeburn  14542:     my %LC_dns_serv;
1.852     albertel 14543: 
                   14544:     sub parse_hosts_tab {
                   14545: 	my ($file) = @_;
                   14546: 	foreach my $configline (@$file) {
                   14547: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  14548:             chomp($configline);
                   14549: 	    if ($configline =~ /^\^/) {
                   14550:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   14551:                     $LC_dns_serv{$1} = 1;
                   14552:                 }
                   14553:                 next;
                   14554:             }
1.1074    raeburn  14555: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 14556: 	    $name=~s/\s//g;
                   14557: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  14558:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   14559:                     my $curr = $hostname{$id};
                   14560:                     my $skip;
                   14561:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   14562:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   14563:                             $skip = 1;
                   14564:                         } else {
                   14565:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   14566:                         }
                   14567:                     }
                   14568:                     unless ($skip) {
                   14569:                         push(@{$name_to_host{$name}},$id);
                   14570:                     }
                   14571:                 } else {
                   14572:                     push(@{$name_to_host{$name}},$id);
                   14573:                 }
1.852     albertel 14574: 		$hostname{$id}=$name;
                   14575: 		$hostdom{$id}=$domain;
                   14576: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  14577:                 if (defined($protocol)) {
                   14578:                     if ($protocol eq 'https') {
                   14579:                         $protocol{$id} = $protocol;
                   14580:                     } else {
                   14581:                         $protocol{$id} = 'http'; 
                   14582:                     }
1.968     raeburn  14583:                 } else {
1.969     raeburn  14584:                     $protocol{$id} = 'http';
1.968     raeburn  14585:                 }
1.1074    raeburn  14586:                 if (defined($intdom)) {
                   14587:                     $internetdom{$id} = $intdom;
                   14588:                 }
1.852     albertel 14589: 	    }
                   14590: 	}
                   14591:     }
1.864     albertel 14592:     
                   14593:     sub reset_hosts_info {
1.897     albertel 14594: 	&purge_remembered();
1.864     albertel 14595: 	&reset_domain_info();
                   14596: 	&reset_hosts_ip_info();
1.892     albertel 14597: 	undef(%name_to_host);
1.864     albertel 14598: 	undef(%hostname);
                   14599: 	undef(%hostdom);
                   14600: 	undef(%libserv);
                   14601: 	undef($loaded);
                   14602:     }
1.1       albertel 14603: 
1.852     albertel 14604:     sub load_hosts_tab {
1.1172.2.70  raeburn  14605: 	my ($ignore_cache,$nocache) = @_;
                   14606: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  14607: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 14608: 	my @config = <$config>;
                   14609: 	&parse_hosts_tab(\@config);
                   14610: 	close($config);
                   14611: 	$loaded=1;
1.1       albertel 14612:     }
1.852     albertel 14613: 
1.838     albertel 14614:     sub hostname {
1.852     albertel 14615: 	&load_hosts_tab() if (!$loaded);
                   14616: 
1.838     albertel 14617: 	my ($lonid) = @_;
                   14618: 	return $hostname{$lonid};
                   14619:     }
1.845     albertel 14620: 
1.838     albertel 14621:     sub all_hostnames {
1.852     albertel 14622: 	&load_hosts_tab() if (!$loaded);
                   14623: 
1.838     albertel 14624: 	return %hostname;
                   14625:     }
1.845     albertel 14626: 
1.888     albertel 14627:     sub all_names {
1.1172.2.70  raeburn  14628:         my ($ignore_cache,$nocache) = @_;
                   14629: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 14630: 
                   14631: 	return %name_to_host;
                   14632:     }
                   14633: 
1.974     raeburn  14634:     sub all_host_domain {
                   14635:         &load_hosts_tab() if (!$loaded);
                   14636:         return %hostdom;
                   14637:     }
                   14638: 
1.845     albertel 14639:     sub is_library {
1.852     albertel 14640: 	&load_hosts_tab() if (!$loaded);
                   14641: 
1.845     albertel 14642: 	return exists($libserv{$_[0]});
                   14643:     }
                   14644: 
                   14645:     sub all_library {
1.852     albertel 14646: 	&load_hosts_tab() if (!$loaded);
                   14647: 
1.845     albertel 14648: 	return %libserv;
                   14649:     }
                   14650: 
1.1062    droeschl 14651:     sub unique_library {
                   14652: 	#2x reverse removes all hostnames that appear more than once
                   14653:         my %unique = reverse &all_library();
                   14654:         return reverse %unique;
                   14655:     }
                   14656: 
1.841     albertel 14657:     sub get_servers {
1.852     albertel 14658: 	&load_hosts_tab() if (!$loaded);
                   14659: 
1.841     albertel 14660: 	my ($domain,$type) = @_;
                   14661: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   14662: 	                                          : %hostname;
                   14663: 	my %result;
1.842     albertel 14664: 	if (ref($domain) eq 'ARRAY') {
                   14665: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 14666: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 14667: 		    $result{$host} = $hostname;
                   14668: 		}
                   14669: 	    }
                   14670: 	} else {
                   14671: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   14672: 		if ($hostdom{$host} eq $domain) {
                   14673: 		    $result{$host} = $hostname;
                   14674: 		}
1.841     albertel 14675: 	    }
                   14676: 	}
                   14677: 	return %result;
                   14678:     }
1.845     albertel 14679: 
1.1062    droeschl 14680:     sub get_unique_servers {
                   14681:         my %unique = reverse &get_servers(@_);
                   14682: 	return reverse %unique;
                   14683:     }
                   14684: 
1.844     albertel 14685:     sub host_domain {
1.852     albertel 14686: 	&load_hosts_tab() if (!$loaded);
                   14687: 
1.844     albertel 14688: 	my ($lonid) = @_;
                   14689: 	return $hostdom{$lonid};
                   14690:     }
                   14691: 
1.841     albertel 14692:     sub all_domains {
1.852     albertel 14693: 	&load_hosts_tab() if (!$loaded);
                   14694: 
1.841     albertel 14695: 	my %seen;
                   14696: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   14697: 	return @uniq;
                   14698:     }
1.1074    raeburn  14699: 
                   14700:     sub internet_dom {
                   14701:         &load_hosts_tab() if (!$loaded);
                   14702: 
                   14703:         my ($lonid) = @_;
                   14704:         return $internetdom{$lonid};
                   14705:     }
1.1107    raeburn  14706: 
                   14707:     sub is_LC_dns {
                   14708:         &load_hosts_tab() if (!$loaded);
                   14709: 
                   14710:         my ($hostname) = @_;
                   14711:         return exists($LC_dns_serv{$hostname});
                   14712:     }
                   14713: 
1.1       albertel 14714: }
                   14715: 
1.847     albertel 14716: { 
                   14717:     my %iphost;
1.856     albertel 14718:     my %name_to_ip;
                   14719:     my %lonid_to_ip;
1.869     albertel 14720: 
1.847     albertel 14721:     sub get_hosts_from_ip {
                   14722: 	my ($ip) = @_;
                   14723: 	my %iphosts = &get_iphost();
                   14724: 	if (ref($iphosts{$ip})) {
                   14725: 	    return @{$iphosts{$ip}};
                   14726: 	}
                   14727: 	return;
1.839     albertel 14728:     }
1.864     albertel 14729:     
                   14730:     sub reset_hosts_ip_info {
                   14731: 	undef(%iphost);
                   14732: 	undef(%name_to_ip);
                   14733: 	undef(%lonid_to_ip);
                   14734:     }
1.856     albertel 14735: 
                   14736:     sub get_host_ip {
                   14737: 	my ($lonid) = @_;
                   14738: 	if (exists($lonid_to_ip{$lonid})) {
                   14739: 	    return $lonid_to_ip{$lonid};
                   14740: 	}
                   14741: 	my $name=&hostname($lonid);
                   14742:    	my $ip = gethostbyname($name);
                   14743: 	return if (!$ip || length($ip) ne 4);
                   14744: 	$ip=inet_ntoa($ip);
                   14745: 	$name_to_ip{$name}   = $ip;
                   14746: 	$lonid_to_ip{$lonid} = $ip;
                   14747: 	return $ip;
                   14748:     }
1.847     albertel 14749:     
                   14750:     sub get_iphost {
1.1172.2.70  raeburn  14751: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14752: 
1.869     albertel 14753: 	if (!$ignore_cache) {
                   14754: 	    if (%iphost) {
                   14755: 		return %iphost;
                   14756: 	    }
                   14757: 	    my ($ip_info,$cached)=
                   14758: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14759: 	    if ($cached) {
                   14760: 		%iphost      = %{$ip_info->[0]};
                   14761: 		%name_to_ip  = %{$ip_info->[1]};
                   14762: 		%lonid_to_ip = %{$ip_info->[2]};
                   14763: 		return %iphost;
                   14764: 	    }
                   14765: 	}
1.894     albertel 14766: 
                   14767: 	# get yesterday's info for fallback
                   14768: 	my %old_name_to_ip;
                   14769: 	my ($ip_info,$cached)=
                   14770: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14771: 	if ($cached) {
                   14772: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14773: 	}
                   14774: 
1.1172.2.70  raeburn  14775: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14776: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14777: 	    my $ip;
                   14778: 	    if (!exists($name_to_ip{$name})) {
                   14779: 		$ip = gethostbyname($name);
                   14780: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14781: 		    if (defined($old_name_to_ip{$name})) {
                   14782: 			$ip = $old_name_to_ip{$name};
                   14783: 			&logthis("Can't find $name defaulting to old $ip");
                   14784: 		    } else {
                   14785: 			&logthis("Name $name no IP found");
                   14786: 			next;
                   14787: 		    }
                   14788: 		} else {
                   14789: 		    $ip=inet_ntoa($ip);
1.847     albertel 14790: 		}
                   14791: 		$name_to_ip{$name} = $ip;
                   14792: 	    } else {
                   14793: 		$ip = $name_to_ip{$name};
1.653     albertel 14794: 	    }
1.888     albertel 14795: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14796: 		$lonid_to_ip{$id} = $ip;
                   14797: 	    }
                   14798: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14799: 	}
1.1172.2.70  raeburn  14800:         unless ($nocache) {
                   14801: 	    &do_cache_new('iphost','iphost',
                   14802: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14803: 		          48*60*60);
                   14804:         }
1.869     albertel 14805: 
1.847     albertel 14806: 	return %iphost;
1.598     albertel 14807:     }
                   14808: 
1.992     raeburn  14809:     #
                   14810:     #  Given a DNS returns the loncapa host name for that DNS 
                   14811:     # 
                   14812:     sub host_from_dns {
                   14813:         my ($dns) = @_;
                   14814:         my @hosts;
                   14815:         my $ip;
                   14816: 
1.993     raeburn  14817:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14818:             $ip = $name_to_ip{$dns};
                   14819:         }
                   14820:         if (!$ip) {
                   14821:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14822:             if (length($ip) == 4) { 
                   14823: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14824:             }
                   14825:         }
                   14826:         if ($ip) {
                   14827: 	    @hosts = get_hosts_from_ip($ip);
                   14828: 	    return $hosts[0];
                   14829:         }
                   14830:         return undef;
1.986     foxr     14831:     }
1.992     raeburn  14832: 
1.1074    raeburn  14833:     sub get_internet_names {
                   14834:         my ($lonid) = @_;
                   14835:         return if ($lonid eq '');
                   14836:         my ($idnref,$cached)=
                   14837:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14838:         if ($cached) {
                   14839:             return $idnref;
                   14840:         }
                   14841:         my $ip = &get_host_ip($lonid);
                   14842:         my @hosts = &get_hosts_from_ip($ip);
                   14843:         my %iphost = &get_iphost();
                   14844:         my (@idns,%seen);
                   14845:         foreach my $id (@hosts) {
                   14846:             my $dom = &host_domain($id);
                   14847:             my $prim_id = &domain($dom,'primary');
                   14848:             my $prim_ip = &get_host_ip($prim_id);
                   14849:             next if ($seen{$prim_ip});
                   14850:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14851:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14852:                     my $intdom = &internet_dom($id);
                   14853:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14854:                         push(@idns,$intdom);
                   14855:                     }
                   14856:                 }
                   14857:             }
                   14858:             $seen{$prim_ip} = 1;
                   14859:         }
1.1172.2.23  raeburn  14860:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  14861:     }
                   14862: 
1.986     foxr     14863: }
                   14864: 
1.1079    raeburn  14865: sub all_loncaparevs {
1.1172.2.39  raeburn  14866:     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  14867: }
                   14868: 
1.1172.2.27  raeburn  14869: # ------------------------------------------------------- Read loncaparev table
                   14870: {
                   14871:     sub load_loncaparevs {
                   14872:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  14873:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  14874:                 while (my $configline=<$config>) {
                   14875:                     chomp($configline);
                   14876:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14877:                     $loncaparevs{$hostid}=$loncaparev;
                   14878:                 }
                   14879:                 close($config);
                   14880:             }
                   14881:         }
                   14882:     }
                   14883: }
                   14884: 
                   14885: # ----------------------------------------------------- Read serverhostID table
                   14886: {
                   14887:     sub load_serverhomeIDs {
                   14888:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  14889:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  14890:                 while (my $configline=<$config>) {
                   14891:                     chomp($configline);
                   14892:                     my ($name,$id)=split(/:/,$configline);
                   14893:                     $serverhomeIDs{$name}=$id;
                   14894:                 }
                   14895:                 close($config);
                   14896:             }
                   14897:         }
                   14898:     }
                   14899: }
                   14900: 
                   14901: 
1.862     albertel 14902: BEGIN {
                   14903: 
                   14904: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14905:     unless ($readit) {
                   14906: {
                   14907:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14908:     %perlvar = (%perlvar,%{$configvars});
                   14909: }
                   14910: 
                   14911: 
1.1       albertel 14912: # ------------------------------------------------------ Read spare server file
                   14913: {
1.1172.2.96  raeburn  14914:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14915: 
                   14916:     while (my $configline=<$config>) {
                   14917:        chomp($configline);
1.284     matthew  14918:        if ($configline) {
1.784     albertel 14919: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14920: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14921: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14922:        }
                   14923:     }
1.448     albertel 14924:     close($config);
1.1       albertel 14925: }
1.11      www      14926: # ------------------------------------------------------------ Read permissions
                   14927: {
1.1172.2.96  raeburn  14928:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14929: 
                   14930:     while (my $configline=<$config>) {
1.448     albertel 14931: 	chomp($configline);
                   14932: 	if ($configline) {
                   14933: 	    my ($role,$perm)=split(/ /,$configline);
                   14934: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14935: 	}
1.11      www      14936:     }
1.448     albertel 14937:     close($config);
1.11      www      14938: }
                   14939: 
                   14940: # -------------------------------------------- Read plain texts for permissions
                   14941: {
1.1172.2.96  raeburn  14942:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14943: 
                   14944:     while (my $configline=<$config>) {
1.448     albertel 14945: 	chomp($configline);
                   14946: 	if ($configline) {
1.742     raeburn  14947: 	    my ($short,@plain)=split(/:/,$configline);
                   14948:             %{$prp{$short}} = ();
                   14949: 	    if (@plain > 0) {
                   14950:                 $prp{$short}{'std'} = $plain[0];
                   14951:                 for (my $i=1; $i<@plain; $i++) {
                   14952:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14953:                 }
                   14954:             }
1.448     albertel 14955: 	}
1.135     www      14956:     }
1.448     albertel 14957:     close($config);
1.135     www      14958: }
                   14959: 
                   14960: # ---------------------------------------------------------- Read package table
                   14961: {
1.1172.2.96  raeburn  14962:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14963: 
                   14964:     while (my $configline=<$config>) {
1.483     albertel 14965: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14966: 	chomp($configline);
                   14967: 	my ($short,$plain)=split(/:/,$configline);
                   14968: 	my ($pack,$name)=split(/\&/,$short);
                   14969: 	if ($plain ne '') {
                   14970: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14971: 	    $packagetab{$short}=$plain; 
                   14972: 	}
1.11      www      14973:     }
1.448     albertel 14974:     close($config);
1.329     matthew  14975: }
                   14976: 
1.1172.2.27  raeburn  14977: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  14978: 
1.1172.2.27  raeburn  14979: &load_loncaparevs();
                   14980: 
                   14981: # ------------------------------------------------------- Read serverhostID table
                   14982: 
                   14983: &load_serverhomeIDs();
1.1074    raeburn  14984: 
1.1172.2.27  raeburn  14985: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14986: {
                   14987:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14988:     if (-e $file) {
                   14989:         my $parser = HTML::LCParser->new($file);
                   14990:         while (my $token = $parser->get_token()) {
                   14991:             if ($token->[0] eq 'S') {
                   14992:                 my $item = $token->[1];
                   14993:                 my $name = $token->[2]{'name'};
                   14994:                 my $value = $token->[2]{'value'};
                   14995:                 if ($item ne '' && $name ne '' && $value ne '') {
                   14996:                     my $release = $parser->get_text();
                   14997:                     $release =~ s/(^\s*|\s*$ )//gx;
                   14998:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   14999:                 }
                   15000:             }
                   15001:         }
                   15002:     }
1.1073    raeburn  15003: }
                   15004: 
1.1138    raeburn  15005: # ---------------------------------------------------------- Read managers table
                   15006: {
                   15007:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  15008:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  15009:             while (my $configline=<$config>) {
                   15010:                 chomp($configline);
                   15011:                 next if ($configline =~ /^\#/);
                   15012:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   15013:                     $managerstab{$configline} = 1;
                   15014:                 }
                   15015:             }
                   15016:             close($config);
                   15017:         }
                   15018:     }
                   15019: }
                   15020: 
1.329     matthew  15021: # ------------- set up temporary directory
                   15022: {
1.1117    foxr     15023:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  15024: 
1.11      www      15025: }
                   15026: 
1.1172.2.104  raeburn  15027: # ------------- set default texengine (domain default overrides this)
                   15028: {
                   15029:     $deftex = LONCAPA::texengine();
                   15030: }
                   15031: 
1.1172.2.114  raeburn  15032: # ------------- set default minimum length for passwords for internal auth users
                   15033: {
                   15034:     $passwdmin = LONCAPA::passwd_min();
                   15035: }
                   15036: 
1.794     albertel 15037: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   15038: 				'compress_threshold'=> 20_000,
                   15039:  			        });
1.185     www      15040: 
1.281     www      15041: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      15042: $dumpcount=0;
1.958     www      15043: $locknum=0;
1.22      www      15044: 
1.163     harris41 15045: &logtouch();
1.672     albertel 15046: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      15047: $readit=1;
1.564     albertel 15048:     {
                   15049: 	use integer;
                   15050: 	my $test=(2**32)+1;
1.568     albertel 15051: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 15052: 	&logthis(" Detected 64bit platform ($_64bit)");
                   15053:     }
1.195     www      15054: }
1.1       albertel 15055: }
1.179     www      15056: 
1.1       albertel 15057: 1;
1.191     harris41 15058: __END__
                   15059: 
1.243     albertel 15060: =pod
                   15061: 
1.191     harris41 15062: =head1 NAME
                   15063: 
1.243     albertel 15064: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 15065: 
                   15066: =head1 SYNOPSIS
                   15067: 
1.243     albertel 15068: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 15069: 
                   15070:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   15071: 
1.243     albertel 15072: Common parameters:
                   15073: 
                   15074: =over 4
                   15075: 
                   15076: =item *
                   15077: 
                   15078: $uname : an internal username (if $cname expecting a course Id specifically)
                   15079: 
                   15080: =item *
                   15081: 
                   15082: $udom : a domain (if $cdom expecting a course's domain specifically)
                   15083: 
                   15084: =item *
                   15085: 
                   15086: $symb : a resource instance identifier
                   15087: 
                   15088: =item *
                   15089: 
                   15090: $namespace : the name of a .db file that contains the data needed or
                   15091: being set.
                   15092: 
                   15093: =back
                   15094: 
1.394     bowersj2 15095: =head1 OVERVIEW
1.191     harris41 15096: 
1.394     bowersj2 15097: lonnet provides subroutines which interact with the
                   15098: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   15099: about classes, users, and resources.
1.243     albertel 15100: 
                   15101: For many of these objects you can also use this to store data about
                   15102: them or modify them in various ways.
1.191     harris41 15103: 
1.394     bowersj2 15104: =head2 Symbs
1.191     harris41 15105: 
1.394     bowersj2 15106: To identify a specific instance of a resource, LON-CAPA uses symbols
                   15107: or "symbs"X<symb>. These identifiers are built from the URL of the
                   15108: map, the resource number of the resource in the map, and the URL of
                   15109: the resource itself. The latter is somewhat redundant, but might help
                   15110: if maps change.
                   15111: 
                   15112: An example is
                   15113: 
                   15114:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   15115: 
                   15116: The respective map entry is
                   15117: 
                   15118:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   15119:   title="Problem 2">
                   15120:  </resource>
                   15121: 
                   15122: Symbs are used by the random number generator, as well as to store and
                   15123: restore data specific to a certain instance of for example a problem.
                   15124: 
                   15125: =head2 Storing And Retrieving Data
                   15126: 
                   15127: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   15128: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   15129: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   15130: is is the non-critical message twin of cstore. These functions are for
                   15131: handlers to store a perl hash to a user's permanent data space in an
                   15132: easy manner, and to retrieve it again on another call. It is expected
                   15133: that a handler would use this once at the beginning to retrieve data,
                   15134: and then again once at the end to send only the new data back.
                   15135: 
                   15136: The data is stored in the user's data directory on the user's
                   15137: homeserver under the ID of the course.
                   15138: 
                   15139: The hash that is returned by restore will have all of the previous
                   15140: value for all of the elements of the hash.
                   15141: 
                   15142: Example:
                   15143: 
                   15144:  #creating a hash
                   15145:  my %hash;
                   15146:  $hash{'foo'}='bar';
                   15147: 
                   15148:  #storing it
                   15149:  &Apache::lonnet::cstore(\%hash);
                   15150: 
                   15151:  #changing a value
                   15152:  $hash{'foo'}='notbar';
                   15153: 
                   15154:  #adding a new value
                   15155:  $hash{'bar'}='foo';
                   15156:  &Apache::lonnet::cstore(\%hash);
                   15157: 
                   15158:  #retrieving the hash
                   15159:  my %history=&Apache::lonnet::restore();
                   15160: 
                   15161:  #print the hash
                   15162:  foreach my $key (sort(keys(%history))) {
                   15163:    print("\%history{$key} = $history{$key}");
                   15164:  }
                   15165: 
                   15166: Will print out:
1.191     harris41 15167: 
1.394     bowersj2 15168:  %history{1:foo} = bar
                   15169:  %history{1:keys} = foo:timestamp
                   15170:  %history{1:timestamp} = 990455579
                   15171:  %history{2:bar} = foo
                   15172:  %history{2:foo} = notbar
                   15173:  %history{2:keys} = foo:bar:timestamp
                   15174:  %history{2:timestamp} = 990455580
                   15175:  %history{bar} = foo
                   15176:  %history{foo} = notbar
                   15177:  %history{timestamp} = 990455580
                   15178:  %history{version} = 2
                   15179: 
                   15180: Note that the special hash entries C<keys>, C<version> and
                   15181: C<timestamp> were added to the hash. C<version> will be equal to the
                   15182: total number of versions of the data that have been stored. The
                   15183: C<timestamp> attribute will be the UNIX time the hash was
                   15184: stored. C<keys> is available in every historical section to list which
                   15185: keys were added or changed at a specific historical revision of a
                   15186: hash.
                   15187: 
                   15188: B<Warning>: do not store the hash that restore returns directly. This
                   15189: will cause a mess since it will restore the historical keys as if the
                   15190: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 15191: 
1.394     bowersj2 15192: Calling convention:
1.191     harris41 15193: 
1.1172.2.27  raeburn  15194:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  15195:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 15196: 
1.394     bowersj2 15197: For more detailed information, see lonnet specific documentation.
1.191     harris41 15198: 
1.394     bowersj2 15199: =head1 RETURN MESSAGES
1.191     harris41 15200: 
1.394     bowersj2 15201: =over 4
1.191     harris41 15202: 
1.394     bowersj2 15203: =item * B<con_lost>: unable to contact remote host
1.191     harris41 15204: 
1.394     bowersj2 15205: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   15206: when the connection is brought back up
1.191     harris41 15207: 
1.394     bowersj2 15208: =item * B<con_failed>: unable to contact remote host and unable to save message
                   15209: for later delivery
1.191     harris41 15210: 
1.967     bisitz   15211: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 15212: 
1.394     bowersj2 15213: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 15214: that was requested
1.191     harris41 15215: 
1.243     albertel 15216: =back
1.191     harris41 15217: 
1.243     albertel 15218: =head1 PUBLIC SUBROUTINES
1.191     harris41 15219: 
1.243     albertel 15220: =head2 Session Environment Functions
1.191     harris41 15221: 
1.243     albertel 15222: =over 4
1.191     harris41 15223: 
1.394     bowersj2 15224: =item * 
                   15225: X<appenv()>
1.949     raeburn  15226: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 15227: the user envirnoment file, and will be restored for each access this
1.620     albertel 15228: user makes during this session, also modifies the %env for the current
1.949     raeburn  15229: process. Optional rolesarrayref - if defined contains a reference to an array
                   15230: of roles which are exempt from the restriction on modifying user.role entries 
                   15231: in the user's environment.db and in %env.    
1.191     harris41 15232: 
                   15233: =item *
1.394     bowersj2 15234: X<delenv()>
1.987     raeburn  15235: B<delenv($delthis,$regexp)>: removes all items from the session
                   15236: environment file that begin with $delthis. If the 
                   15237: optional second arg - $regexp - is true, $delthis is treated as a 
                   15238: regular expression, otherwise \Q$delthis\E is used. 
                   15239: The values are also deleted from the current processes %env.
1.191     harris41 15240: 
1.795     albertel 15241: =item * get_env_multiple($name) 
                   15242: 
                   15243: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   15244: values may be defined and end up as an array ref.
                   15245: 
                   15246: returns an array of values
                   15247: 
1.243     albertel 15248: =back
                   15249: 
                   15250: =head2 User Information
1.191     harris41 15251: 
1.243     albertel 15252: =over 4
1.191     harris41 15253: 
                   15254: =item *
1.394     bowersj2 15255: X<queryauthenticate()>
                   15256: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 15257: authentication scheme
                   15258: 
                   15259: =item *
1.394     bowersj2 15260: X<authenticate()>
1.1073    raeburn  15261: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 15262: authenticate user from domain's lib servers (first use the current
                   15263: one). C<$upass> should be the users password.
1.1073    raeburn  15264: $checkdefauth is optional (value is 1 if a check should be made to
                   15265:    authenticate user using default authentication method, and allow
                   15266:    account creation if username does not have account in the domain).
                   15267: $clientcancheckhost is optional (value is 1 if checking whether the
                   15268:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 15269: 
                   15270: =item *
1.394     bowersj2 15271: X<homeserver()>
                   15272: B<homeserver($uname,$udom)>: find the server which has
                   15273: the user's directory and files (there must be only one), this caches
                   15274: the answer, and also caches if there is a borken connection.
1.191     harris41 15275: 
                   15276: =item *
1.394     bowersj2 15277: X<idget()>
                   15278: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   15279: (IDs are a unique resource in a domain, there must be only 1 ID per
                   15280: username, and only 1 username per ID in a specific domain) (returns
                   15281: hash: id=>name,id=>name)
1.191     harris41 15282: 
                   15283: =item *
1.394     bowersj2 15284: X<idrget()>
                   15285: B<idrget($udom,@unames)>: find the IDs behind a list of
                   15286: usernames (returns hash: name=>id,name=>id)
1.191     harris41 15287: 
                   15288: =item *
1.394     bowersj2 15289: X<idput()>
                   15290: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 15291: 
                   15292: =item *
1.394     bowersj2 15293: X<rolesinit()>
1.1169    droeschl 15294: B<rolesinit($udom,$username)>: get user privileges.
                   15295: returns user role, first access and timer interval hashes
1.243     albertel 15296: 
                   15297: =item *
1.1171    droeschl 15298: X<privileged()>
                   15299: B<privileged($username,$domain)>: returns a true if user has a
                   15300: privileged and active role (i.e. su or dc), false otherwise.
                   15301: 
                   15302: =item *
1.551     albertel 15303: X<getsection()>
                   15304: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 15305: course $cname, return section name/number or '' for "not in course"
                   15306: and '-1' for "no section"
                   15307: 
                   15308: =item *
1.394     bowersj2 15309: X<userenvironment()>
                   15310: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 15311: passed in @what from the requested user's environment, returns a hash
                   15312: 
1.858     raeburn  15313: =item * 
                   15314: X<userlog_query()>
1.859     albertel 15315: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   15316: activity.log file. %filters defines filters applied when parsing the
                   15317: log file. These can be start or end timestamps, or the type of action
                   15318: - log to look for Login or Logout events, check for Checkin or
                   15319: Checkout, role for role selection. The response is in the form
                   15320: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   15321: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  15322: 
1.243     albertel 15323: =back
                   15324: 
                   15325: =head2 User Roles
                   15326: 
                   15327: =over 4
                   15328: 
                   15329: =item *
                   15330: 
1.1172.2.65  raeburn  15331: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   15332: returns codes for allowed actions.
                   15333: 
                   15334: The first argument is required, all others are optional.
                   15335: 
                   15336: $priv is the privilege being checked.
                   15337: $uri contains additional information about what is being checked for access (e.g.,
                   15338: URL, course ID etc.).
                   15339: $symb is the unique resource instance identifier in a course; if needed,
                   15340: but not provided, it will be retrieved via a call to &symbread().
                   15341: $role is the role for which a priv is being checked (only used if priv is evb).
                   15342: $clientip is the user's IP address (only used when checking for access to portfolio
                   15343: files).
                   15344: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   15345: prevents recursive calls to &allowed.
                   15346: 
1.243     albertel 15347:  F: full access
                   15348:  U,I,K: authentication modes (cxx only)
                   15349:  '': forbidden
                   15350:  1: user needs to choose course
                   15351:  2: browse allowed
1.766     albertel 15352:  A: passphrase authentication needed
1.1172.2.65  raeburn  15353:  B: access temporarily blocked because of a blocking event in a course.
1.1172.2.146.  .1(raebu 15354:22):  D: access blocked because access is required via session initiated via deep-link
1.243     albertel 15355: 
                   15356: =item *
                   15357: 
1.1172.2.13  raeburn  15358: constructaccess($url,$setpriv) : check for access to construction space URL
                   15359: 
                   15360: See if the owner domain and name in the URL match those in the
                   15361: expected environment.  If so, return three element list
                   15362: ($ownername,$ownerdomain,$ownerhome).
                   15363: 
                   15364: Otherwise return the null string.
                   15365: 
                   15366: If second argument 'setpriv' is true, it assigns the privileges,
                   15367: and returns the same three element list, unless the owner has
                   15368: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   15369: in which case the null string is returned.
                   15370: 
                   15371: =item *
                   15372: 
1.1172.2.84  raeburn  15373: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   15374: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   15375: for system, domain, and course level. $uname and $udom are optional (current
                   15376: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 15377: 
                   15378: =item *
                   15379: 
1.988     raeburn  15380: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   15381: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  15382: $type is Course (default) or Community.
1.988     raeburn  15383: If $forcedefault evaluates to true, text returned will be default 
                   15384: text for $type. Otherwise, if this is a course, the text returned 
                   15385: will be a custom name for the role (if defined in the course's 
                   15386: environment).  If no custom name is defined the default is returned.
                   15387:    
1.832     raeburn  15388: =item *
                   15389: 
1.1172.2.23  raeburn  15390: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  15391: All arguments are optional. Returns a hash of a roles, either for
                   15392: co-author/assistant author roles for a user's Construction Space
1.906     albertel 15393: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  15394: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   15395: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   15396: For each key, value is set to colon-separated start and end times for
                   15397: the role.  If no username and domain are specified, will default to
1.934     raeburn  15398: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  15399: of role statuses (active, future or previous), roles 
                   15400: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   15401: to restrict the list of roles reported. If no array ref is 
                   15402: provided for types, will default to return only active roles.
1.834     albertel 15403: 
1.1172.2.13  raeburn  15404: =item *
                   15405: 
                   15406: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   15407: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   15408: 
                   15409: Additional optional arguments are: $type (if role checking is to be restricted
                   15410: to certain user status types -- previous (expired roles), active (currently
                   15411: available roles) or future (roles available in the future), and
                   15412: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  15413: have active Domain Coordinator role in course's domain or in additional
                   15414: domains (specified in 'Domains to check for privileged users' in course
                   15415: environment -- set via:  Course Settings -> Classlists and staff listing).
                   15416: 
                   15417: =item *
                   15418: 
                   15419: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   15420: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   15421: $possdomains and $possroles are optional array refs -- to domains to check and
                   15422: roles to check.  If $possdomains is not specified, a dump will be done of the
                   15423: users' roles.db to check for a dc or su role in any domain. This can be
                   15424: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   15425: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   15426: this then allows &privileged_by_domain() to be used, which caches the identity
                   15427: of privileged users, eliminating the need for repeated calls to &dump().
                   15428: 
                   15429: =item *
                   15430: 
                   15431: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   15432: where the outer hash keys are domains specified in the $possdomains array ref,
                   15433: next inner hash keys are privileged roles specified in the $roles array ref,
                   15434: and the innermost hash contains key = value pairs for username:domain = end:start
                   15435: for active or future "privileged" users with that role in that domain. To avoid
                   15436: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   15437: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  15438: 
1.243     albertel 15439: =back
                   15440: 
                   15441: =head2 User Modification
                   15442: 
                   15443: =over 4
                   15444: 
                   15445: =item *
                   15446: 
1.957     raeburn  15447: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 15448: user for the level given by URL.  Optional start and end dates (leave empty
                   15449: string or zero for "no date")
1.191     harris41 15450: 
                   15451: =item *
                   15452: 
1.243     albertel 15453: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   15454: change a users, password, possible return values are: ok,
                   15455: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   15456: refused
1.191     harris41 15457: 
                   15458: =item *
                   15459: 
1.243     albertel 15460: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 15461: 
                   15462: =item *
                   15463: 
1.1058    raeburn  15464: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   15465:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   15466: 
                   15467: will update user information (firstname,middlename,lastname,generation,
                   15468: permanentemail), and if forceid is true, student/employee ID also.
                   15469: A user's institutional affiliation(s) can also be updated.
                   15470: User information fields will not be overwritten with empty entries 
                   15471: unless the field is included in the $candelete array reference.
                   15472: This array is included when a single user is modified via "Manage Users",
                   15473: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 15474: 
                   15475: =item *
                   15476: 
1.286     matthew  15477: modifystudent
                   15478: 
1.957     raeburn  15479: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  15480: The course id is resolved based on the current user's environment.  
                   15481: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  15482: associated with a course.
                   15483: 
1.297     matthew  15484: This call is essentially a wrapper for lonnet::modifyuser and
                   15485: lonnet::modify_student_enrollment
1.286     matthew  15486: 
                   15487: Inputs: 
                   15488: 
                   15489: =over 4
                   15490: 
1.957     raeburn  15491: =item B<$udom> Student's loncapa domain
1.286     matthew  15492: 
1.957     raeburn  15493: =item B<$uname> Student's loncapa login name
1.286     matthew  15494: 
1.964     bisitz   15495: =item B<$uid> Student/Employee ID
1.286     matthew  15496: 
1.957     raeburn  15497: =item B<$umode> Student's authentication mode
1.286     matthew  15498: 
1.957     raeburn  15499: =item B<$upass> Student's password
1.286     matthew  15500: 
1.957     raeburn  15501: =item B<$first> Student's first name
1.286     matthew  15502: 
1.957     raeburn  15503: =item B<$middle> Student's middle name
1.286     matthew  15504: 
1.957     raeburn  15505: =item B<$last> Student's last name
1.286     matthew  15506: 
1.957     raeburn  15507: =item B<$gene> Student's generation
1.286     matthew  15508: 
1.957     raeburn  15509: =item B<$usec> Student's section in course
1.286     matthew  15510: 
                   15511: =item B<$end> Unix time of the roles expiration
                   15512: 
                   15513: =item B<$start> Unix time of the roles start date
                   15514: 
                   15515: =item B<$forceid> If defined, allow $uid to be changed
                   15516: 
                   15517: =item B<$desiredhome> server to use as home server for student
                   15518: 
1.957     raeburn  15519: =item B<$email> Student's permanent e-mail address
                   15520: 
                   15521: =item B<$type> Type of enrollment (auto or manual)
                   15522: 
1.963     raeburn  15523: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   15524: 
                   15525: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  15526: 
1.963     raeburn  15527: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  15528: 
1.963     raeburn  15529: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  15530: 
1.1172.2.19  raeburn  15531: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   15532: 
                   15533: =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  15534: 
1.286     matthew  15535: =back
1.297     matthew  15536: 
                   15537: =item *
                   15538: 
                   15539: modify_student_enrollment
                   15540: 
1.1172.2.31  raeburn  15541: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  15542: 'role.request.course' must be defined for this function to proceed.
                   15543: 
                   15544: Inputs:
                   15545: 
                   15546: =over 4
                   15547: 
1.1172.2.31  raeburn  15548: =item $udom, student's domain
1.297     matthew  15549: 
1.1172.2.31  raeburn  15550: =item $uname, student's name
1.297     matthew  15551: 
1.1172.2.31  raeburn  15552: =item $uid, student's user id
1.297     matthew  15553: 
1.1172.2.31  raeburn  15554: =item $first, student's first name
1.297     matthew  15555: 
                   15556: =item $middle
                   15557: 
                   15558: =item $last
                   15559: 
                   15560: =item $gene
                   15561: 
                   15562: =item $usec
                   15563: 
                   15564: =item $end
                   15565: 
                   15566: =item $start
                   15567: 
1.957     raeburn  15568: =item $type
                   15569: 
                   15570: =item $locktype
                   15571: 
                   15572: =item $cid
                   15573: 
                   15574: =item $selfenroll
                   15575: 
                   15576: =item $context
                   15577: 
1.1172.2.19  raeburn  15578: =item $credits, number of credits student will earn from this class
                   15579: 
1.1172.2.76  raeburn  15580: =item $instsec, institutional course section code for student
                   15581: 
1.297     matthew  15582: =back
                   15583: 
1.191     harris41 15584: 
                   15585: =item *
                   15586: 
1.243     albertel 15587: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   15588: custom role; give a custom role to a user for the level given by URL.  Specify
                   15589: name and domain of role author, and role name
1.191     harris41 15590: 
                   15591: =item *
                   15592: 
1.243     albertel 15593: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 15594: 
                   15595: =item *
                   15596: 
1.243     albertel 15597: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   15598: 
                   15599: =back
                   15600: 
                   15601: =head2 Course Infomation
                   15602: 
                   15603: =over 4
1.191     harris41 15604: 
                   15605: =item *
                   15606: 
1.1118    foxr     15607: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 15608: specified course id, including all environment settings for the
                   15609: course, the description of the course will be in the hash under the
                   15610: key 'description'
1.191     harris41 15611: 
1.1118    foxr     15612: $options is an optional parameter that if supplied is a hash reference that controls
                   15613: what how this function works.  It has the following key/values:
                   15614: 
                   15615: =over 4
                   15616: 
                   15617: =item freshen_cache
                   15618: 
                   15619: If defined, and the environment cache for the course is valid, it is 
                   15620: returned in the returned hash.
                   15621: 
                   15622: =item one_time
                   15623: 
                   15624: If defined, the last cache time is set to _now_
                   15625: 
                   15626: =item user
                   15627: 
                   15628: If defined, the supplied username is used instead of the current user.
                   15629: 
                   15630: 
                   15631: =back
                   15632: 
1.191     harris41 15633: =item *
                   15634: 
1.624     albertel 15635: resdata($name,$domain,$type,@which) : request for current parameter
                   15636: setting for a specific $type, where $type is either 'course' or 'user',
                   15637: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  15638: answers for 10 minutes.
1.243     albertel 15639: 
1.877     foxr     15640: =item *
                   15641: 
                   15642: get_courseresdata($courseid, $domain) : dump the entire course resource
                   15643: data base, returning a hash that is keyed by the resource name and has
                   15644: values that are the resource value.  I believe that the timestamps and
                   15645: versions are also returned.
                   15646: 
1.1172.2.31  raeburn  15647: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   15648: supplemental content area. This routine caches the number of files for
                   15649: 10 minutes.
                   15650: 
1.243     albertel 15651: =back
                   15652: 
                   15653: =head2 Course Modification
                   15654: 
                   15655: =over 4
1.191     harris41 15656: 
                   15657: =item *
                   15658: 
1.243     albertel 15659: writecoursepref($courseid,%prefs) : write preferences (environment
                   15660: database) for a course
1.191     harris41 15661: 
                   15662: =item *
                   15663: 
1.1011    raeburn  15664: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   15665: 
                   15666: =item *
                   15667: 
1.1038    raeburn  15668: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 15669: 
1.1167    droeschl 15670: =item *
                   15671: 
                   15672: is_course($courseid), is_course($cdom, $cnum)
                   15673: 
                   15674: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   15675: two component version $cdom, $cnum. It checks if the specified course exists.
                   15676: 
                   15677: Returns:
                   15678:     undef if the course doesn't exist, otherwise
                   15679:     in scalar context the combined courseid.
                   15680:     in list context the two components of the course identifier, domain and 
                   15681:     courseid.    
                   15682: 
1.243     albertel 15683: =back
                   15684: 
1.1172.2.109  raeburn  15685: =head2 Bubblesheet Configuration
                   15686: 
                   15687: =over 4
                   15688: 
                   15689: =item *
                   15690: 
                   15691: get_scantron_config($which)
                   15692: 
                   15693: $which - the name of the configuration to parse from the file.
                   15694: 
                   15695: Parses and returns the bubblesheet configuration line selected as a
                   15696: hash of configuration file fields.
                   15697: 
                   15698: 
                   15699: Returns:
                   15700:     If the named configuration is not in the file, an empty
                   15701:     hash is returned.
                   15702: 
                   15703:     a hash with the fields
                   15704:       name         - internal name for the this configuration setup
                   15705:       description  - text to display to operator that describes this config
                   15706:       CODElocation - if 0 or the string 'none'
                   15707:                           - no CODE exists for this config
                   15708:                      if -1 || the string 'letter'
                   15709:                           - a CODE exists for this config and is
                   15710:                             a string of letters
                   15711:                      Unsupported value (but planned for future support)
                   15712:                           if a positive integer
                   15713:                                - The CODE exists as the first n items from
                   15714:                                  the question section of the form
                   15715:                           if the string 'number'
                   15716:                                - The CODE exists for this config and is
                   15717:                                  a string of numbers
                   15718:       CODEstart   - (only matter if a CODE exists) column in the line where
                   15719:                      the CODE starts
                   15720:       CODElength  - length of the CODE
                   15721:       IDstart     - column where the student/employee ID starts
                   15722:       IDlength    - length of the student/employee ID info
                   15723:       Qstart      - column where the information from the bubbled
                   15724:                     'questions' start
                   15725:       Qlength     - number of columns comprising a single bubble line from
                   15726:                     the sheet. (usually either 1 or 10)
                   15727:       Qon         - either a single character representing the character used
                   15728:                     to signal a bubble was chosen in the positional setup, or
                   15729:                     the string 'letter' if the letter of the chosen bubble is
                   15730:                     in the final, or 'number' if a number representing the
                   15731:                     chosen bubble is in the file (1->A 0->J)
                   15732:       Qoff        - the character used to represent that a bubble was
                   15733:                     left blank
                   15734:       PaperID     - if the scanning process generates a unique number for each
                   15735:                     sheet scanned the column that this ID number starts in
                   15736:       PaperIDlength - number of columns that comprise the unique ID number
                   15737:                       for the sheet of paper
                   15738:       FirstName   - column that the first name starts in
                   15739:       FirstNameLength - number of columns that the first name spans
                   15740:       LastName    - column that the last name starts in
                   15741:       LastNameLength - number of columns that the last name spans
                   15742:       BubblesPerRow - number of bubbles available in each row used to
                   15743:                       bubble an answer. (If not specified, 10 assumed).
                   15744: 
                   15745: 
                   15746: =item *
                   15747: 
                   15748: get_scantronformat_file($cdom)
                   15749: 
                   15750: $cdom - the course's domain (optional); if not supplied, uses
                   15751: domain for current $env{'request.course.id'}.
                   15752: 
                   15753: Returns an array containing lines from the scantron format file for
                   15754: the domain of the course.
                   15755: 
                   15756: If a url for a custom.tab file is listed in domain's configuration.db,
                   15757: lines are from this file.
                   15758: 
                   15759: Otherwise, if a default.tab has been published in RES space by the
                   15760: domainconfig user, lines are from this file.
                   15761: 
                   15762: Otherwise, fall back to getting lines from the legacy file on the
                   15763: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   15764: 
                   15765: =back
                   15766: 
1.243     albertel 15767: =head2 Resource Subroutines
                   15768: 
                   15769: =over 4
1.191     harris41 15770: 
                   15771: =item *
                   15772: 
1.243     albertel 15773: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 15774: 
                   15775: =item *
                   15776: 
1.243     albertel 15777: repcopy($filename) : subscribes to the requested file, and attempts to
                   15778: replicate from the owning library server, Might return
1.607     raeburn  15779: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   15780: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 15781: resource. Expects the local filesystem pathname
                   15782: (/home/httpd/html/res/....)
                   15783: 
                   15784: =back
                   15785: 
                   15786: =head2 Resource Information
                   15787: 
                   15788: =over 4
1.191     harris41 15789: 
                   15790: =item *
                   15791: 
1.1172.2.28  raeburn  15792: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   15793: and returns the value of a variety of different possible values,
                   15794: $varname should be a request string, and the other parameters can be
                   15795: used to specify who and what one is asking about. Ordinarily, $cid 
                   15796: does not need to be specified, as it is retrived from 
                   15797: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   15798: within lonuserstate::loadmap() when initializing a course, before
                   15799: $env{'request.course.id'} has been set, so it needs to be provided
                   15800: in that one case.
1.243     albertel 15801: 
                   15802: Possible values for $varname are environment.lastname (or other item
                   15803: from the envirnment hash), user.name (or someother aspect about the
                   15804: user), resource.0.maxtries (or some other part and parameter of a
                   15805: resource)
1.204     albertel 15806: 
                   15807: =item *
                   15808: 
1.243     albertel 15809: directcondval($number) : get current value of a condition; reads from a state
                   15810: string
1.204     albertel 15811: 
                   15812: =item *
                   15813: 
1.243     albertel 15814: condval($condidx) : value of condition index based on state
1.204     albertel 15815: 
                   15816: =item *
                   15817: 
1.243     albertel 15818: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   15819: resource's metadata, $what should be either a specific key, or either
                   15820: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   15821: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   15822: 
                   15823: this function automatically caches all requests
1.191     harris41 15824: 
                   15825: =item *
                   15826: 
1.243     albertel 15827: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15828: network of library servers; returns file handle of where SQL and regex results
                   15829: will be stored for query
1.191     harris41 15830: 
                   15831: =item *
                   15832: 
1.1172.2.66  raeburn  15833: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   15834: return symbolic list entry (all arguments optional).
                   15835: 
                   15836: Args: filename is the filename (including path) for the file for which a symb
                   15837: is required; donotrecurse, if true will prevent calls to allowed() being made
                   15838: to check access status if more than one resource was found in the bighash
                   15839: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   15840: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   15841: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15842: cause possible symbs to be checked to determine if they are subject to content
                   15843: blocking, if so they will not be included as possible symbs; possibles is a
                   15844: ref to a hash, which, as a side effect, will be populated with all possible
                   15845: symbs (content blocking not tested).
                   15846: 
1.243     albertel 15847: returns the data handle
1.191     harris41 15848: 
                   15849: =item *
                   15850: 
1.1172.2.17  raeburn  15851: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  15852: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15853: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  15854: on failure, user must be in a course, as it assumes the existence of
                   15855: the course initial hash, and uses $env('request.course.id'}.  The third
                   15856: arg is an optional reference to a scalar.  If this arg is passed in the
                   15857: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15858: encrypted; otherwise it will be null.
1.243     albertel 15859: 
1.191     harris41 15860: =item *
                   15861: 
1.243     albertel 15862: symbclean($symb) : removes versions numbers from a symb, returns the
                   15863: cleaned symb
1.191     harris41 15864: 
                   15865: =item *
                   15866: 
1.243     albertel 15867: is_on_map($uri) : checks if the $uri is somewhere on the current
                   15868: course map, user must be in a course for it to work.
1.191     harris41 15869: 
                   15870: =item *
                   15871: 
1.243     albertel 15872: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 15873: 
                   15874: =item *
                   15875: 
1.243     albertel 15876: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   15877: a random seed, all arguments are optional, if they aren't sent it uses the
                   15878: environment to derive them. Note: if symb isn't sent and it can't get one
                   15879: from &symbread it will use the current time as its return value
1.191     harris41 15880: 
                   15881: =item *
                   15882: 
1.243     albertel 15883: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   15884: unfakeable, receipt
1.191     harris41 15885: 
                   15886: =item *
                   15887: 
1.620     albertel 15888: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 15889: 
                   15890: =item *
                   15891: 
1.243     albertel 15892: countacc($url) : count the number of accesses to a given URL
1.191     harris41 15893: 
                   15894: =item *
                   15895: 
1.243     albertel 15896: 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 15897: 
                   15898: =item *
                   15899: 
1.243     albertel 15900: 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 15901: 
                   15902: =item *
                   15903: 
1.243     albertel 15904: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 15905: 
                   15906: =item *
                   15907: 
1.243     albertel 15908: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   15909: forcing spreadsheet to reevaluate the resource scores next time.
                   15910: 
1.1172.2.13  raeburn  15911: =item *
                   15912: 
                   15913: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   15914: when viewing in course context.
                   15915: 
                   15916:  input: six args -- filename (decluttered), course number, course domain,
                   15917:                     url, symb (if registered) and group (if this is a
                   15918:                     group item -- e.g., bulletin board, group page etc.).
                   15919: 
                   15920:  output: array of five scalars --
                   15921:          $cfile -- url for file editing if editable on current server
                   15922:          $home -- homeserver of resource (i.e., for author if published,
                   15923:                                           or course if uploaded.).
                   15924:          $switchserver --  1 if server switch will be needed.
                   15925:          $forceedit -- 1 if icon/link should be to go to edit mode
                   15926:          $forceview -- 1 if icon/link should be to go to view mode
                   15927: 
                   15928: =item *
                   15929: 
                   15930: is_course_upload($file,$cnum,$cdom)
                   15931: 
                   15932: Used in course context to determine if current file was uploaded to
                   15933: the course (i.e., would be found in /userfiles/docs on the course's
                   15934: homeserver.
                   15935: 
                   15936:   input: 3 args -- filename (decluttered), course number and course domain.
                   15937:   output: boolean -- 1 if file was uploaded.
                   15938: 
1.243     albertel 15939: =back
                   15940: 
                   15941: =head2 Storing/Retreiving Data
                   15942: 
                   15943: =over 4
1.191     harris41 15944: 
                   15945: =item *
                   15946: 
1.1172.2.64  raeburn  15947: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   15948: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15949: the remaining args aren't required and if they aren't passed or are '' they will
                   15950: be derived from the env (with the exception of $laststore, which is an
                   15951: optional arg used when a user's submission is stored in grading).
                   15952: $laststore is $version=$timestamp, where $version is the most recent version
                   15953: number retrieved for the corresponding $symb in the $namespace db file, and
                   15954: $timestamp is the timestamp for that transaction (UNIX time).
                   15955: $laststore is currently only passed when cstore() is called by
                   15956: structuretags::finalize_storage().
1.191     harris41 15957: 
                   15958: =item *
                   15959: 
1.1172.2.64  raeburn  15960: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   15961: but uses critical subroutine
1.191     harris41 15962: 
                   15963: =item *
                   15964: 
1.243     albertel 15965: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15966: all args are optional
1.191     harris41 15967: 
                   15968: =item *
                   15969: 
1.717     albertel 15970: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15971: dumps the complete (or key matching regexp) namespace into a hash
                   15972: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15973: normally &store()ed into
                   15974: 
                   15975: $range should be either an integer '100' (give me the first 100
                   15976:                                            matching records)
                   15977:               or be  two integers sperated by a - with no spaces
                   15978:                  '30-50' (give me the 30th through the 50th matching
                   15979:                           records)
                   15980: 
                   15981: 
                   15982: =item *
                   15983: 
1.1172.2.59  raeburn  15984: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15985: replaces a &store() version of data with a replacement set of data
                   15986: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  15987: reference. If $tolog is true, the transaction is logged in the courselog
                   15988: with an action=PUTSTORE.
1.717     albertel 15989: 
                   15990: =item *
                   15991: 
1.243     albertel 15992: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15993: works very similar to store/cstore, but all data is stored in a
                   15994: temporary location and can be reset using tmpreset, $storehash should
                   15995: be a hash reference, returns nothing on success
1.191     harris41 15996: 
                   15997: =item *
                   15998: 
1.243     albertel 15999: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   16000: similar to restore, but all data is stored in a temporary location and
                   16001: can be reset using tmpreset. Returns a hash of values on success,
                   16002: error string otherwise.
1.191     harris41 16003: 
                   16004: =item *
                   16005: 
1.243     albertel 16006: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   16007: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 16008: 
                   16009: =item *
                   16010: 
1.243     albertel 16011: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16012: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 16013: 
                   16014: =item *
                   16015: 
1.243     albertel 16016: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   16017: namesp ($udom and $uname are optional)
1.191     harris41 16018: 
                   16019: =item *
                   16020: 
1.702     albertel 16021: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 16022: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 16023: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  16024: 
1.702     albertel 16025: $range should be either an integer '100' (give me the first 100
                   16026:                                            matching records)
                   16027:               or be  two integers sperated by a - with no spaces
                   16028:                  '30-50' (give me the 30th through the 50th matching
                   16029:                           records)
1.449     matthew  16030: =item *
                   16031: 
                   16032: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   16033: $store can be a scalar, an array reference, or if the amount to be 
                   16034: incremented is > 1, a hash reference.
                   16035: 
                   16036: ($udom and $uname are optional)
1.191     harris41 16037: 
                   16038: =item *
                   16039: 
1.243     albertel 16040: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   16041: ($udom and $uname are optional)
1.191     harris41 16042: 
                   16043: =item *
                   16044: 
1.243     albertel 16045: cput($namespace,$storehash,$udom,$uname) : critical put
                   16046: ($udom and $uname are optional)
1.191     harris41 16047: 
                   16048: =item *
                   16049: 
1.748     albertel 16050: newput($namespace,$storehash,$udom,$uname) :
                   16051: 
                   16052: Attempts to store the items in the $storehash, but only if they don't
                   16053: currently exist, if this succeeds you can be certain that you have 
                   16054: successfully created a new key value pair in the $namespace db.
                   16055: 
                   16056: 
                   16057: Args:
                   16058:  $namespace: name of database to store values to
                   16059:  $storehash: hashref to store to the db
                   16060:  $udom: (optional) domain of user containing the db
                   16061:  $uname: (optional) name of user caontaining the db
                   16062: 
                   16063: Returns:
                   16064:  'ok' -> succeeded in storing all keys of $storehash
                   16065:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   16066:                         least <key> already existed in the db (other
                   16067:                         requested keys may also already exist)
1.967     bisitz   16068:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 16069:  'con_lost' -> unable to contact request server
                   16070:  'refused' -> action was not allowed by remote machine
                   16071: 
                   16072: 
                   16073: =item *
                   16074: 
1.243     albertel 16075: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16076: reference filled in from namesp (encrypts the return communication)
                   16077: ($udom and $uname are optional)
1.191     harris41 16078: 
                   16079: =item *
                   16080: 
1.243     albertel 16081: log($udom,$name,$home,$message) : write to permanent log for user; use
                   16082: critical subroutine
                   16083: 
1.806     raeburn  16084: =item *
                   16085: 
1.860     raeburn  16086: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   16087: array reference filled in from namespace found in domain level on either
                   16088: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  16089: 
                   16090: =item *
                   16091: 
1.860     raeburn  16092: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   16093: domain level either on specified domain server ($uhome) or primary domain 
                   16094: server ($udom and $uhome are optional)
1.806     raeburn  16095: 
1.943     raeburn  16096: =item * 
                   16097: 
1.1172.2.35  raeburn  16098: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   16099: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   16100: the target domain.
                   16101: 
                   16102: May also include additional key => value pairs for the following groups:
                   16103: 
                   16104: =over
                   16105: 
                   16106: =item
                   16107: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   16108: 
                   16109: =over
                   16110: 
                   16111: =item defaultquota, authorquota
                   16112: 
                   16113: =back
                   16114: 
                   16115: =item
                   16116: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   16117: portfolio for users).
                   16118: 
                   16119: =over
                   16120: 
                   16121: =item
                   16122: aboutme, blog, webdav, portfolio
                   16123: 
                   16124: =back
                   16125: 
                   16126: =item
                   16127: requestcourses: ability to request courses, and how requests are processed.
                   16128: 
                   16129: =over
                   16130: 
                   16131: =item
1.1172.2.37  raeburn  16132: official, unofficial, community, textbook
1.1172.2.35  raeburn  16133: 
                   16134: =back
                   16135: 
                   16136: =item
                   16137: inststatus: types of institutional affiliation, and order in which they are displayed.
                   16138: 
                   16139: =over
                   16140: 
                   16141: =item
1.1172.2.44  raeburn  16142: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  16143: 
                   16144: =back
                   16145: 
                   16146: =item
                   16147: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   16148: for course's uploaded content.
                   16149: 
                   16150: =over
                   16151: 
                   16152: =item
1.1172.2.68  raeburn  16153: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   16154: communityquota, textbookquota
1.1172.2.35  raeburn  16155: 
                   16156: =back
                   16157: 
                   16158: =item
                   16159: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   16160: on your servers.
                   16161: 
                   16162: =over
                   16163: 
                   16164: =item
                   16165: remotesessions, hostedsessions
                   16166: 
                   16167: =back
                   16168: 
                   16169: =back
                   16170: 
                   16171: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   16172: utility to create a configuration.db file on a domain's primary library server
                   16173: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   16174: -- corresponding values are authentication type (internal, krb4, krb5,
                   16175: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   16176: will be available. Values are retrieved from cache (if current), unless the
                   16177: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   16178: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   16179: 
                   16180: Typical usage:
1.943     raeburn  16181: 
1.1172.2.35  raeburn  16182: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  16183: 
1.243     albertel 16184: =back
                   16185: 
                   16186: =head2 Network Status Functions
                   16187: 
                   16188: =over 4
1.191     harris41 16189: 
                   16190: =item *
                   16191: 
1.1137    raeburn  16192: dirlist() : return directory list based on URI (first arg).
                   16193: 
                   16194: Inputs: 1 required, 5 optional.
                   16195: 
                   16196: =over
                   16197: 
                   16198: =item 
                   16199: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   16200: 
                   16201: =item
                   16202: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   16203: 
                   16204: =item
                   16205: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   16206: 
                   16207: =item
                   16208: $getpropath - boolean: 1 if prepend path using &propath(). 
                   16209: 
                   16210: =item
                   16211: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   16212: 
                   16213: =item 
                   16214: $alternateRoot - path to prepend in place of path from $uri.
                   16215: 
                   16216: =back
                   16217: 
                   16218: Returns: Array of up to two items.
                   16219: 
                   16220: =over
                   16221: 
                   16222: a reference to an array of files/subdirectories
                   16223: 
                   16224: =over
                   16225: 
                   16226: Each element in the array of files/subdirectories is a & separated list of
                   16227: item name and the result of running stat on the item.  If dirlist was requested
                   16228: for a file instead of a directory, the item name will be ''. For a directory 
                   16229: listing, if the item is a metadata file, the element will end &N&M 
                   16230: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   16231: default copyright set (1).  
                   16232: 
                   16233: =back
                   16234: 
                   16235: a scalar containing error condition (if encountered).
                   16236: 
                   16237: =over
                   16238: 
                   16239: =item 
                   16240: no_host (no homeserver identified for $username:$domain).
                   16241: 
                   16242: =item 
                   16243: no_such_host (server contacted for listing not identified as valid host).
                   16244: 
                   16245: =item 
                   16246: con_lost (connection to remote server failed).
                   16247: 
                   16248: =item 
                   16249: refused (invalid $username:$domain received on lond side).
                   16250: 
                   16251: =item 
                   16252: no_such_dir (directory at specified path on lond side does not exist). 
                   16253: 
                   16254: =item 
                   16255: empty (directory at specified path on lond side is empty).
                   16256: 
                   16257: =over
                   16258: 
                   16259: This is currently not encountered because the &ls3, &ls2, 
                   16260: &ls (_handler) routines on the lond side do not filter out
                   16261: . and .. from a directory listing. 
                   16262: 
                   16263: =back
                   16264: 
                   16265: =back
                   16266: 
                   16267: =back
1.191     harris41 16268: 
                   16269: =item *
                   16270: 
1.243     albertel 16271: spareserver() : find server with least workload from spare.tab
                   16272: 
1.986     foxr     16273: 
                   16274: =item *
                   16275: 
                   16276: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   16277: if there is no corresponding loncapa host.
                   16278: 
1.243     albertel 16279: =back
                   16280: 
1.986     foxr     16281: 
1.243     albertel 16282: =head2 Apache Request
                   16283: 
                   16284: =over 4
1.191     harris41 16285: 
                   16286: =item *
                   16287: 
1.243     albertel 16288: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   16289: localhost, posts hash
                   16290: 
                   16291: =back
                   16292: 
                   16293: =head2 Data to String to Data
                   16294: 
                   16295: =over 4
1.191     harris41 16296: 
                   16297: =item *
                   16298: 
1.243     albertel 16299: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   16300: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 16301: 
                   16302: =item *
                   16303: 
1.243     albertel 16304: hashref2str($hashref) : convert a hashref into a string complete with
                   16305: escaping and '=' and '&' separators, supports elements that are
                   16306: arrayrefs and hashrefs
1.191     harris41 16307: 
                   16308: =item *
                   16309: 
1.243     albertel 16310: arrayref2str($arrayref) : convert an arrayref into a string complete
                   16311: with escaping and '&' separators, supports elements that are arrayrefs
                   16312: and hashrefs
1.191     harris41 16313: 
                   16314: =item *
                   16315: 
1.243     albertel 16316: str2hash($string) : convert string to hash using unescaping and
                   16317: splitting on '=' and '&', supports elements that are arrayrefs and
                   16318: hashrefs
1.191     harris41 16319: 
                   16320: =item *
                   16321: 
1.243     albertel 16322: str2array($string) : convert string to hash using unescaping and
                   16323: splitting on '&', supports elements that are arrayrefs and hashrefs
                   16324: 
                   16325: =back
                   16326: 
                   16327: =head2 Logging Routines
                   16328: 
                   16329: 
                   16330: These routines allow one to make log messages in the lonnet.log and
                   16331: lonnet.perm logfiles.
1.191     harris41 16332: 
1.1119    foxr     16333: =over 4
                   16334: 
1.191     harris41 16335: =item *
                   16336: 
1.243     albertel 16337: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 16338: 
                   16339: =item *
                   16340: 
1.243     albertel 16341: logthis() : append message to the normal lonnet.log file, it gets
                   16342: preiodically rolled over and deleted.
1.191     harris41 16343: 
                   16344: =item *
                   16345: 
1.243     albertel 16346: logperm() : append a permanent message to lonnet.perm.log, this log
                   16347: file never gets deleted by any automated portion of the system, only
                   16348: messages of critical importance should go in here.
                   16349: 
1.1119    foxr     16350: 
1.243     albertel 16351: =back
                   16352: 
                   16353: =head2 General File Helper Routines
                   16354: 
                   16355: =over 4
1.191     harris41 16356: 
                   16357: =item *
                   16358: 
1.481     raeburn  16359: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   16360: (a) files in /uploaded
                   16361:   (i) If a local copy of the file exists - 
                   16362:       compares modification date of local copy with last-modified date for 
                   16363:       definitive version stored on home server for course. If local copy is 
                   16364:       stale, requests a new version from the home server and stores it. 
                   16365:       If the original has been removed from the home server, then local copy 
                   16366:       is unlinked.
                   16367:   (ii) If local copy does not exist -
                   16368:       requests the file from the home server and stores it. 
                   16369:   
                   16370:   If $caller is 'uploadrep':  
                   16371:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   16372:     for request for files originally uploaded via DOCS. 
                   16373:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   16374:   
                   16375:   Otherwise:
                   16376:      This indicates a call from the content generation phase of the request.
                   16377:      -  returns the entire contents of the file or -1.
                   16378:      
                   16379: (b) files in /res
                   16380:    - returns the entire contents of a file or -1; 
                   16381:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 16382: 
1.712     albertel 16383: 
                   16384: =item *
                   16385: 
                   16386: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   16387:                   reference
                   16388: 
                   16389: returns either a stat() list of data about the file or an empty list
                   16390: if the file doesn't exist or couldn't find out about it (connection
                   16391: problems or user unknown)
                   16392: 
1.191     harris41 16393: =item *
                   16394: 
1.243     albertel 16395: filelocation($dir,$file) : returns file system location of a file
                   16396: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   16397: directory that relative $file lookups are to looked in ($dir of /a/dir
                   16398: and a file of ../bob will become /a/bob)
1.191     harris41 16399: 
                   16400: =item *
                   16401: 
                   16402: hreflocation($dir,$file) : returns file system location or a URL; same as
                   16403: filelocation except for hrefs
                   16404: 
                   16405: =item *
                   16406: 
1.1172.2.49  raeburn  16407: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   16408: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 16409: 
1.243     albertel 16410: =back
                   16411: 
1.608     albertel 16412: =head2 Usererfile file routines (/uploaded*)
                   16413: 
                   16414: =over 4
                   16415: 
                   16416: =item *
                   16417: 
                   16418: userfileupload(): main rotine for putting a file in a user or course's
                   16419:                   filespace, arguments are,
                   16420: 
1.620     albertel 16421:  formname - required - this is the name of the element in $env where the
1.608     albertel 16422:            filename, and the contents of the file to create/modifed exist
1.620     albertel 16423:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   16424:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  16425:  context - if coursedoc, store the file in the course of the active role
                   16426:              of the current user; 
                   16427:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   16428:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 16429:  subdir - required - subdirectory to put the file in under ../userfiles/
                   16430:          if undefined, it will be placed in "unknown"
                   16431: 
                   16432:  (This routine calls clean_filename() to remove any dangerous
                   16433:  characters from the filename, and then calls finuserfileupload() to
                   16434:  complete the transaction)
                   16435: 
                   16436:  returns either the url of the uploaded file (/uploaded/....) if successful
                   16437:  and /adm/notfound.html if unsuccessful
                   16438: 
                   16439: =item *
                   16440: 
                   16441: clean_filename(): routine for cleaing a filename up for storage in
                   16442:                  userfile space, argument is:
                   16443: 
                   16444:  filename - proposed filename
                   16445: 
                   16446: returns: the new clean filename
                   16447: 
                   16448: =item *
                   16449: 
1.1090    raeburn  16450: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 16451: userspace, probably shouldn't be called directly
                   16452: 
                   16453:   docuname: username or courseid of destination for the file
                   16454:   docudom: domain of user/course of destination for the file
                   16455:   formname: same as for userfileupload()
1.1090    raeburn  16456:   fname: filename (including subdirectories) for the file
                   16457:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  16458:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  16459:   allfiles: reference to hash used to store objects found by parser
                   16460:   codebase: reference to hash used for codebases of java objects found by parser
                   16461:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   16462:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   16463:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   16464:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   16465:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   16466:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  16467:   mimetype: reference to scalar to accommodate mime type determined
                   16468:             from File::MMagic if $parser = parse.
1.608     albertel 16469: 
                   16470:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  16471:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   16472:  was 'overwrite').
                   16473:  
1.608     albertel 16474: 
                   16475: =item *
                   16476: 
                   16477: renameuserfile(): renames an existing userfile to a new name
                   16478: 
                   16479:   Args:
                   16480:    docuname: username or courseid of destination for the file
                   16481:    docudom: domain of user/course of destination for the file
                   16482:    old: current file name (including any subdirs under userfiles)
                   16483:    new: desired file name (including any subdirs under userfiles)
                   16484: 
                   16485: =item *
                   16486: 
                   16487: mkdiruserfile(): creates a directory is a userfiles dir
                   16488: 
                   16489:   Args:
                   16490:    docuname: username or courseid of destination for the file
                   16491:    docudom: domain of user/course of destination for the file
                   16492:    dir: dir to create (including any subdirs under userfiles)
                   16493: 
                   16494: =item *
                   16495: 
                   16496: removeuserfile(): removes a file that exists in userfiles
                   16497: 
                   16498:   Args:
                   16499:    docuname: username or courseid of destination for the file
                   16500:    docudom: domain of user/course of destination for the file
                   16501:    fname: filname to delete (including any subdirs under userfiles)
                   16502: 
                   16503: =item *
                   16504: 
                   16505: removeuploadedurl(): convience function for removeuserfile()
                   16506: 
                   16507:   Args:
                   16508:    url:  a full /uploaded/... url to delete
                   16509: 
1.747     albertel 16510: =item * 
                   16511: 
                   16512: get_portfile_permissions():
                   16513:   Args:
                   16514:     domain: domain of user or course contain the portfolio files
                   16515:     user: name of user or num of course contain the portfolio files
                   16516:   Returns:
                   16517:     hashref of a dump of the proper file_permissions.db
                   16518:    
                   16519: 
                   16520: =item * 
                   16521: 
                   16522: get_access_controls():
                   16523: 
                   16524: Args:
                   16525:   current_permissions: the hash ref returned from get_portfile_permissions()
                   16526:   group: (optional) the group you want the files associated with
                   16527:   file: (optional) the file you want access info on
                   16528: 
                   16529: Returns:
1.749     raeburn  16530:     a hash (keys are file names) of hashes containing
                   16531:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   16532:         values are XML containing access control settings (see below) 
1.747     albertel 16533: 
                   16534: Internal notes:
                   16535: 
1.749     raeburn  16536:  access controls are stored in file_permissions.db as key=value pairs.
                   16537:     key -> path to file/file_name\0uniqueID:scope_end_start
                   16538:         where scope -> public,guest,course,group,domains or users.
                   16539:               end -> UNIX time for end of access (0 -> no end date)
                   16540:               start -> UNIX time for start of access
                   16541: 
                   16542:     value -> XML description of access control
                   16543:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   16544:             <start></start>
                   16545:             <end></end>
                   16546: 
                   16547:             <password></password>  for scope type = guest
                   16548: 
                   16549:             <domain></domain>     for scope type = course or group
                   16550:             <number></number>
                   16551:             <roles id="">
                   16552:              <role></role>
                   16553:              <access></access>
                   16554:              <section></section>
                   16555:              <group></group>
                   16556:             </roles>
                   16557: 
                   16558:             <dom></dom>         for scope type = domains
                   16559: 
                   16560:             <users>             for scope type = users
                   16561:              <user>
                   16562:               <uname></uname>
                   16563:               <udom></udom>
                   16564:              </user>
                   16565:             </users>
                   16566:            </scope> 
                   16567:               
                   16568:  Access data is also aggregated for each file in an additional key=value pair:
                   16569:  key -> path to file/file_name\0accesscontrol 
                   16570:  value -> reference to hash
                   16571:           hash contains key = value pairs
                   16572:           where key = uniqueID:scope_end_start
                   16573:                 value = UNIX time record was last updated
                   16574: 
                   16575:           Used to improve speed of look-ups of access controls for each file.  
                   16576:  
                   16577:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   16578: 
1.1172.2.13  raeburn  16579: =item *
                   16580: 
1.749     raeburn  16581: modify_access_controls():
                   16582: 
                   16583: Modifies access controls for a portfolio file
                   16584: Args
                   16585: 1. file name
                   16586: 2. reference to hash of required changes,
                   16587: 3. domain
                   16588: 4. username
                   16589:   where domain,username are the domain of the portfolio owner 
                   16590:   (either a user or a course) 
                   16591: 
                   16592: Returns:
                   16593: 1. result of additions or updates ('ok' or 'error', with error message). 
                   16594: 2. result of deletions ('ok' or 'error', with error message).
                   16595: 3. reference to hash of any new or updated access controls.
                   16596: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   16597:    key = integer (inbound ID)
1.1172.2.13  raeburn  16598:    value = uniqueID
                   16599: 
                   16600: =item *
                   16601: 
                   16602: get_timebased_id():
                   16603: 
                   16604: Attempts to get a unique timestamp-based suffix for use with items added to a
                   16605: course via the Course Editor (e.g., folders, composite pages,
                   16606: group bulletin boards).
                   16607: 
                   16608: Args: (first three required; six others optional)
                   16609: 
                   16610: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   16611:    docssequence, or name of group
                   16612: 
                   16613: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   16614:    e.g., num, boardids
                   16615: 
                   16616: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   16617:    file will be named nohist_namespace.db
                   16618: 
                   16619: 4. cdom: domain of course; default is current course domain from %env
                   16620: 
                   16621: 5. cnum: course number; default is current course number from %env
                   16622: 
                   16623: 6. idtype: set to concat if an additional digit is to be appended to the
                   16624:    unix timestamp to form the suffix, if the plain timestamp is already
                   16625:    in use.  Default is to not do this, but simply increment the unix
                   16626:    timestamp by 1 until a unique key is obtained.
                   16627: 
                   16628: 7. who: holder of locking key; defaults to user:domain for user.
                   16629: 
                   16630: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   16631:    retrying); default is 3.
                   16632: 
                   16633: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   16634: 
                   16635: Returns:
                   16636: 
                   16637: 1. suffix obtained (numeric)
                   16638: 
                   16639: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   16640: 
                   16641: 3. error: contains (localized) error message if an error occurred.
                   16642: 
1.747     albertel 16643: 
1.608     albertel 16644: =back
                   16645: 
1.243     albertel 16646: =head2 HTTP Helper Routines
                   16647: 
                   16648: =over 4
                   16649: 
1.191     harris41 16650: =item *
                   16651: 
                   16652: escape() : unpack non-word characters into CGI-compatible hex codes
                   16653: 
                   16654: =item *
                   16655: 
                   16656: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   16657: 
1.243     albertel 16658: =back
                   16659: 
                   16660: =head1 PRIVATE SUBROUTINES
                   16661: 
                   16662: =head2 Underlying communication routines (Shouldn't call)
                   16663: 
                   16664: =over 4
                   16665: 
                   16666: =item *
                   16667: 
                   16668: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   16669: 
                   16670: =item *
                   16671: 
                   16672: reply() : uses subreply to send a message to remote machine, logs all failures
                   16673: 
                   16674: =item *
                   16675: 
                   16676: critical() : passes a critical message to another server; if cannot
                   16677: get through then place message in connection buffer directory and
                   16678: returns con_delayed, if incapable of saving message, returns
                   16679: con_failed
                   16680: 
                   16681: =item *
                   16682: 
                   16683: reconlonc() : tries to reconnect lonc client processes.
                   16684: 
                   16685: =back
                   16686: 
                   16687: =head2 Resource Access Logging
                   16688: 
                   16689: =over 4
                   16690: 
                   16691: =item *
                   16692: 
                   16693: flushcourselogs() : flush (save) buffer logs and access logs
                   16694: 
                   16695: =item *
                   16696: 
                   16697: courselog($what) : save message for course in hash
                   16698: 
                   16699: =item *
                   16700: 
                   16701: courseacclog($what) : save message for course using &courselog().  Perform
                   16702: special processing for specific resource types (problems, exams, quizzes, etc).
                   16703: 
1.191     harris41 16704: =item *
                   16705: 
                   16706: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   16707: as a PerlChildExitHandler
1.243     albertel 16708: 
                   16709: =back
                   16710: 
                   16711: =head2 Other
                   16712: 
                   16713: =over 4
                   16714: 
                   16715: =item *
                   16716: 
                   16717: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 16718: 
                   16719: =back
                   16720: 
                   16721: =cut
1.877     foxr     16722: 

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