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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.146.  .12(raeb    4:-23): # $Id: lonnet.pm,v 1.1172.2.146.2.11 2023/01/22 17:39:48 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);
1.1172.2.146.  .5(raebu 1257:22):     if ((!$uhome) || ($uhome eq 'no_host')) {
1.456     albertel 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");
1.1172.2.146.  .5(raebu 1306:22): 	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.1172.2.146.  .6(raebu 1312:22): sub can_switchserver {
                   1313:22):     my ($udom,$home) = @_;
                   1314:22):     my ($canswitch,@intdoms);
                   1315:22):     my $internet_names = &get_internet_names($home);
                   1316:22):     if (ref($internet_names) eq 'ARRAY') {
                   1317:22):         @intdoms = @{$internet_names};
                   1318:22):     }
                   1319:22):     my $uint_dom = &internet_dom(&domain($udom,'primary'));
                   1320:22):     if ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1321:22):         $canswitch = 1;
                   1322:22):     } else {
                   1323:22):          my $serverhomeID = &get_server_homeID(&hostname($home));
                   1324:22):          my $serverhomedom = &host_domain($serverhomeID);
                   1325:22):          my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1326:22):          my %udomdefaults = &get_domain_defaults($udom);
                   1327:22):          my $remoterev = &get_server_loncaparev('',$home);
                   1328:22):          $canswitch = &can_host_session($udom,$home,$remoterev,
                   1329:22):                                         $udomdefaults{'remotesessions'},
                   1330:22):                                         $defdomdefaults{'hostedsessions'});
                   1331:22):     }
                   1332:22):     return $canswitch;
                   1333:22): }
                   1334:22): 
1.1073    raeburn  1335: sub can_host_session {
1.1074    raeburn  1336:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1337:     my $canhost = 1;
1.1074    raeburn  1338:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1339:     if (ref($remotesessions) eq 'HASH') {
                   1340:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1341:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1342:                 $canhost = 0;
                   1343:             } else {
                   1344:                 $canhost = 1;
                   1345:             }
                   1346:         }
                   1347:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1348:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1349:                 $canhost = 1;
                   1350:             } else {
                   1351:                 $canhost = 0;
                   1352:             }
                   1353:         }
                   1354:         if ($canhost) {
                   1355:             if ($remotesessions->{'version'} ne '') {
                   1356:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1357:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1358:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1359:                         my $major = $1;
                   1360:                         my $minor = $2;
                   1361:                         if (($major < $reqmajor ) ||
                   1362:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1363:                             $canhost = 0;
                   1364:                         }
                   1365:                     } else {
                   1366:                         $canhost = 0;
                   1367:                     }
                   1368:                 }
                   1369:             }
                   1370:         }
                   1371:     }
                   1372:     if ($canhost) {
                   1373:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1374:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1375:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1376:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1377:                 if (($uint_dom ne '') && 
                   1378:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1379:                     $canhost = 0;
                   1380:                 } else {
                   1381:                     $canhost = 1;
                   1382:                 }
                   1383:             }
                   1384:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1385:                 if (($uint_dom ne '') && 
                   1386:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1387:                     $canhost = 1;
                   1388:                 } else {
                   1389:                     $canhost = 0;
                   1390:                 }
                   1391:             }
                   1392:         }
                   1393:     }
                   1394:     return $canhost;
                   1395: }
                   1396: 
1.1083    raeburn  1397: sub spare_can_host {
                   1398:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1399:     my $canhost=1;
1.1172.2.62  raeburn  1400:     my $try_server_hostname = &hostname($try_server);
                   1401:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1402:     my $serverhomedom = &host_domain($serverhomeID);
                   1403:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1404:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1405:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1406:             $canhost = 0;
                   1407:         }
                   1408:     }
1.1172.2.136  raeburn  1409:     if ($canhost) {
                   1410:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
                   1411:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
                   1412:                 unless (&shared_institution($udom,$try_server)) {
                   1413:                     $canhost = 0;
                   1414:                 }
                   1415:             }
                   1416:         }
                   1417:     }
1.1172.2.62  raeburn  1418:     if (($canhost) && ($uint_dom)) {
                   1419:         my @intdoms;
                   1420:         my $internet_names = &get_internet_names($try_server);
                   1421:         if (ref($internet_names) eq 'ARRAY') {
                   1422:             @intdoms = @{$internet_names};
                   1423:         }
                   1424:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1425:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1426:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1427:                                          $remotesessions,
                   1428:                                          $defdomdefaults{'hostedsessions'});
                   1429:         }
1.1083    raeburn  1430:     }
                   1431:     return $canhost;
                   1432: }
                   1433: 
1.1123    raeburn  1434: sub this_host_spares {
                   1435:     my ($dom) = @_;
1.1126    raeburn  1436:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1437:     my @hosts = &current_machine_ids();
                   1438:     foreach my $lonhost (@hosts) {
                   1439:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1440:             $dom_in_use = $dom;
                   1441:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1442:             last;
                   1443:         }
                   1444:     }
1.1126    raeburn  1445:     if ($dom_in_use ne '') {
                   1446:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1447:     }
                   1448:     if (ref($result) ne 'HASH') {
                   1449:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1450:         $dom_in_use = &host_domain($lonhost_in_use);
                   1451:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1452:         if (ref($result) ne 'HASH') {
                   1453:             $result = \%spareid;
                   1454:         }
                   1455:     }
                   1456:     return $result;
                   1457: }
                   1458: 
                   1459: sub spares_for_offload  {
                   1460:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1461:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1462:     if (defined($cached)) {
                   1463:         return $result;
                   1464:     } else {
1.1126    raeburn  1465:         my $cachetime = 60*60*24;
                   1466:         my %domconfig =
                   1467:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1468:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1469:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1470:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1471:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1472:                 }
                   1473:             }
                   1474:         }
                   1475:     }
1.1126    raeburn  1476:     return;
1.1123    raeburn  1477: }
                   1478: 
1.1129    raeburn  1479: sub get_lonbalancer_config {
                   1480:     my ($servers) = @_;
                   1481:     my ($currbalancer,$currtargets);
                   1482:     if (ref($servers) eq 'HASH') {
                   1483:         foreach my $server (keys(%{$servers})) {
                   1484:             my %what = (
                   1485:                          spareid => 1,
                   1486:                          perlvar => 1,
                   1487:                        );
                   1488:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1489:             if ($result eq 'ok') {
                   1490:                 if (ref($returnhash) eq 'HASH') {
                   1491:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1492:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1493:                             $currbalancer = $server;
                   1494:                             $currtargets = {};
                   1495:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1496:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1497:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1498:                                 }
                   1499:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1500:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1501:                                 }
                   1502:                             }
                   1503:                             last;
                   1504:                         }
                   1505:                     }
                   1506:                 }
                   1507:             }
                   1508:         }
                   1509:     }
                   1510:     return ($currbalancer,$currtargets);
                   1511: }
                   1512: 
                   1513: sub check_loadbalancing {
1.1172.2.88  raeburn  1514:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1515:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107  raeburn  1516:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129    raeburn  1517:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1518:     my @hosts = &current_machine_ids();
1.1129    raeburn  1519:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1520:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1521:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1522:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1523:     my $domneedscache; 
1.1129    raeburn  1524:     my $cachetime = 60*60*24;
                   1525: 
                   1526:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1527:         $dom_in_use = $udom;
                   1528:         $homeintdom = 1;
                   1529:     } else {
                   1530:         $dom_in_use = $serverhomedom;
                   1531:     }
                   1532:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1533:     unless (defined($cached)) {
                   1534:         my %domconfig =
                   1535:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1536:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1537:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1538:         } else {
                   1539:             $domneedscache = $dom_in_use;
1.1129    raeburn  1540:         }
                   1541:     }
                   1542:     if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1543:         ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1544:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1545:         if ($is_balancer) {
                   1546:             if (ref($currrules) eq 'HASH') {
                   1547:                 if ($homeintdom) {
                   1548:                     if ($uname ne '') {
                   1549:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1550:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1551:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1552:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1553:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1554:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1555:                             }
                   1556:                         }
                   1557:                         if ($rule_in_effect eq '') {
                   1558:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1559:                             if ($userenv{'inststatus'} ne '') {
                   1560:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1561:                                 my ($othertitle,$usertypes,$types) =
                   1562:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1563:                                 if (ref($types) eq 'ARRAY') {
                   1564:                                     foreach my $type (@{$types}) {
                   1565:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1566:                                             if (exists($currrules->{$type})) {
                   1567:                                                 $rule_in_effect = $currrules->{$type};
                   1568:                                             }
                   1569:                                         }
                   1570:                                     }
                   1571:                                 }
                   1572:                             } else {
                   1573:                                 if (exists($currrules->{'default'})) {
                   1574:                                     $rule_in_effect = $currrules->{'default'};
                   1575:                                 }
                   1576:                             }
                   1577:                         }
                   1578:                     } else {
                   1579:                         if (exists($currrules->{'default'})) {
                   1580:                             $rule_in_effect = $currrules->{'default'};
                   1581:                         }
                   1582:                     }
                   1583:                 } else {
                   1584:                     if ($currrules->{'_LC_external'} ne '') {
                   1585:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1586:                     }
                   1587:                 }
                   1588:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1589:                                                        $uname,$udom);
                   1590:             }
                   1591:         }
                   1592:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1593:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1594:         unless (defined($cached)) {
                   1595:             my %domconfig =
                   1596:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1597:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1598:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1599:             } else {
                   1600:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1601:             }
                   1602:         }
                   1603:         if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1604:             ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1605:                 &check_balancer_result($result,@hosts);
                   1606:             if ($is_balancer) {
1.1129    raeburn  1607:                 if (ref($currrules) eq 'HASH') {
                   1608:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1609:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1610:                     }
                   1611:                 }
                   1612:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1613:                                                        $uname,$udom);
                   1614:             }
                   1615:         } else {
                   1616:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1617:                 $is_balancer = 1;
                   1618:                 $offloadto = &this_host_spares($dom_in_use);
                   1619:             }
1.1172.2.75  raeburn  1620:             unless (defined($cached)) {
                   1621:                 $domneedscache = $serverhomedom;
                   1622:             }
1.1129    raeburn  1623:         }
                   1624:     } else {
                   1625:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1626:             $is_balancer = 1;
                   1627:             $offloadto = &this_host_spares($dom_in_use);
                   1628:         }
1.1172.2.75  raeburn  1629:         unless (defined($cached)) {
                   1630:             $domneedscache = $serverhomedom;
                   1631:         }
                   1632:     }
                   1633:     if ($domneedscache) {
                   1634:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1635:     }
1.1172.2.130  raeburn  1636:     if (($is_balancer) && ($caller ne 'switchserver')) {
1.1172.2.5  raeburn  1637:         my $lowest_load = 30000;
                   1638:         if (ref($offloadto) eq 'HASH') {
                   1639:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1640:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1641:                     ($otherserver,$lowest_load) =
                   1642:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1643:                 }
1.1129    raeburn  1644:             }
1.1172.2.5  raeburn  1645:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1646: 
1.1172.2.5  raeburn  1647:             if (!$found_server) {
                   1648:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1649:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1650:                         ($otherserver,$lowest_load) =
                   1651:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1652:                     }
                   1653:                 }
                   1654:             }
                   1655:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1656:             if (@{$offloadto} == 1) {
                   1657:                 $otherserver = $offloadto->[0];
                   1658:             } elsif (@{$offloadto} > 1) {
                   1659:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1660:                     ($otherserver,$lowest_load) =
                   1661:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1662:                 }
                   1663:             }
                   1664:         }
1.1172.2.88  raeburn  1665:         unless ($caller eq 'login') {
                   1666:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1667:                 $is_balancer = 0;
                   1668:                 if ($uname ne '' && $udom ne '') {
                   1669:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1670:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1671:                                  'user.loadbalcheck.time' => time});
                   1672:                     }
1.1172.2.5  raeburn  1673:                 }
1.1129    raeburn  1674:             }
                   1675:         }
1.1172.2.130  raeburn  1676:     }
                   1677:     if (($is_balancer) && (!$homeintdom)) {
                   1678:         undef($setcookie);
1.1129    raeburn  1679:     }
1.1172.2.107  raeburn  1680:     return ($is_balancer,$otherserver,$setcookie);
1.1129    raeburn  1681: }
                   1682: 
1.1172.2.12  raeburn  1683: sub check_balancer_result {
                   1684:     my ($result,@hosts) = @_;
1.1172.2.107  raeburn  1685:     my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1686:     if (ref($result) eq 'HASH') {
                   1687:         if ($result->{'lonhost'} ne '') {
                   1688:             my $currbalancer = $result->{'lonhost'};
                   1689:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1690:                 $is_balancer = 1;
                   1691:                 $currtargets = $result->{'targets'};
                   1692:                 $currrules = $result->{'rules'};
                   1693:             }
                   1694:         } else {
                   1695:             foreach my $key (keys(%{$result})) {
                   1696:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1697:                     (ref($result->{$key}) eq 'HASH')) {
                   1698:                     $is_balancer = 1;
                   1699:                     $currrules = $result->{$key}{'rules'};
                   1700:                     $currtargets = $result->{$key}{'targets'};
1.1172.2.107  raeburn  1701:                     $setcookie = $result->{$key}{'cookie'};
1.1172.2.12  raeburn  1702:                     last;
                   1703:                 }
                   1704:             }
                   1705:         }
                   1706:     }
1.1172.2.107  raeburn  1707:     return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1708: }
                   1709: 
1.1129    raeburn  1710: sub get_loadbalancer_targets {
                   1711:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1712:     my $offloadto;
1.1172.2.4  raeburn  1713:     if ($rule_in_effect eq 'none') {
                   1714:         return [$perlvar{'lonHostID'}];
                   1715:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1716:         $offloadto = $currtargets;
                   1717:     } else {
                   1718:         if ($rule_in_effect eq 'homeserver') {
                   1719:             my $homeserver = &homeserver($uname,$udom);
                   1720:             if ($homeserver ne 'no_host') {
                   1721:                 $offloadto = [$homeserver];
                   1722:             }
                   1723:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1724:             my %domconfig =
                   1725:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1726:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1727:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1728:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1729:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1730:                     }
                   1731:                 }
                   1732:             } else {
1.1172.2.7  raeburn  1733:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1734:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1735:                 if (&hostname($remotebalancer) ne '') {
                   1736:                     $offloadto = [$remotebalancer];
                   1737:                 }
                   1738:             }
                   1739:         } elsif (&hostname($rule_in_effect) ne '') {
                   1740:             $offloadto = [$rule_in_effect];
                   1741:         }
                   1742:     }
                   1743:     return $offloadto;
                   1744: }
                   1745: 
1.1127    raeburn  1746: sub internet_dom_servers {
                   1747:     my ($dom) = @_;
                   1748:     my (%uniqservers,%servers);
                   1749:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1750:     my @machinedoms = &machine_domains($primaryserver);
                   1751:     foreach my $mdom (@machinedoms) {
                   1752:         my %currservers = %servers;
                   1753:         my %server = &get_servers($mdom);
                   1754:         %servers = (%currservers,%server);
                   1755:     }
                   1756:     my %by_hostname;
                   1757:     foreach my $id (keys(%servers)) {
                   1758:         push(@{$by_hostname{$servers{$id}}},$id);
                   1759:     }
                   1760:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1761:         if (@{$by_hostname{$hostname}} > 1) {
                   1762:             my $match = 0;
                   1763:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1764:                 if (&host_domain($id) eq $dom) {
                   1765:                     $uniqservers{$id} = $hostname;
                   1766:                     $match = 1;
                   1767:                 }
                   1768:             }
                   1769:             unless ($match) {
                   1770:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1771:             }
                   1772:         } else {
                   1773:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1774:         }
                   1775:     }
                   1776:     return %uniqservers;
                   1777: }
                   1778: 
1.1       albertel 1779: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1780: 
1.599     albertel 1781: my %homecache;
1.1       albertel 1782: sub homeserver {
1.230     stredwic 1783:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1784:     my $index="$uname:$udom";
1.426     albertel 1785: 
1.599     albertel 1786:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1787: 
                   1788:     my %servers = &get_servers($udom,'library');
                   1789:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1790:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1791: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1792: 
                   1793: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1794: 	if ($answer eq 'found') {
                   1795: 	    delete($badServerCache{$tryserver}); 
                   1796: 	    return $homecache{$index}=$tryserver;
                   1797: 	} elsif ($answer eq 'no_host') {
                   1798: 	    $badServerCache{$tryserver}=1;
                   1799: 	}
1.1       albertel 1800:     }    
                   1801:     return 'no_host';
1.70      www      1802: }
                   1803: 
                   1804: # ------------------------------------- Find the usernames behind a list of IDs
                   1805: 
                   1806: sub idget {
                   1807:     my ($udom,@ids)=@_;
                   1808:     my %returnhash=();
                   1809:     
1.841     albertel 1810:     my %servers = &get_servers($udom,'library');
                   1811:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1812: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1813: 	$idlist=~tr/A-Z/a-z/; 
                   1814: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1815: 	my @answer=();
                   1816: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1817: 	    @answer=split(/\&/,$reply);
                   1818: 	}                    ;
                   1819: 	my $i;
                   1820: 	for ($i=0;$i<=$#ids;$i++) {
                   1821: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1822: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1823: 	    } 
                   1824: 	}
                   1825:     } 
1.70      www      1826:     return %returnhash;
                   1827: }
                   1828: 
                   1829: # ------------------------------------- Find the IDs behind a list of usernames
                   1830: 
                   1831: sub idrget {
                   1832:     my ($udom,@unames)=@_;
                   1833:     my %returnhash=();
1.800     albertel 1834:     foreach my $uname (@unames) {
                   1835:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1836:     }
1.70      www      1837:     return %returnhash;
                   1838: }
                   1839: 
                   1840: # ------------------------------- Store away a list of names and associated IDs
                   1841: 
                   1842: sub idput {
                   1843:     my ($udom,%ids)=@_;
                   1844:     my %servers=();
1.800     albertel 1845:     foreach my $uname (keys(%ids)) {
                   1846: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1847:         my $uhom=&homeserver($uname,$udom);
1.70      www      1848:         if ($uhom ne 'no_host') {
1.800     albertel 1849:             my $id=&escape($ids{$uname});
1.70      www      1850:             $id=~tr/A-Z/a-z/;
1.800     albertel 1851:             my $esc_unam=&escape($uname);
1.70      www      1852: 	    if ($servers{$uhom}) {
1.800     albertel 1853: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1854:             } else {
1.800     albertel 1855:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1856:             }
                   1857:         }
1.191     harris41 1858:     }
1.800     albertel 1859:     foreach my $server (keys(%servers)) {
                   1860:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1861:     }
1.344     www      1862: }
                   1863: 
1.1172.2.30  raeburn  1864: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1865: 
                   1866: sub iddel {
                   1867:     my ($udom,$idshashref,$uhome)=@_;
                   1868:     my %result=();
                   1869:     unless (ref($idshashref) eq 'HASH') {
                   1870:         return %result;
                   1871:     }
                   1872:     my %servers=();
                   1873:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1874:         my $uhom;
                   1875:         if ($uhome) {
                   1876:             $uhom = $uhome;
                   1877:         } else {
                   1878:             $uhom=&homeserver($uname,$udom);
                   1879:         }
                   1880:         if ($uhom ne 'no_host') {
                   1881:             if ($servers{$uhom}) {
                   1882:                 $servers{$uhom}.='&'.&escape($id);
                   1883:             } else {
                   1884:                 $servers{$uhom}=&escape($id);
                   1885:             }
                   1886:         }
                   1887:     }
                   1888:     foreach my $server (keys(%servers)) {
                   1889:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1890:     }
                   1891:     return %result;
                   1892: }
                   1893: 
1.1023    raeburn  1894: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1895: sub dump_dom {
1.1165    droeschl 1896:     my ($namespace, $udom, $regexp) = @_;
                   1897: 
                   1898:     $udom ||= $env{'user.domain'};
                   1899: 
                   1900:     return () unless $udom;
                   1901: 
                   1902:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1903: }
                   1904: 
1.1023    raeburn  1905: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1906: 
                   1907: sub get_dom {
1.1172.2.146.  .1(raebu 1908:22):     my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
1.1172.2.57  raeburn  1909:     return if ($udom eq 'public');
1.806     raeburn  1910:     my $items='';
                   1911:     foreach my $item (@$storearr) {
                   1912:         $items.=&escape($item).'&';
                   1913:     }
                   1914:     $items=~s/\&$//;
1.860     raeburn  1915:     if (!$udom) {
                   1916:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1917:         return if ($udom eq 'public');
1.860     raeburn  1918:         if (defined(&domain($udom,'primary'))) {
                   1919:             $uhome=&domain($udom,'primary');
                   1920:         } else {
1.874     albertel 1921:             undef($uhome);
1.860     raeburn  1922:         }
                   1923:     } else {
                   1924:         if (!$uhome) {
                   1925:             if (defined(&domain($udom,'primary'))) {
                   1926:                 $uhome=&domain($udom,'primary');
                   1927:             }
                   1928:         }
                   1929:     }
                   1930:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1172.2.139  raeburn  1931:         my $rep;
                   1932:         if (grep { $_ eq $uhome } &current_machine_ids()) {
                   1933:             # domain information is hosted on this machine
                   1934:             $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
1.1172.2.146.  .1(raebu 1935:22):         } else {
                   1936:22):             if ($encrypt) {
                   1937:22):                 $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   1938:22):             } else {
                   1939:22):                 $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   1940:22):             }
1.1172.2.139  raeburn  1941:         }
1.866     raeburn  1942:         my %returnhash;
1.875     albertel 1943:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1944:             return %returnhash;
                   1945:         }
1.806     raeburn  1946:         my @pairs=split(/\&/,$rep);
                   1947:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1948:             return @pairs;
                   1949:         }
                   1950:         my $i=0;
                   1951:         foreach my $item (@$storearr) {
                   1952:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1953:             $i++;
                   1954:         }
                   1955:         return %returnhash;
                   1956:     } else {
1.880     banghart 1957:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1958:     }
                   1959: }
                   1960: 
                   1961: # -------------------------------------------- put items in domain db files 
                   1962: 
                   1963: sub put_dom {
1.1172.2.146.  .1(raebu 1964:22):     my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
1.860     raeburn  1965:     if (!$udom) {
                   1966:         $udom=$env{'user.domain'};
                   1967:         if (defined(&domain($udom,'primary'))) {
                   1968:             $uhome=&domain($udom,'primary');
                   1969:         } else {
1.874     albertel 1970:             undef($uhome);
1.860     raeburn  1971:         }
                   1972:     } else {
                   1973:         if (!$uhome) {
                   1974:             if (defined(&domain($udom,'primary'))) {
                   1975:                 $uhome=&domain($udom,'primary');
                   1976:             }
                   1977:         }
                   1978:     } 
                   1979:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1980:         my $items='';
                   1981:         foreach my $item (keys(%$storehash)) {
                   1982:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1983:         }
                   1984:         $items=~s/\&$//;
1.1172.2.146.  .1(raebu 1985:22):         if ($encrypt) {
                   1986:22):             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   1987:22):         } else {
                   1988:22):             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1989:22):         }
1.806     raeburn  1990:     } else {
1.860     raeburn  1991:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1992:     }
                   1993: }
                   1994: 
1.1023    raeburn  1995: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1996: sub newput_dom {
1.1023    raeburn  1997:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1998:     my $result;
                   1999:     if (!$udom) {
                   2000:         $udom=$env{'user.domain'};
                   2001:     }
1.1023    raeburn  2002:     if ($udom) {
                   2003:         my $uname = &get_domainconfiguser($udom);
                   2004:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2005:     }
                   2006:     return $result;
                   2007: }
                   2008: 
1.1023    raeburn  2009: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2010: sub del_dom {
1.1023    raeburn  2011:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2012:     if (ref($storearr) eq 'ARRAY') {
                   2013:         if (!$udom) {
                   2014:             $udom=$env{'user.domain'};
                   2015:         }
1.1023    raeburn  2016:         if ($udom) {
                   2017:             my $uname = &get_domainconfiguser($udom); 
                   2018:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2019:         }
                   2020:     }
                   2021: }
                   2022: 
1.1172.2.146.  .4(raebu 2023:22): sub store_dom {
                   2024:22):     my ($storehash,$id,$namespace,$dom,$home,$encrypt) = @_;
                   2025:22):     $$storehash{'ip'}=&get_requestor_ip();
                   2026:22):     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2027:22):     my $namevalue='';
                   2028:22):     foreach my $key (keys(%{$storehash})) {
                   2029:22):         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   2030:22):     }
                   2031:22):     $namevalue=~s/\&$//;
                   2032:22):     if (grep { $_ eq $home } current_machine_ids()) {
                   2033:22):         return LONCAPA::Lond::store_dom("storedom:$dom:$namespace:$id:$namevalue");
                   2034:22):     } else {
                   2035:22):         if ($namespace eq 'private') {
                   2036:22):             return 'refused';
                   2037:22):         } elsif ($encrypt) {
                   2038:22):             return reply("encrypt:storedom:$dom:$namespace:$id:$namevalue",$home);
                   2039:22):         } else {
                   2040:22):             return reply("storedom:$dom:$namespace:$id:$namevalue",$home);
                   2041:22):         }
                   2042:22):     }
                   2043:22): }
                   2044:22): 
                   2045:22): sub restore_dom {
                   2046:22):     my ($id,$namespace,$dom,$home,$encrypt) = @_;
                   2047:22):     my $answer;
                   2048:22):     if (grep { $_ eq $home } current_machine_ids()) {
                   2049:22):         $answer = LONCAPA::Lond::restore_dom("restoredom:$dom:$namespace:$id");
                   2050:22):     } elsif ($namespace ne 'private') {
                   2051:22):         if ($encrypt) {
                   2052:22):             $answer=&reply("encrypt:restoredom:$dom:$namespace:$id",$home);
                   2053:22):         } else {
                   2054:22):             $answer=&reply("restoredom:$dom:$namespace:$id",$home);
                   2055:22):         }
                   2056:22):     }
                   2057:22):     my %returnhash=();
                   2058:22):     unless (($answer eq '') || ($answer eq 'con_lost') || ($answer eq 'refused') ||
                   2059:22):             ($answer eq 'unknown_cmd') || ($answer eq 'rejected')) {
                   2060:22):         foreach my $line (split(/\&/,$answer)) {
                   2061:22):             my ($name,$value)=split(/\=/,$line);
                   2062:22):             $returnhash{&unescape($name)}=&thaw_unescape($value);
                   2063:22):         }
                   2064:22):         my $version;
                   2065:22):         for ($version=1;$version<=$returnhash{'version'};$version++) {
                   2066:22):             foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2067:22):                 $returnhash{$item}=$returnhash{$version.':'.$item};
                   2068:22):             }
                   2069:22):         }
                   2070:22):     }
                   2071:22):     return %returnhash;
                   2072:22): }
                   2073:22): 
1.1023    raeburn  2074: # ----------------------------------construct domainconfig user for a domain 
                   2075: sub get_domainconfiguser {
                   2076:     my ($udom) = @_;
                   2077:     return $udom.'-domainconfig';
                   2078: }
                   2079: 
1.837     raeburn  2080: sub retrieve_inst_usertypes {
                   2081:     my ($udom) = @_;
                   2082:     my (%returnhash,@order);
1.989     raeburn  2083:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2084:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2085:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  2086:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2087:     } else {
                   2088:         if (defined(&domain($udom,'primary'))) {
                   2089:             my $uhome=&domain($udom,'primary');
                   2090:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2091:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  2092:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2093:                 return (\%returnhash,\@order);
                   2094:             }
                   2095:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2096:             my @pairs=split(/\&/,$hashitems);
                   2097:             foreach my $item (@pairs) {
                   2098:                 my ($key,$value)=split(/=/,$item,2);
                   2099:                 $key = &unescape($key);
                   2100:                 next if ($key =~ /^error: 2 /);
                   2101:                 $returnhash{$key}=&thaw_unescape($value);
                   2102:             }
                   2103:             my @esc_order = split(/\&/,$orderitems);
                   2104:             foreach my $item (@esc_order) {
                   2105:                 push(@order,&unescape($item));
                   2106:             }
                   2107:         } else {
1.1172.2.44  raeburn  2108:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2109:         }
1.1172.2.44  raeburn  2110:         return (\%returnhash,\@order);
1.837     raeburn  2111:     }
                   2112: }
                   2113: 
1.868     raeburn  2114: sub is_domainimage {
                   2115:     my ($url) = @_;
1.1172.2.142  raeburn  2116:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
1.868     raeburn  2117:         if (&domain($1) ne '') {
                   2118:             return '1';
                   2119:         }
                   2120:     }
                   2121:     return;
                   2122: }
                   2123: 
1.899     raeburn  2124: sub inst_directory_query {
                   2125:     my ($srch) = @_;
                   2126:     my $udom = $srch->{'srchdomain'};
                   2127:     my %results;
                   2128:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2129:     my $outcome;
1.899     raeburn  2130:     if ($homeserver ne '') {
1.1172.2.116  raeburn  2131:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2132:             if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2133:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116  raeburn  2134:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
                   2135:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2136:                     (($major == 2) && ($minor < 11)) ||
                   2137:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
                   2138:                     return;
                   2139:                 }
                   2140:             }
                   2141:         }
1.904     albertel 2142: 	my $queryid=&reply("querysend:instdirsearch:".
                   2143: 			   &escape($srch->{'srchby'}).':'.
                   2144: 			   &escape($srch->{'srchterm'}).':'.
                   2145: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2146: 	my $host=&hostname($homeserver);
                   2147: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  2148: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2149: 	    return;
                   2150: 	}
                   2151: 	my $response = &get_query_reply($queryid);
                   2152: 	my $maxtries = 5;
                   2153: 	my $tries = 1;
                   2154: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2155: 	    $response = &get_query_reply($queryid);
                   2156: 	    $tries ++;
                   2157: 	}
                   2158: 
                   2159:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2160:             if ($response eq 'unavailable') {
                   2161:                 $outcome = $response;
                   2162:             } else {
                   2163:                 $outcome = 'ok';
                   2164:                 my @matches = split(/\n/,$response);
                   2165:                 foreach my $match (@matches) {
                   2166:                     my ($key,$value) = split(/=/,$match);
                   2167:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2168:                 }
1.899     raeburn  2169:             }
                   2170:         }
                   2171:     }
1.909     raeburn  2172:     return ($outcome,%results);
1.899     raeburn  2173: }
                   2174: 
                   2175: sub usersearch {
                   2176:     my ($srch) = @_;
                   2177:     my $dom = $srch->{'srchdomain'};
                   2178:     my %results;
                   2179:     my %libserv = &all_library();
                   2180:     my $query = 'usersearch';
                   2181:     foreach my $tryserver (keys(%libserv)) {
                   2182:         if (&host_domain($tryserver) eq $dom) {
1.1172.2.116  raeburn  2183:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2184:                 if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2185:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.119  raeburn  2186:                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116  raeburn  2187:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2188:                              (($major == 2) && ($minor < 11)) ||
                   2189:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
                   2190:                 }
                   2191:             }
1.899     raeburn  2192:             my $host=&hostname($tryserver);
                   2193:             my $queryid=
1.911     raeburn  2194:                 &reply("querysend:".&escape($query).':'.
                   2195:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2196:                        &escape($srch->{'srchtype'}).':'.
                   2197:                        &escape($srch->{'srchterm'}),$tryserver);
                   2198:             if ($queryid !~/^\Q$host\E\_/) {
                   2199:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2200:                 next;
1.899     raeburn  2201:             }
                   2202:             my $reply = &get_query_reply($queryid);
                   2203:             my $maxtries = 1;
                   2204:             my $tries = 1;
                   2205:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2206:                 $reply = &get_query_reply($queryid);
                   2207:                 $tries ++;
                   2208:             }
                   2209:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2210:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2211:             } else {
1.911     raeburn  2212:                 my @matches;
                   2213:                 if ($reply =~ /\n/) {
                   2214:                     @matches = split(/\n/,$reply);
                   2215:                 } else {
                   2216:                     @matches = split(/\&/,$reply);
                   2217:                 }
1.899     raeburn  2218:                 foreach my $match (@matches) {
                   2219:                     my ($uname,$udom,%userhash);
1.911     raeburn  2220:                     foreach my $entry (split(/:/,$match)) {
                   2221:                         my ($key,$value) =
                   2222:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2223:                         $userhash{$key} = $value;
                   2224:                         if ($key eq 'username') {
                   2225:                             $uname = $value;
                   2226:                         } elsif ($key eq 'domain') {
                   2227:                             $udom = $value;
1.911     raeburn  2228:                         }
1.899     raeburn  2229:                     }
                   2230:                     $results{$uname.':'.$udom} = \%userhash;
                   2231:                 }
                   2232:             }
                   2233:         }
                   2234:     }
                   2235:     return %results;
                   2236: }
                   2237: 
1.912     raeburn  2238: sub get_instuser {
                   2239:     my ($udom,$uname,$id) = @_;
                   2240:     my $homeserver = &domain($udom,'primary');
                   2241:     my ($outcome,%results);
                   2242:     if ($homeserver ne '') {
                   2243:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2244:                            &escape($id).':'.&escape($udom),$homeserver);
                   2245:         my $host=&hostname($homeserver);
                   2246:         if ($queryid !~/^\Q$host\E\_/) {
                   2247:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2248:             return;
                   2249:         }
                   2250:         my $response = &get_query_reply($queryid);
                   2251:         my $maxtries = 5;
                   2252:         my $tries = 1;
                   2253:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2254:             $response = &get_query_reply($queryid);
                   2255:             $tries ++;
                   2256:         }
                   2257:         if (!&error($response) && $response ne 'refused') {
                   2258:             if ($response eq 'unavailable') {
                   2259:                 $outcome = $response;
                   2260:             } else {
                   2261:                 $outcome = 'ok';
                   2262:                 my @matches = split(/\n/,$response);
                   2263:                 foreach my $match (@matches) {
                   2264:                     my ($key,$value) = split(/=/,$match);
                   2265:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2266:                 }
                   2267:             }
                   2268:         }
                   2269:     }
                   2270:     my %userinfo;
                   2271:     if (ref($results{$uname}) eq 'HASH') {
                   2272:         %userinfo = %{$results{$uname}};
                   2273:     } 
                   2274:     return ($outcome,%userinfo);
                   2275: }
                   2276: 
1.1172.2.69  raeburn  2277: sub get_multiple_instusers {
                   2278:     my ($udom,$users,$caller) = @_;
                   2279:     my ($outcome,$results);
                   2280:     if (ref($users) eq 'HASH') {
                   2281:         my $count = keys(%{$users});
                   2282:         my $requested = &freeze_escape($users);
                   2283:         my $homeserver = &domain($udom,'primary');
                   2284:         if ($homeserver ne '') {
                   2285:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2286:             my $host=&hostname($homeserver);
                   2287:             if ($queryid !~/^\Q$host\E\_/) {
                   2288:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2289:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2290:                 return ($outcome,$results);
                   2291:             }
                   2292:             my $response = &get_query_reply($queryid);
                   2293:             my $maxtries = 5;
                   2294:             if ($count > 100) {
                   2295:                 $maxtries = 1+int($count/20);
                   2296:             }
                   2297:             my $tries = 1;
                   2298:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2299:                 $response = &get_query_reply($queryid);
                   2300:                 $tries ++;
                   2301:             }
                   2302:             if ($response eq '') {
                   2303:                 $results = {};
                   2304:                 foreach my $key (keys(%{$users})) {
                   2305:                     my ($uname,$id);
                   2306:                     if ($caller eq 'id') {
                   2307:                         $id = $key;
                   2308:                     } else {
                   2309:                         $uname = $key;
                   2310:                     }
                   2311:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2312:                     $outcome = $resp;
                   2313:                     if ($resp eq 'ok') {
                   2314:                         %{$results} = (%{$results}, %info);
                   2315:                     } else {
                   2316:                         last;
                   2317:                     }
                   2318:                 }
                   2319:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2320:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2321:                     $outcome = $response;
                   2322:                 } else {
                   2323:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2324:                     if ($outcome eq 'ok') {
                   2325:                         $results = &thaw_unescape($userdata);
                   2326:                     }
                   2327:                 }
                   2328:             }
                   2329:         }
                   2330:     }
                   2331:     return ($outcome,$results);
                   2332: }
                   2333: 
1.912     raeburn  2334: sub inst_rulecheck {
1.923     raeburn  2335:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2336:     my %returnhash;
                   2337:     if ($udom ne '') {
                   2338:         if (ref($rules) eq 'ARRAY') {
                   2339:             @{$rules} = map {&escape($_);} (@{$rules});
                   2340:             my $rulestr = join(':',@{$rules});
                   2341:             my $homeserver=&domain($udom,'primary');
                   2342:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2343:                 my $response;
                   2344:                 if ($item eq 'username') {                
                   2345:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2346:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2347:                                               $homeserver));
1.923     raeburn  2348:                 } elsif ($item eq 'id') {
                   2349:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2350:                                               ':'.&escape($id).':'.$rulestr,
                   2351:                                               $homeserver));
1.1172.2.146.  .5(raebu 2352:22):                 } elsif ($item eq 'unamemap') {
                   2353:22):                     $response=&unescape(&reply('instunamemapcheck:'.
                   2354:22):                                                &escape($udom).':'.&escape($uname).
                   2355:22):                                               ':'.$rulestr,$homeserver));
1.945     raeburn  2356:                 } elsif ($item eq 'selfcreate') {
                   2357:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2358:                                                &escape($udom).':'.&escape($uname).
                   2359:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2360:                 }
1.912     raeburn  2361:                 if ($response ne 'refused') {
                   2362:                     my @pairs=split(/\&/,$response);
                   2363:                     foreach my $item (@pairs) {
                   2364:                         my ($key,$value)=split(/=/,$item,2);
                   2365:                         $key = &unescape($key);
                   2366:                         next if ($key =~ /^error: 2 /);
                   2367:                         $returnhash{$key}=&thaw_unescape($value);
                   2368:                     }
                   2369:                 }
                   2370:             }
                   2371:         }
                   2372:     }
                   2373:     return %returnhash;
                   2374: }
                   2375: 
                   2376: sub inst_userrules {
1.923     raeburn  2377:     my ($udom,$check) = @_;
1.912     raeburn  2378:     my (%ruleshash,@ruleorder);
                   2379:     if ($udom ne '') {
                   2380:         my $homeserver=&domain($udom,'primary');
                   2381:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2382:             my $response;
                   2383:             if ($check eq 'id') {
                   2384:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2385:                                  $homeserver);
1.943     raeburn  2386:             } elsif ($check eq 'email') {
                   2387:                 $response=&reply('instemailrules:'.&escape($udom),
                   2388:                                  $homeserver);
1.1172.2.146.  .5(raebu 2389:22):             } elsif ($check eq 'unamemap') {
                   2390:22):                 $response=&reply('unamemaprules:'.&escape($udom),
                   2391:22):                                  $homeserver);
1.923     raeburn  2392:             } else {
                   2393:                 $response=&reply('instuserrules:'.&escape($udom),
                   2394:                                  $homeserver);
                   2395:             }
1.912     raeburn  2396:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2397:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2398:                 ($response ne 'no_such_host')) {
                   2399:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2400:                 my @pairs=split(/\&/,$hashitems);
                   2401:                 foreach my $item (@pairs) {
                   2402:                     my ($key,$value)=split(/=/,$item,2);
                   2403:                     $key = &unescape($key);
                   2404:                     next if ($key =~ /^error: 2 /);
                   2405:                     $ruleshash{$key}=&thaw_unescape($value);
                   2406:                 }
                   2407:                 my @esc_order = split(/\&/,$orderitems);
                   2408:                 foreach my $item (@esc_order) {
                   2409:                     push(@ruleorder,&unescape($item));
                   2410:                 }
                   2411:             }
                   2412:         }
                   2413:     }
                   2414:     return (\%ruleshash,\@ruleorder);
                   2415: }
                   2416: 
1.976     raeburn  2417: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2418: 
                   2419: sub get_domain_defaults {
1.1172.2.35  raeburn  2420:     my ($domain,$ignore_cache) = @_;
                   2421:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2422:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2423:     unless ($ignore_cache) {
                   2424:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2425:         if (defined($cached)) {
                   2426:             if (ref($result) eq 'HASH') {
                   2427:                 return %{$result};
                   2428:             }
1.943     raeburn  2429:         }
                   2430:     }
                   2431:     my %domdefaults;
                   2432:     my %domconfig =
1.989     raeburn  2433:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2434:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2435:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2436:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2437:                                   'coursecategories','autoenroll',
1.1172.2.146.  .4(raebu 2438:22):                                   'helpsettings','wafproxy','ltisec'],$domain);
1.1172.2.41  raeburn  2439:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2440:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2441:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2442:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2443:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2444:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2445:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2446:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.146.  .12(raeb 2447:-23):         $domdefaults{'portal_def_email'} = $domconfig{'defaults'}{'portal_def_email'};
                   2448:-23):         $domdefaults{'portal_def_web'} = $domconfig{'defaults'}{'portal_def_web'};
1.1172.2.91  raeburn  2449:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2450:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2451:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.1172.2.146.  .5(raebu 2452:22):         $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
1.943     raeburn  2453:     } else {
                   2454:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2455:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2456:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2457:     }
1.976     raeburn  2458:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2459:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2460:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2461:         } else {
                   2462:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2463:         }
1.1172.2.6  raeburn  2464:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2465:         foreach my $item (@usertools) {
                   2466:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2467:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2468:             }
                   2469:         }
1.1172.2.29  raeburn  2470:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2471:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2472:         }
1.976     raeburn  2473:     }
1.985     raeburn  2474:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2475:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2476:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2477:         }
                   2478:     }
1.1172.2.9  raeburn  2479:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2480:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2481:     }
1.989     raeburn  2482:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2483:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2484:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2485:         }
                   2486:     }
1.1047    raeburn  2487:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2488:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
1.1172.2.144  raeburn  2489:         $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
1.1172.2.60  raeburn  2490:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2491:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2492:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2493:         }
1.1172.2.41  raeburn  2494:         foreach my $type (@coursetypes) {
                   2495:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2496:                 unless ($type eq 'community') {
                   2497:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2498:                 }
                   2499:             }
                   2500:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2501:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2502:             }
1.1172.2.60  raeburn  2503:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2504:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2505:                     $domdefaults{$type.'postsubtimeout'} =
                   2506:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2507:                 }
                   2508:             }
1.1172.2.30  raeburn  2509:         }
1.1172.2.67  raeburn  2510:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2511:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2512:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2513:                 if (@clonecodes) {
                   2514:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2515:                 }
                   2516:             }
                   2517:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2518:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2519:         }
1.1172.2.103  raeburn  2520:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2521:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2522:         }
1.1172.2.146.  .3(raebu 2523:22):         if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
                   2524:22):             $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
                   2525:22):         }
1.1047    raeburn  2526:     }
1.1073    raeburn  2527:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2528:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2529:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2530:         }
                   2531:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2532:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2533:         }
1.1172.2.62  raeburn  2534:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2535:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2536:         }
1.1172.2.137  raeburn  2537:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1172.2.136  raeburn  2538:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
                   2539:         }
1.1073    raeburn  2540:     }
1.1172.2.41  raeburn  2541:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2542:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2543:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2544:                             'approval','limit');
                   2545:             foreach my $type (@coursetypes) {
                   2546:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2547:                     my @mgrdc = ();
                   2548:                     foreach my $item (@settings) {
                   2549:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2550:                             push(@mgrdc,$item);
                   2551:                         }
                   2552:                     }
                   2553:                     if (@mgrdc) {
                   2554:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2555:                     }
                   2556:                 }
                   2557:             }
                   2558:         }
                   2559:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2560:             foreach my $type (@coursetypes) {
                   2561:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2562:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2563:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2564:                     }
                   2565:                 }
                   2566:             }
                   2567:         }
                   2568:     }
1.1172.2.46  raeburn  2569:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2570:         $domdefaults{'catauth'} = 'std';
                   2571:         $domdefaults{'catunauth'} = 'std';
                   2572:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2573:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2574:         }
                   2575:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2576:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2577:         }
                   2578:     }
1.1172.2.76  raeburn  2579:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2580:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
1.1172.2.146  raeburn  2581:         $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
1.1172.2.76  raeburn  2582:     }
1.1172.2.89  raeburn  2583:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2584:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2585:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2586:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2587:         }
                   2588:     }
1.1172.2.142  raeburn  2589:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   2590:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
                   2591:             if ($domconfig{'wafproxy'}{$item}) {
                   2592:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
                   2593:             }
                   2594:         }
                   2595:     }
1.1172.2.146.  .4(raebu 2596:22):     if (ref($domconfig{'ltisec'}) eq 'HASH') {
                   2597:22):         if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
                   2598:22):             $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
                   2599:22):             $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
                   2600:22):             $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
                   2601:22):         }
                   2602:22):         if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
                   2603:22):             if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
                   2604:22):                 $domdefaults{'privhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
                   2605:22):             }
                   2606:22):         }
                   2607:22):     }
1.1172.2.23  raeburn  2608:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2609:     return %domdefaults;
                   2610: }
                   2611: 
1.1172.2.106  raeburn  2612: sub get_dom_cats {
                   2613:     my ($dom) = @_;
                   2614:     return unless (&domain($dom));
                   2615:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2616:     unless (defined($cached)) {
                   2617:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2618:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2619:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2620:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2621:             } else {
                   2622:                 $cats = {};
                   2623:             }
                   2624:         } else {
                   2625:             $cats = {};
                   2626:         }
                   2627:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2628:     }
                   2629:     return $cats;
                   2630: }
                   2631: 
                   2632: sub get_dom_instcats {
                   2633:     my ($dom) = @_;
                   2634:     return unless (&domain($dom));
                   2635:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2636:     unless (defined($cached)) {
                   2637:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2638:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2639:         if ($totcodes > 0) {
                   2640:             my $caller = 'global';
                   2641:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2642:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2643:                 $instcats = {
1.1172.2.146.  .10(raeb 2644:-23):                                 totcodes => $totcodes,
1.1172.2.106  raeburn  2645:                                 codes => \%codes,
                   2646:                                 codetitles => \@codetitles,
                   2647:                                 cat_titles => \%cat_titles,
                   2648:                                 cat_order => \%cat_order,
                   2649:                             };
                   2650:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2651:             }
                   2652:         }
                   2653:     }
                   2654:     return $instcats;
                   2655: }
                   2656: 
                   2657: sub retrieve_instcodes {
                   2658:     my ($coursecodes,$dom) = @_;
                   2659:     my $totcodes;
                   2660:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2661:     foreach my $course (keys(%courses)) {
                   2662:         if (ref($courses{$course}) eq 'HASH') {
                   2663:             if ($courses{$course}{'inst_code'} ne '') {
                   2664:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2665:                 $totcodes ++;
                   2666:             }
                   2667:         }
                   2668:     }
                   2669:     return $totcodes;
                   2670: }
                   2671: 
1.1172.2.113  raeburn  2672: # --------------------------------------------- Get domain config for passwords
                   2673: 
                   2674: sub get_passwdconf {
                   2675:     my ($dom) = @_;
                   2676:     my (%passwdconf,$gotconf,$lookup);
                   2677:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2678:     if (defined($cached)) {
                   2679:         if (ref($result) eq 'HASH') {
                   2680:             %passwdconf = %{$result};
                   2681:             $gotconf = 1;
                   2682:         }
                   2683:     }
                   2684:     unless ($gotconf) {
                   2685:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2686:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2687:             %passwdconf = %{$domconfig{'passwords'}};
                   2688:         }
                   2689:         my $cachetime = 24*60*60;
                   2690:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2691:     }
                   2692:     return %passwdconf;
                   2693: }
                   2694: 
1.1172.2.146.  .1(raebu 2695:22): sub course_portal_url {
                   2696:22):     my ($cnum,$cdom,$r) = @_;
                   2697:22):     my $chome = &homeserver($cnum,$cdom);
                   2698:22):     my $hostname = &hostname($chome);
                   2699:22):     my $protocol = $protocol{$chome};
                   2700:22):     $protocol = 'http' if ($protocol ne 'https');
                   2701:22):     my %domdefaults = &get_domain_defaults($cdom);
                   2702:22):     my $firsturl;
                   2703:22):     if ($domdefaults{'portal_def'}) {
                   2704:22):         $firsturl = $domdefaults{'portal_def'};
                   2705:22):     } else {
                   2706:22):         my $alias = &Apache::lonnet::use_proxy_alias($r,$chome);
                   2707:22):         $hostname = $alias if ($alias ne '');
                   2708:22):         $firsturl = $protocol.'://'.$hostname;
                   2709:22):     }
                   2710:22):     return $firsturl;
                   2711:22): }
                   2712:22): 
          .12(raeb 2713:-23): sub url_prefix {
                   2714:-23):     my ($r,$dom,$home,$context) = @_;
                   2715:-23):     my $prefix;
                   2716:-23):     my %domdefs = &get_domain_defaults($dom);
                   2717:-23):     if ($domdefs{'portal_def'} && $domdefs{'portal_def_'.$context}) {
                   2718:-23):         if ($domdefs{'portal_def'} =~ m{^(https?://[^/]+)}) {
                   2719:-23):             $prefix = $1;
                   2720:-23):         }
                   2721:-23):     }
                   2722:-23):     if ($prefix eq '') {
                   2723:-23):         my $hostname = &hostname($home);
                   2724:-23):         my $protocol = $protocol{$home};
                   2725:-23):         $protocol = 'http' if ($protocol{$home} ne 'https');
                   2726:-23):         my $alias = &use_proxy_alias($r,$home);
                   2727:-23):         $hostname = $alias if ($alias ne '');
                   2728:-23):         $prefix = $protocol.'://'.$hostname;
                   2729:-23):     }
                   2730:-23):     return $prefix;
                   2731:-23): }
                   2732:-23): 
1.344     www      2733: # --------------------------------------------------- Assign a key to a student
                   2734: 
                   2735: sub assign_access_key {
1.364     www      2736: #
                   2737: # a valid key looks like uname:udom#comments
                   2738: # comments are being appended
                   2739: #
1.498     www      2740:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2741:     $kdom=
1.620     albertel 2742:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2743:     $knum=
1.620     albertel 2744:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2745:     $cdom=
1.620     albertel 2746:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2747:     $cnum=
1.620     albertel 2748:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2749:     $udom=$env{'user.name'} unless (defined($udom));
                   2750:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2751:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2752:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2753:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2754:                                                   # assigned to this person
                   2755:                                                   # - this should not happen,
1.345     www      2756:                                                   # unless something went wrong
                   2757:                                                   # the first time around
                   2758: # ready to assign
1.364     www      2759:         $logentry=$1.'; '.$logentry;
1.496     www      2760:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2761:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2762: # key now belongs to user
1.346     www      2763: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2764:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2765:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2766:                 return 'ok';
                   2767:             } else {
                   2768:                 return 
                   2769:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2770: 	    }
                   2771:         } else {
                   2772:             return 'error: Could not assign key, try again later.';
                   2773:         }
1.364     www      2774:     } elsif (!$existing{$ckey}) {
1.345     www      2775: # the key does not exist
                   2776: 	return 'error: The key does not exist';
                   2777:     } else {
                   2778: # the key is somebody else's
                   2779: 	return 'error: The key is already in use';
                   2780:     }
1.344     www      2781: }
                   2782: 
1.364     www      2783: # ------------------------------------------ put an additional comment on a key
                   2784: 
                   2785: sub comment_access_key {
                   2786: #
                   2787: # a valid key looks like uname:udom#comments
                   2788: # comments are being appended
                   2789: #
                   2790:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2791:     $cdom=
1.620     albertel 2792:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2793:     $cnum=
1.620     albertel 2794:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2795:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2796:     if ($existing{$ckey}) {
                   2797:         $existing{$ckey}.='; '.$logentry;
                   2798: # ready to assign
1.367     www      2799:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2800:                                                  $cdom,$cnum) eq 'ok') {
                   2801: 	    return 'ok';
                   2802:         } else {
                   2803: 	    return 'error: Count not store comment.';
                   2804:         }
                   2805:     } else {
                   2806: # the key does not exist
                   2807: 	return 'error: The key does not exist';
                   2808:     }
                   2809: }
                   2810: 
1.344     www      2811: # ------------------------------------------------------ Generate a set of keys
                   2812: 
                   2813: sub generate_access_keys {
1.364     www      2814:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2815:     $cdom=
1.620     albertel 2816:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2817:     $cnum=
1.620     albertel 2818:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2819:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2820:     unless (($cdom) && ($cnum)) { return 0; }
                   2821:     if ($number>10000) { return 0; }
                   2822:     sleep(2); # make sure don't get same seed twice
                   2823:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2824:     my $total=0;
                   2825:     for (my $i=1;$i<=$number;$i++) {
                   2826:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2827:                   sprintf("%lx",int(100000*rand)).'-'.
                   2828:                   sprintf("%lx",int(100000*rand));
                   2829:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2830:        $newkey=~s/0/h/g; # and also 0 and O
                   2831:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2832:        if ($existing{$newkey}) {
                   2833:            $i--;
                   2834:        } else {
1.364     www      2835: 	  if (&put('accesskeys',
                   2836:               { $newkey => '# generated '.localtime().
1.620     albertel 2837:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2838:                            '; '.$logentry },
                   2839: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2840:               $total++;
                   2841: 	  }
                   2842:        }
                   2843:     }
1.620     albertel 2844:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2845:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2846:     return $total;
                   2847: }
                   2848: 
                   2849: # ------------------------------------------------------- Validate an accesskey
                   2850: 
                   2851: sub validate_access_key {
                   2852:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2853:     $cdom=
1.620     albertel 2854:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2855:     $cnum=
1.620     albertel 2856:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2857:     $udom=$env{'user.domain'} unless (defined($udom));
                   2858:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2859:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2860:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2861: }
                   2862: 
                   2863: # ------------------------------------- Find the section of student in a course
1.652     albertel 2864: sub devalidate_getsection_cache {
                   2865:     my ($udom,$unam,$courseid)=@_;
                   2866:     my $hashid="$udom:$unam:$courseid";
                   2867:     &devalidate_cache_new('getsection',$hashid);
                   2868: }
1.298     matthew  2869: 
1.815     albertel 2870: sub courseid_to_courseurl {
                   2871:     my ($courseid) = @_;
                   2872:     #already url style courseid
                   2873:     return $courseid if ($courseid =~ m{^/});
                   2874: 
                   2875:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2876: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2877: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2878: 	return "/$cdom/$cnum";
                   2879:     }
                   2880: 
                   2881:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2882:     if (exists($courseinfo{'num'})) {
                   2883: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2884:     }
                   2885: 
                   2886:     return undef;
                   2887: }
                   2888: 
1.298     matthew  2889: sub getsection {
                   2890:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2891:     my $cachetime=1800;
1.551     albertel 2892: 
                   2893:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2894:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2895:     if (defined($cached)) { return $result; }
                   2896: 
1.298     matthew  2897:     my %Pending; 
                   2898:     my %Expired;
                   2899:     #
                   2900:     # Each role can either have not started yet (pending), be active, 
                   2901:     #    or have expired.
                   2902:     #
                   2903:     # If there is an active role, we are done.
                   2904:     #
                   2905:     # If there is more than one role which has not started yet, 
                   2906:     #     choose the one which will start sooner
                   2907:     # If there is one role which has not started yet, return it.
                   2908:     #
                   2909:     # If there is more than one expired role, choose the one which ended last.
                   2910:     # If there is a role which has expired, return it.
                   2911:     #
1.815     albertel 2912:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2913:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2914:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2915:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2916:         my $section=$1;
                   2917:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2918:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2919:         my $now=time;
1.548     albertel 2920:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2921:             $Expired{$end}=$section;
                   2922:             next;
                   2923:         }
1.548     albertel 2924:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2925:             $Pending{$start}=$section;
                   2926:             next;
                   2927:         }
1.599     albertel 2928:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2929:     }
                   2930:     #
                   2931:     # Presumedly there will be few matching roles from the above
                   2932:     # loop and the sorting time will be negligible.
                   2933:     if (scalar(keys(%Pending))) {
                   2934:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2935:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2936:     } 
                   2937:     if (scalar(keys(%Expired))) {
                   2938:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2939:         my $time = pop(@sorted);
1.599     albertel 2940:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2941:     }
1.599     albertel 2942:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2943: }
1.70      www      2944: 
1.599     albertel 2945: sub save_cache {
                   2946:     &purge_remembered();
1.722     albertel 2947:     #&Apache::loncommon::validate_page();
1.620     albertel 2948:     undef(%env);
1.780     albertel 2949:     undef($env_loaded);
1.599     albertel 2950: }
1.452     albertel 2951: 
1.599     albertel 2952: my $to_remember=-1;
                   2953: my %remembered;
                   2954: my %accessed;
                   2955: my $kicks=0;
                   2956: my $hits=0;
1.849     albertel 2957: sub make_key {
                   2958:     my ($name,$id) = @_;
1.872     albertel 2959:     if (length($id) > 65 
                   2960: 	&& length(&escape($id)) > 200) {
                   2961: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2962:     }
1.849     albertel 2963:     return &escape($name.':'.$id);
                   2964: }
                   2965: 
1.599     albertel 2966: sub devalidate_cache_new {
                   2967:     my ($name,$id,$debug) = @_;
                   2968:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  2969:     my $remembered_id=$name.':'.$id;
1.849     albertel 2970:     $id=&make_key($name,$id);
1.599     albertel 2971:     $memcache->delete($id);
1.1172.2.81  raeburn  2972:     delete($remembered{$remembered_id});
                   2973:     delete($accessed{$remembered_id});
1.599     albertel 2974: }
                   2975: 
                   2976: sub is_cached_new {
                   2977:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  2978:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   2979:                                      # keys in %remembered hash, which persists for
                   2980:                                      # duration of request (no restriction on key length).
                   2981:     if (exists($remembered{$remembered_id})) {
                   2982: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2983: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2984: 	$hits++;
1.1172.2.81  raeburn  2985: 	return ($remembered{$remembered_id},1);
1.599     albertel 2986:     }
1.1172.2.81  raeburn  2987:     $id=&make_key($name,$id);
1.599     albertel 2988:     my $value = $memcache->get($id);
                   2989:     if (!(defined($value))) {
                   2990: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2991: 	return (undef,undef);
1.416     albertel 2992:     }
1.599     albertel 2993:     if ($value eq '__undef__') {
                   2994: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2995: 	$value=undef;
                   2996:     }
1.1172.2.81  raeburn  2997:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2998:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2999:     return ($value,1);
                   3000: }
                   3001: 
                   3002: sub do_cache_new {
                   3003:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  3004:     my $remembered_id=$name.':'.$id;
1.849     albertel 3005:     $id=&make_key($name,$id);
1.599     albertel 3006:     my $setvalue=$value;
                   3007:     if (!defined($setvalue)) {
                   3008: 	$setvalue='__undef__';
                   3009:     }
1.623     albertel 3010:     if (!defined($time) ) {
                   3011: 	$time=600;
                   3012:     }
1.599     albertel 3013:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 3014:     my $result = $memcache->set($id,$setvalue,$time);
                   3015:     if (! $result) {
1.872     albertel 3016: 	&logthis("caching of id -> $id  failed");
1.910     albertel 3017: 	$memcache->disconnect_all();
1.872     albertel 3018:     }
1.600     albertel 3019:     # need to make a copy of $value
1.1172.2.81  raeburn  3020:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3021:     return $value;
                   3022: }
                   3023: 
                   3024: sub make_room {
1.1172.2.81  raeburn  3025:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 3026: 
1.1172.2.81  raeburn  3027:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 3028:                                     : $value;
1.599     albertel 3029:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  3030:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3031:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   3032:     my $to_kick;
                   3033:     my $max_time=0;
                   3034:     foreach my $other (keys(%accessed)) {
                   3035: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   3036: 	    $to_kick=$other;
                   3037: 	    $max_time=&tv_interval($accessed{$other});
                   3038: 	}
                   3039:     }
                   3040:     delete($remembered{$to_kick});
                   3041:     delete($accessed{$to_kick});
                   3042:     $kicks++;
                   3043:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 3044:     return;
                   3045: }
                   3046: 
1.599     albertel 3047: sub purge_remembered {
1.604     albertel 3048:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   3049:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 3050:     undef(%remembered);
                   3051:     undef(%accessed);
1.428     albertel 3052: }
1.70      www      3053: # ------------------------------------- Read an entry from a user's environment
                   3054: 
                   3055: sub userenvironment {
                   3056:     my ($udom,$unam,@what)=@_;
1.976     raeburn  3057:     my $items;
                   3058:     foreach my $item (@what) {
                   3059:         $items.=&escape($item).'&';
                   3060:     }
                   3061:     $items=~s/\&$//;
1.70      www      3062:     my %returnhash=();
1.1009    raeburn  3063:     my $uhome = &homeserver($unam,$udom);
                   3064:     unless ($uhome eq 'no_host') {
                   3065:         my @answer=split(/\&/, 
                   3066:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  3067:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   3068:             return %returnhash;
                   3069:         }
1.1009    raeburn  3070:         my $i;
                   3071:         for ($i=0;$i<=$#what;$i++) {
                   3072: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3073:         }
1.70      www      3074:     }
                   3075:     return %returnhash;
1.1       albertel 3076: }
                   3077: 
1.617     albertel 3078: # ---------------------------------------------------------- Get a studentphoto
                   3079: sub studentphoto {
                   3080:     my ($udom,$unam,$ext) = @_;
                   3081:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  3082:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3083:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3084:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3085:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3086:             } else {
                   3087:                 my ($result,$perm_reqd)=
1.707     albertel 3088: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3089:                 if ($result eq 'ok') {
                   3090:                     if (!($perm_reqd eq 'yes')) {
                   3091:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3092:                     }
                   3093:                 }
                   3094:             }
                   3095:         }
                   3096:     } else {
                   3097:         my ($result,$perm_reqd) = 
1.707     albertel 3098: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3099:         if ($result eq 'ok') {
                   3100:             if (!($perm_reqd eq 'yes')) {
                   3101:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3102:             }
                   3103:         }
                   3104:     }
                   3105:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3106: }
                   3107: 
                   3108: sub retrievestudentphoto {
                   3109:     my ($udom,$unam,$ext,$type) = @_;
                   3110:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   3111:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   3112:     if ($ret eq 'ok') {
                   3113:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3114:         if ($type eq 'thumbnail') {
                   3115:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3116:         }
                   3117:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   3118:         return $tokenurl;
                   3119:     } else {
                   3120:         if ($type eq 'thumbnail') {
                   3121:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3122:         } else { 
                   3123:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3124:         }
1.617     albertel 3125:     }
                   3126: }
                   3127: 
1.263     www      3128: # -------------------------------------------------------------------- New chat
                   3129: 
                   3130: sub chatsend {
1.724     raeburn  3131:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3132:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3133:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3134:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3135:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3136: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3137: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3138: }
                   3139: 
                   3140: # ------------------------------------------ Find current version of a resource
                   3141: 
                   3142: sub getversion {
                   3143:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  3144:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3145:     return &currentversion(&filelocation('',$fname));
                   3146: }
                   3147: 
                   3148: sub currentversion {
                   3149:     my $fname=shift;
                   3150:     my $author=$fname;
                   3151:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3152:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3153:     my $home=&homeserver($uname,$udom);
1.292     www      3154:     if ($home eq 'no_host') { 
                   3155:         return -1; 
                   3156:     }
1.1112    www      3157:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3158:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3159: 	return -1;
                   3160:     }
1.1112    www      3161:     return $answer;
1.263     www      3162: }
                   3163: 
1.1111    www      3164: #
                   3165: # Return special version number of resource if set by override, empty otherwise
                   3166: #
                   3167: sub usedversion {
                   3168:     my $fname=shift;
                   3169:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3170:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3171:     if ($urlversion) { return $urlversion; }
                   3172:     return '';
                   3173: }
                   3174: 
1.1       albertel 3175: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3176: 
1.1       albertel 3177: sub subscribe {
                   3178:     my $fname=shift;
1.761     raeburn  3179:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3180:     $fname=~s/[\n\r]//g;
1.1       albertel 3181:     my $author=$fname;
                   3182:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3183:     my ($udom,$uname)=split(/\//,$author);
                   3184:     my $home=homeserver($uname,$udom);
1.335     albertel 3185:     if ($home eq 'no_host') {
                   3186:         return 'not_found';
1.1       albertel 3187:     }
                   3188:     my $answer=reply("sub:$fname",$home);
1.64      www      3189:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3190: 	$answer.=' by '.$home;
                   3191:     }
1.1       albertel 3192:     return $answer;
                   3193: }
                   3194:     
1.8       www      3195: # -------------------------------------------------------------- Replicate file
                   3196: 
                   3197: sub repcopy {
                   3198:     my $filename=shift;
1.23      www      3199:     $filename=~s/\/+/\//g;
1.1142    raeburn  3200:     my $londocroot = $perlvar{'lonDocRoot'};
                   3201:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3202:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3203:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3204: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3205: 	return &repcopy_userfile($filename);
                   3206:     }
1.532     albertel 3207:     $filename=~s/[\n\r]//g;
1.8       www      3208:     my $transname="$filename.in.transfer";
1.828     www      3209: # FIXME: this should flock
1.607     raeburn  3210:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3211:     my $remoteurl=subscribe($filename);
1.64      www      3212:     if ($remoteurl =~ /^con_lost by/) {
                   3213: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3214:            return 'unavailable';
1.8       www      3215:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3216: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3217: 	   return 'not_found';
1.64      www      3218:     } elsif ($remoteurl =~ /^rejected by/) {
                   3219: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3220:            return 'forbidden';
1.20      www      3221:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3222:            return 'ok';
1.8       www      3223:     } else {
1.290     www      3224:         my $author=$filename;
                   3225:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3226:         my ($udom,$uname)=split(/\//,$author);
                   3227:         my $home=homeserver($uname,$udom);
                   3228:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3229:            my @parts=split(/\//,$filename);
                   3230:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3231:            if ($path ne "$londocroot/res") {
1.8       www      3232:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3233: 	       return 'bad_request';
1.8       www      3234:            }
                   3235:            my $count;
                   3236:            for ($count=5;$count<$#parts;$count++) {
                   3237:                $path.="/$parts[$count]";
                   3238:                if ((-e $path)!=1) {
                   3239: 		   mkdir($path,0777);
                   3240:                }
                   3241:            }
                   3242:            my $ua=new LWP::UserAgent;
                   3243:            my $request=new HTTP::Request('GET',"$remoteurl");
                   3244:            my $response=$ua->request($request,$transname);
                   3245:            if ($response->is_error()) {
                   3246: 	       unlink($transname);
                   3247:                my $message=$response->status_line;
1.672     albertel 3248:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3249:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3250:                return 'unavailable';
1.8       www      3251:            } else {
1.16      www      3252: 	       if ($remoteurl!~/\.meta$/) {
                   3253:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   3254:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   3255:                   if ($mresponse->is_error()) {
                   3256: 		      unlink($filename.'.meta');
                   3257:                       &logthis(
1.672     albertel 3258:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3259:                   }
                   3260: 	       }
1.8       www      3261:                rename($transname,$filename);
1.607     raeburn  3262:                return 'ok';
1.8       www      3263:            }
1.290     www      3264:        }
1.8       www      3265:     }
1.330     www      3266: }
                   3267: 
1.1172.2.124  raeburn  3268: # ------------------------------------------------- Unsubscribe from a resource
                   3269: 
                   3270: sub unsubscribe {
                   3271:     my ($fname) = @_;
                   3272:     my $answer;
                   3273:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3274:     $fname=~s/[\n\r]//g;
                   3275:     my $author=$fname;
                   3276:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3277:     my ($udom,$uname)=split(/\//,$author);
                   3278:     my $home=homeserver($uname,$udom);
                   3279:     if ($home eq 'no_host') {
                   3280:         $answer = 'no_host';
                   3281:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3282:         $answer = 'home';
                   3283:     } else {
1.1172.2.125  raeburn  3284:         $answer = reply("unsub:$fname",$home);
1.1172.2.124  raeburn  3285:     }
                   3286:     return $answer;
                   3287: }
                   3288: 
1.330     www      3289: # ------------------------------------------------ Get server side include body
                   3290: sub ssi_body {
1.381     albertel 3291:     my ($filelink,%form)=@_;
1.606     matthew  3292:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3293:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3294:     }
1.953     www      3295:     my $output='';
                   3296:     my $response;
1.980     raeburn  3297:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3298:        ($output,$response)=&externalssi($filelink);
1.953     www      3299:     } else {
1.1004    droeschl 3300:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3301:        $filelink .= 'inhibitmenu=yes';
1.953     www      3302:        ($output,$response)=&ssi($filelink,%form);
                   3303:     }
1.778     albertel 3304:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3305:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3306:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3307:     if (wantarray) {
                   3308:         return ($output, $response);
                   3309:     } else {
                   3310:         return $output;
                   3311:     }
1.8       www      3312: }
                   3313: 
1.15      www      3314: # --------------------------------------------------------- Server Side Include
                   3315: 
1.782     albertel 3316: sub absolute_url {
1.1172.2.145  raeburn  3317:     my ($host_name,$unalias,$keep_proto) = @_;
1.782     albertel 3318:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3319:     if ($host_name eq '') {
                   3320: 	$host_name = $ENV{'SERVER_NAME'};
                   3321:     }
1.1172.2.145  raeburn  3322:     if ($unalias) {
                   3323:         my $alias = &get_proxy_alias();
                   3324:         if ($alias eq $host_name) {
                   3325:             my $lonhost = $perlvar{'lonHostID'};
                   3326:             my $hostname = &hostname($lonhost);
                   3327:             my $lcproto;
                   3328:             if (($keep_proto) || ($hostname eq '')) {
                   3329:                 $lcproto = $protocol;
                   3330:             } else {
                   3331:                 $lcproto = $protocol{$lonhost};
                   3332:                 $lcproto = 'http' if ($lcproto ne 'https');
                   3333:                 $lcproto .= '://';
                   3334:             }
                   3335:             unless ($hostname eq '') {
                   3336:                 return $lcproto.$hostname;
                   3337:             }
                   3338:         }
                   3339:     } 
1.782     albertel 3340:     return $protocol.$host_name;
                   3341: }
                   3342: 
1.942     foxr     3343: #
                   3344: #   Server side include.
                   3345: # Parameters:
                   3346: #  fn     Possibly encrypted resource name/id.
                   3347: #  form   Hash that describes how the rendering should be done
                   3348: #         and other things.
1.944     foxr     3349: # Returns:
1.950     raeburn  3350: #   Scalar context: The content of the response.
                   3351: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3352: #     
1.15      www      3353: sub ssi {
                   3354: 
1.944     foxr     3355:     my ($fn,%form)=@_;
1.1172.2.145  raeburn  3356:     my ($host,$request,$response);
                   3357:     $host = &absolute_url('',1);
1.711     albertel 3358: 
                   3359:     $form{'no_update_last_known'}=1;
1.895     albertel 3360:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3361:     if (%form) {
1.1172.2.145  raeburn  3362:       $request=new HTTP::Request('POST',$host.$fn);
1.1172.2.58  raeburn  3363:       $request->content(join('&',map {
                   3364:             my $name = escape($_);
                   3365:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3366:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3367:             : &escape($form{$_}) );
                   3368:         } keys(%form)));
1.23      www      3369:     } else {
1.1172.2.145  raeburn  3370:       $request=new HTTP::Request('GET',$host.$fn);
1.23      www      3371:     }
                   3372: 
1.15      www      3373:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3374: 
1.1172.2.101  raeburn  3375:     if (($env{'request.course.id'}) &&
                   3376:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3377:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3378:         ($form{'grade_symb'} ne '') &&
                   3379:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3380:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3381:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3382:             my $ua=new LWP::UserAgent;
                   3383:             $ua->local_address('127.0.0.1');
                   3384:             $response = $ua->request($request);
                   3385:         } else {
                   3386:             {
                   3387:                 require LWP::Protocol::http;
                   3388:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3389:                 my $ua=new LWP::UserAgent;
                   3390:                 $response = $ua->request($request);
                   3391:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3392:             }
                   3393:         }
                   3394:     } else {
                   3395:         my $ua=new LWP::UserAgent;
                   3396:         $response = $ua->request($request);
                   3397:     }
1.944     foxr     3398:     if (wantarray) {
1.1172.2.3  raeburn  3399: 	return ($response->content, $response);
1.944     foxr     3400:     } else {
1.1172.2.3  raeburn  3401: 	return $response->content;
1.942     foxr     3402:     }
1.324     www      3403: }
                   3404: 
                   3405: sub externalssi {
                   3406:     my ($url)=@_;
                   3407:     my $ua=new LWP::UserAgent;
                   3408:     my $request=new HTTP::Request('GET',$url);
                   3409:     my $response=$ua->request($request);
1.954     raeburn  3410:     if (wantarray) {
                   3411:         return ($response->content, $response);
                   3412:     } else {
                   3413:         return $response->content;
                   3414:     }
1.15      www      3415: }
1.254     www      3416: 
1.1172.2.98  raeburn  3417: # If the local copy of a replicated resource is outdated, trigger a
                   3418: # connection from the homeserver to flush the delayed queue. If no update
                   3419: # happens, remove local copies of outdated resource (and corresponding
                   3420: # metadata file).
                   3421: 
                   3422: sub remove_stale_resfile {
                   3423:     my ($url) = @_;
                   3424:     my $removed;
                   3425:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3426:         my $audom = $1;
                   3427:         my $auname = $2;
                   3428:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3429:             my $homeserver = &homeserver($auname,$audom);
                   3430:             unless (($homeserver eq 'no_host') ||
                   3431:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3432:                 my $fname = &filelocation('',$url);
                   3433:                 if (-e $fname) {
                   3434:                     my $hostname = &hostname($homeserver);
                   3435:                     if ($hostname) {
1.1172.2.120  raeburn  3436:                         my $protocol = $protocol{$homeserver};
                   3437:                         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98  raeburn  3438:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.120  raeburn  3439:                         my $ua=new LWP::UserAgent;
                   3440:                         $ua->timeout(5);
1.1172.2.98  raeburn  3441:                         my $request=new HTTP::Request('HEAD',$uri);
                   3442:                         my $response=$ua->request($request);
                   3443:                         if ($response->is_success()) {
                   3444:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3445:                             my $locmodtime = (stat($fname))[9];
                   3446:                             if ($locmodtime < $remmodtime) {
                   3447:                                 my $stale;
                   3448:                                 my $answer = &reply('pong',$homeserver);
                   3449:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3450:                                     sleep(0.2);
                   3451:                                     $locmodtime = (stat($fname))[9];
                   3452:                                     if ($locmodtime < $remmodtime) {
                   3453:                                         my $posstransfer = $fname.'.in.transfer';
                   3454:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3455:                                             $removed = 1;
                   3456:                                         } else {
                   3457:                                             $stale = 1;
                   3458:                                         }
                   3459:                                     } else {
                   3460:                                         $removed = 1;
                   3461:                                     }
                   3462:                                 } else {
                   3463:                                     $stale = 1;
                   3464:                                 }
                   3465:                                 if ($stale) {
1.1172.2.124  raeburn  3466:                                     if (unlink($fname)) {
                   3467:                                         if ($uri!~/\.meta$/) {
                   3468:                                             if (-e $fname.'.meta') {
                   3469:                                                 unlink($fname.'.meta');
                   3470:                                             }
                   3471:                                         }
                   3472:                                         my $unsubresult = &unsubscribe($fname);
                   3473:                                         unless ($unsubresult eq 'ok') {
                   3474:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3475:                                         }
                   3476:                                         $removed = 1;
1.1172.2.98  raeburn  3477:                                     }
                   3478:                                 }
                   3479:                             }
                   3480:                         }
                   3481:                     }
                   3482:                 }
                   3483:             }
                   3484:         }
                   3485:     }
                   3486:     return $removed;
                   3487: }
                   3488: 
1.492     albertel 3489: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3490: 
                   3491: sub allowuploaded {
                   3492:     my ($srcurl,$url)=@_;
                   3493:     $url=&clutter(&declutter($url));
                   3494:     my $dir=$url;
                   3495:     $dir=~s/\/[^\/]+$//;
                   3496:     my %httpref=();
                   3497:     my $httpurl=&hreflocation('',$url);
                   3498:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3499:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3500: }
1.477     raeburn  3501: 
1.1172.2.13  raeburn  3502: #
                   3503: # Determine if the current user should be able to edit a particular resource,
                   3504: # when viewing in course context.
                   3505: # (a) When viewing resource used to determine if "Edit" item is included in
                   3506: #     Functions.
                   3507: # (b) When displaying folder contents in course editor, used to determine if
                   3508: #     "Edit" link will be displayed alongside resource.
                   3509: #
                   3510: #  input: six args -- filename (decluttered), course number, course domain,
                   3511: #                   url, symb (if registered) and group (if this is a group
                   3512: #                   item -- e.g., bulletin board, group page etc.).
                   3513: #  output: array of five scalars --
                   3514: #          $cfile -- url for file editing if editable on current server
                   3515: #          $home -- homeserver of resource (i.e., for author if published,
                   3516: #                                           or course if uploaded.).
                   3517: #          $switchserver --  1 if server switch will be needed.
                   3518: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3519: #          $forceview -- 1 if icon/link should be to go to view mode
                   3520: #
                   3521: 
                   3522: sub can_edit_resource {
                   3523:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3524:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3525: #
                   3526: # For aboutme pages user can only edit his/her own.
                   3527: #
                   3528:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3529:         my ($sdom,$sname) = ($1,$2);
                   3530:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3531:             $home = $env{'user.home'};
                   3532:             $cfile = $resurl;
                   3533:             if ($env{'form.forceedit'}) {
                   3534:                 $forceview = 1;
                   3535:             } else {
                   3536:                 $forceedit = 1;
                   3537:             }
                   3538:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3539:         } else {
                   3540:             return;
                   3541:         }
                   3542:     }
                   3543: 
                   3544:     if ($env{'request.course.id'}) {
                   3545:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3546:         if ($group ne '') {
                   3547: # if this is a group homepage or group bulletin board, check group privs
                   3548:             my $allowed = 0;
                   3549:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3550:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3551:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3552:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3553:                     $allowed = 1;
                   3554:                 }
                   3555:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3556:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3557:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3558:                     $allowed = 1;
                   3559:                 }
                   3560:             }
                   3561:             if ($allowed) {
                   3562:                 $home=&homeserver($cnum,$cdom);
                   3563:                 if ($env{'form.forceedit'}) {
                   3564:                     $forceview = 1;
                   3565:                 } else {
                   3566:                     $forceedit = 1;
                   3567:                 }
                   3568:                 $cfile = $resurl;
                   3569:             } else {
                   3570:                 return;
                   3571:             }
                   3572:         } else {
1.1172.2.15  raeburn  3573:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3574:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3575:                     return;
                   3576:                 }
                   3577:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3578: #
                   3579: # No edit allowed where CC has switched to student role.
                   3580: #
                   3581:                 return;
                   3582:             }
                   3583:         }
                   3584:     }
                   3585: 
                   3586:     if ($file ne '') {
                   3587:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3588:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3589:                 $uploaded = 1;
                   3590:                 $incourse = 1;
                   3591:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3592:                     $cfile = &hreflocation('',$file);
                   3593:                     if ($env{'form.forceedit'}) {
                   3594:                         $forceview = 1;
                   3595:                     } else {
                   3596:                         $forceedit = 1;
                   3597:                     }
                   3598:                 }
                   3599:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3600:                 $incourse = 1;
                   3601:                 if ($env{'form.forceedit'}) {
                   3602:                     $forceview = 1;
                   3603:                 } else {
                   3604:                     $forceedit = 1;
                   3605:                 }
                   3606:                 $cfile = $resurl;
                   3607:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3608:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3609:                     $incourse = 1;
                   3610:                     if ($env{'form.forceedit'}) {
                   3611:                         $forceview = 1;
                   3612:                     } else {
                   3613:                         $forceedit = 1;
                   3614:                     }
                   3615:                     $cfile = $resurl;
                   3616:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3617:                     $incourse = 1;
                   3618:                     $cfile = $resurl.'/smpedit';
                   3619:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3620:                     $incourse = 1;
                   3621:                     if ($env{'form.forceedit'}) {
                   3622:                         $forceview = 1;
                   3623:                     } else {
                   3624:                         $forceedit = 1;
                   3625:                     }
                   3626:                     $cfile = $resurl;
1.1172.2.122  raeburn  3627:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3628:                     my ($map,$id,$res) = &decode_symb($symb);
                   3629:                     if ($map =~ /\.page$/) {
                   3630:                         $incourse = 1;
                   3631:                         if ($env{'form.forceedit'}) {
                   3632:                             $forceview = 1;
                   3633:                             $cfile = $map;
                   3634:                         } else {
                   3635:                             $forceedit = 1;
                   3636:                             $cfile =  '/adm/wrapper'.$resurl;
                   3637:                         }
                   3638:                     }
1.1172.2.146.  .1(raebu 3639:22):                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3640:22):                     $incourse = 1;
                   3641:22):                     if ($env{'form.forceedit'}) {
                   3642:22):                         $forceview = 1;
                   3643:22):                     } else {
                   3644:22):                         $forceedit = 1;
                   3645:22):                     }
                   3646:22):                     $cfile = $resurl;
1.1172.2.15  raeburn  3647:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3648:                     $incourse = 1;
                   3649:                     if ($env{'form.forceedit'}) {
                   3650:                         $forceview = 1;
                   3651:                     } else {
                   3652:                         $forceedit = 1;
                   3653:                     }
                   3654:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3655:                 }
                   3656:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3657:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3658:                 if (&is_on_map($template)) {
                   3659:                     $incourse = 1;
                   3660:                     $forceview = 1;
                   3661:                     $cfile = $template;
                   3662:                 }
                   3663:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118  raeburn  3664:                 $incourse = 1;
                   3665:                 if ($env{'form.forceedit'}) {
                   3666:                     $forceview = 1;
                   3667:                 } else {
                   3668:                     $forceedit = 1;
                   3669:                 }
                   3670:                 $cfile = $resurl;
1.1172.2.146.  .1(raebu 3671:22):             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3672:22):                 $incourse = 1;
                   3673:22):                 if ($env{'form.forceedit'}) {
                   3674:22):                     $forceview = 1;
                   3675:22):                 } else {
                   3676:22):                     $forceedit = 1;
                   3677:22):                 }
                   3678:22):                 $cfile = $resurl;
1.1172.2.13  raeburn  3679:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3680:                 $incourse = 1;
                   3681:                 $forceview = 1;
                   3682:                 if ($symb) {
                   3683:                     my ($map,$id,$res)=&decode_symb($symb);
                   3684:                     $env{'request.symb'} = $symb;
                   3685:                     $cfile = &clutter($res);
                   3686:                 } else {
                   3687:                     $cfile = $env{'form.suppurl'};
1.1172.2.146.  .1(raebu 3688:22):                     my $escfile = &unescape($cfile);
                   3689:22):                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3690:22):                         $cfile = '/adm/wrapper'.$escfile;
                   3691:22):                     } else {
                   3692:22):                         $escfile =~ s{^http://}{};
                   3693:22):                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3694:22):                     }
1.1172.2.13  raeburn  3695:                 }
1.1172.2.31  raeburn  3696:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3697:                 if ($env{'form.forceedit'}) {
                   3698:                     $forceview = 1;
                   3699:                 } else {
                   3700:                     $forceedit = 1;
                   3701:                 }
                   3702:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3703:             }
                   3704:         }
                   3705:         if ($uploaded || $incourse) {
                   3706:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3707:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3708:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3709:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3710:             # Check that the user has permission to edit this resource
                   3711:             my $setpriv = 1;
                   3712:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3713:             if (defined($cfudom)) {
                   3714:                 $home=&homeserver($cfuname,$cfudom);
                   3715:                 $cfile=$file;
                   3716:             }
                   3717:         }
                   3718:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3719:             (($home ne '') && ($home ne 'no_host'))) {
                   3720:             my @ids=&current_machine_ids();
                   3721:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3722:                 $switchserver=1;
                   3723:             }
                   3724:         }
                   3725:     }
                   3726:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3727: }
                   3728: 
                   3729: sub is_course_upload {
                   3730:     my ($file,$cnum,$cdom) = @_;
                   3731:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3732:     $uploadpath =~ s{^\/}{};
                   3733:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3734:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3735:         return 1;
                   3736:     }
                   3737:     return;
                   3738: }
                   3739: 
                   3740: sub in_course {
                   3741:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3742:     if ($hideprivileged) {
                   3743:         my $skipuser;
1.1172.2.23  raeburn  3744:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3745:         my @possdoms = ($cdom);
                   3746:         if ($coursehash{'checkforpriv'}) {
                   3747:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3748:         }
                   3749:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3750:             $skipuser = 1;
                   3751:             if ($coursehash{'nothideprivileged'}) {
                   3752:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3753:                     my $user;
                   3754:                     if ($item =~ /:/) {
                   3755:                         $user = $item;
                   3756:                     } else {
                   3757:                         $user = join(':',split(/[\@]/,$item));
                   3758:                     }
                   3759:                     if ($user eq $uname.':'.$udom) {
                   3760:                         undef($skipuser);
                   3761:                         last;
                   3762:                     }
                   3763:                 }
                   3764:             }
                   3765:             if ($skipuser) {
                   3766:                 return 0;
                   3767:             }
                   3768:         }
                   3769:     }
                   3770:     $type ||= 'any';
                   3771:     if (!defined($cdom) || !defined($cnum)) {
                   3772:         my $cid  = $env{'request.course.id'};
                   3773:         $cdom = $env{'course.'.$cid.'.domain'};
                   3774:         $cnum = $env{'course.'.$cid.'.num'};
                   3775:     }
                   3776:     my $typesref;
                   3777:     if (($type eq 'any') || ($type eq 'all')) {
                   3778:         $typesref = ['active','previous','future'];
                   3779:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3780:         $typesref = [$type];
                   3781:     }
                   3782:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3783:                               $typesref,undef,[$cdom]);
                   3784:     my ($tmp) = keys(%roles);
                   3785:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3786:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3787:     if (@course_roles > 0) {
                   3788:         return 1;
                   3789:     }
                   3790:     return 0;
                   3791: }
                   3792: 
1.478     albertel 3793: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3794: # input: action, courseID, current domain, intended
1.637     raeburn  3795: #        path to file, source of file, instruction to parse file for objects,
                   3796: #        ref to hash for embedded objects,
                   3797: #        ref to hash for codebase of java objects.
1.1095    raeburn  3798: #        reference to scalar to accommodate mime type determined
                   3799: #          from File::MMagic if $parser = parse.
1.637     raeburn  3800: #
1.485     raeburn  3801: # output: url to file (if action was uploaddoc), 
                   3802: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3803: #
1.478     albertel 3804: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3805: # course.
1.477     raeburn  3806: #
1.478     albertel 3807: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3808: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3809: #          course's home server.
1.477     raeburn  3810: #
1.478     albertel 3811: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3812: #          be copied from $source (current location) to 
                   3813: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3814: #         and will then be copied to
                   3815: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3816: #         course's home server.
1.485     raeburn  3817: #
1.481     raeburn  3818: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3819: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3820: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3821: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3822: #         in course's home server.
1.637     raeburn  3823: #
1.477     raeburn  3824: 
                   3825: sub process_coursefile {
1.1095    raeburn  3826:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3827:         $mimetype)=@_;
1.477     raeburn  3828:     my $fetchresult;
1.638     albertel 3829:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3830:     if ($action eq 'propagate') {
1.638     albertel 3831:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3832: 			     $home);
1.481     raeburn  3833:     } else {
1.477     raeburn  3834:         my $fpath = '';
                   3835:         my $fname = $file;
1.478     albertel 3836:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3837:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3838:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3839:         if ($action eq 'copy') {
                   3840:             if ($source eq '') {
                   3841:                 $fetchresult = 'no source file';
                   3842:                 return $fetchresult;
                   3843:             } else {
                   3844:                 my $destination = $filepath.'/'.$fname;
                   3845:                 rename($source,$destination);
                   3846:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3847:                                  $home);
1.481     raeburn  3848:             }
                   3849:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3850:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3851:             print $fh $env{'form.'.$source};
1.481     raeburn  3852:             close($fh);
1.637     raeburn  3853:             if ($parser eq 'parse') {
1.1024    raeburn  3854:                 my $mm = new File::MMagic;
1.1095    raeburn  3855:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3856:                 if ($type eq 'text/html') {
1.1024    raeburn  3857:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3858:                     unless ($parse_result eq 'ok') {
                   3859:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3860:                     }
1.637     raeburn  3861:                 }
1.1095    raeburn  3862:                 if (ref($mimetype)) {
                   3863:                     $$mimetype = $type;
                   3864:                 } 
1.637     raeburn  3865:             }
1.477     raeburn  3866:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3867:                                  $home);
1.481     raeburn  3868:             if ($fetchresult eq 'ok') {
                   3869:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3870:             } else {
                   3871:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3872:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3873:                 return '/adm/notfound.html';
                   3874:             }
1.477     raeburn  3875:         }
                   3876:     }
1.485     raeburn  3877:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3878:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3879:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3880:     }
                   3881:     return $fetchresult;
                   3882: }
                   3883: 
1.637     raeburn  3884: sub build_filepath {
                   3885:     my ($fpath) = @_;
                   3886:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3887:     unless ($fpath eq '') {
                   3888:         my @parts=split('/',$fpath);
                   3889:         foreach my $part (@parts) {
                   3890:             $filepath.= '/'.$part;
                   3891:             if ((-e $filepath)!=1) {
                   3892:                 mkdir($filepath,0777);
                   3893:             }
                   3894:         }
                   3895:     }
                   3896:     return $filepath;
                   3897: }
                   3898: 
                   3899: sub store_edited_file {
1.638     albertel 3900:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3901:     my $file = $primary_url;
                   3902:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3903:     my $fpath = '';
                   3904:     my $fname = $file;
                   3905:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3906:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3907:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  3908:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3909:     print $fh $content;
                   3910:     close($fh);
1.638     albertel 3911:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3912:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3913: 			  $home);
1.637     raeburn  3914:     if ($$fetchresult eq 'ok') {
                   3915:         return '/uploaded/'.$fpath.'/'.$fname;
                   3916:     } else {
1.638     albertel 3917:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3918: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3919:         return '/adm/notfound.html';
                   3920:     }
                   3921: }
                   3922: 
1.531     albertel 3923: sub clean_filename {
1.831     albertel 3924:     my ($fname,$args)=@_;
1.315     www      3925: # Replace Windows backslashes by forward slashes
1.257     www      3926:     $fname=~s/\\/\//g;
1.831     albertel 3927:     if (!$args->{'keep_path'}) {
                   3928:         # Get rid of everything but the actual filename
                   3929: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3930:     }
1.315     www      3931: # Replace spaces by underscores
                   3932:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  3933: # Transliterate non-ascii text to ascii
                   3934:     my $lang = &Apache::lonlocal::current_language();
                   3935:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      3936: # Replace all other weird characters by nothing
1.831     albertel 3937:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3938: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3939: # numbers
                   3940:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1172.2.140  raeburn  3941: # Replace three or more adjacent underscores with one for consistency
                   3942: # with loncfile::filename_check() so complete url can be extracted by
                   3943: # lonnet::decode_symb()
                   3944:     $fname=~s/_{3,}/_/g;
1.531     albertel 3945:     return $fname;
                   3946: }
1.1172.2.110  raeburn  3947: 
1.1051    raeburn  3948: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3949: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3950: # image with the same aspect ratio as the original, but with dimensions which do 
                   3951: # not exceed $resizewidth and $resizeheight.
                   3952:  
1.984     neumanie 3953: sub resizeImage {
1.1051    raeburn  3954:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3955:     my $ima = Image::Magick->new;
                   3956:     my $resized;
                   3957:     if (-e $img_path) {
                   3958:         $ima->Read($img_path);
                   3959:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3960:             my $width = $ima->Get('width');
                   3961:             my $height = $ima->Get('height');
                   3962:             if ($width > $resizewidth) {
                   3963: 	        my $factor = $width/$resizewidth;
                   3964:                 my $newheight = $height/$factor;
                   3965:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3966:                 $resized = 1;
                   3967:             }
                   3968:         }
                   3969:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3970:             my $width = $ima->Get('width');
                   3971:             my $height = $ima->Get('height');
                   3972:             if ($height > $resizeheight) {
                   3973:                 my $factor = $height/$resizeheight;
                   3974:                 my $newwidth = $width/$factor;
                   3975:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3976:                 $resized = 1;
                   3977:             }
                   3978:         }
                   3979:         if ($resized) {
                   3980:             $ima->Write($img_path);
                   3981:         }
                   3982:     }
                   3983:     return;
1.977     amueller 3984: }
                   3985: 
1.608     albertel 3986: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3987: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3988: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3989: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.109  raeburn  3990: #                                    canceloverwrite, scantron or ''. 
1.1090    raeburn  3991: #                   if 'coursedoc': upload to the current course
                   3992: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3993: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3994: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3995: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  3996: #        $parser - instruction to parse file for objects ($parser = parse) or
                   3997: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   3998: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   3999: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  4000: #        $allfiles - reference to hash for embedded objects
                   4001: #        $codebase - reference to hash for codebase of java objects
                   4002: #        $desuname - username for permanent storage of uploaded file
                   4003: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  4004: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   4005: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  4006: #        $resizewidth - width (pixels) to which to resize uploaded image
                   4007: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  4008: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  4009: #                    from File::MMagic.
1.858     raeburn  4010: # 
1.686     albertel 4011: # output: url of file in userspace, or error: <message> 
                   4012: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 4013: 
1.531     albertel 4014: sub userfileupload {
1.1090    raeburn  4015:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  4016:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 4017:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 4018:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 4019:     $fname=&clean_filename($fname);
1.1090    raeburn  4020:     # See if there is anything left
1.257     www      4021:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  4022:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   4023:     if ($fname =~ /^\./) {
                   4024:         my ($s,$usec) = &gettimeofday();
                   4025:         while (length($usec) < 6) {
                   4026:             $usec = '0'.$usec;
                   4027:         }
                   4028:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   4029:     }
1.1090    raeburn  4030:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   4031:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   4032:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   4033:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  4034:         my $now = time;
1.1090    raeburn  4035:         my $filepath;
1.1095    raeburn  4036:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  4037:              $filepath = 'tmp/helprequests/'.$now;
                   4038:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   4039:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   4040:                          '_'.$env{'user.domain'}.'/pending';
                   4041:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   4042:             my ($docuname,$docudom);
1.1172.2.96  raeburn  4043:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  4044:                 $docudom = $destudom;
                   4045:             } else {
                   4046:                 $docudom = $env{'user.domain'};
                   4047:             }
1.1172.2.96  raeburn  4048:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  4049:                 $docuname = $destuname;
                   4050:             } else {
                   4051:                 $docuname = $env{'user.name'};
                   4052:             }
                   4053:             if (exists($env{'form.group'})) {
                   4054:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4055:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4056:             }
                   4057:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   4058:             if ($context eq 'canceloverwrite') {
                   4059:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   4060:                 if (-e  $tempfile) {
                   4061:                     my @info = stat($tempfile);
                   4062:                     if ($info[9] eq $env{'form.timestamp'}) {
                   4063:                         unlink($tempfile);
                   4064:                     }
                   4065:                 }
                   4066:                 return;
1.523     raeburn  4067:             }
                   4068:         }
1.1090    raeburn  4069:         # Create the directory if not present
1.741     raeburn  4070:         my @parts=split(/\//,$filepath);
                   4071:         my $fullpath = $perlvar{'lonDaemons'};
                   4072:         for (my $i=0;$i<@parts;$i++) {
                   4073:             $fullpath .= '/'.$parts[$i];
                   4074:             if ((-e $fullpath)!=1) {
                   4075:                 mkdir($fullpath,0777);
                   4076:             }
                   4077:         }
1.1172.2.96  raeburn  4078:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  4079:         print $fh $env{'form.'.$formname};
                   4080:         close($fh);
1.1090    raeburn  4081:         if ($context eq 'existingfile') {
                   4082:             my @info = stat($fullpath.'/'.$fname);
                   4083:             return ($fullpath.'/'.$fname,$info[9]);
                   4084:         } else {
                   4085:             return $fullpath.'/'.$fname;
                   4086:         }
1.523     raeburn  4087:     }
1.995     raeburn  4088:     if ($subdir eq 'scantron') {
                   4089:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  4090:     } else {
1.995     raeburn  4091:         $fname="$subdir/$fname";
                   4092:     }
1.1090    raeburn  4093:     if ($context eq 'coursedoc') {
1.638     albertel 4094: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4095: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  4096:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 4097:             return &finishuserfileupload($docuname,$docudom,
                   4098: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  4099: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  4100:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  4101:         } else {
1.1172.2.21  raeburn  4102:             if ($env{'form.folder'}) {
                   4103:                 $fname=$env{'form.folder'}.'/'.$fname;
                   4104:             }
1.638     albertel 4105:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   4106: 				       $fname,$formname,$parser,
1.1095    raeburn  4107: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  4108:         }
1.719     banghart 4109:     } elsif (defined($destuname)) {
                   4110:         my $docuname=$destuname;
                   4111:         my $docudom=$destudom;
1.860     raeburn  4112: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4113: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4114:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4115:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4116:     } else {
1.638     albertel 4117:         my $docuname=$env{'user.name'};
                   4118:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  4119:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  4120:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4121:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4122:         }
1.860     raeburn  4123: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4124: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4125:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4126:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4127:     }
1.271     www      4128: }
                   4129: 
                   4130: sub finishuserfileupload {
1.860     raeburn  4131:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  4132:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  4133:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      4134:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 4135:   
1.860     raeburn  4136:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 4137:     $file=$fname;
                   4138:     if ($fname=~m|/|) {
                   4139:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   4140: 	$path.=$fnamepath.'/';
                   4141:     }
1.259     www      4142:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      4143:     my $count;
                   4144:     for ($count=4;$count<=$#parts;$count++) {
                   4145:         $filepath.="/$parts[$count]";
                   4146:         if ((-e $filepath)!=1) {
                   4147: 	    mkdir($filepath,0777);
                   4148:         }
                   4149:     }
1.984     neumanie 4150: 
1.258     www      4151: # Save the file
                   4152:     {
1.1172.2.96  raeburn  4153: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4154: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4155: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4156: 	    return '/adm/notfound.html';
                   4157: 	}
1.1090    raeburn  4158:         if ($context eq 'overwrite') {
1.1117    foxr     4159:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4160:             my $target = $filepath.'/'.$file;
                   4161:             if (-e $source) {
                   4162:                 my @info = stat($source);
                   4163:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4164:                     unless (&File::Copy::move($source,$target)) {
                   4165:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4166:                         return "Moving from $source failed";
                   4167:                     }
                   4168:                 } else {
                   4169:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4170:                 }
                   4171:             } else {
                   4172:                 return "Temporary file: $source missing";
                   4173:             }
                   4174:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4175: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4176: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4177: 	    return '/adm/notfound.html';
                   4178: 	}
1.570     albertel 4179: 	close(FH);
1.1051    raeburn  4180:         if ($resizewidth && $resizeheight) {
                   4181:             my $mm = new File::MMagic;
                   4182:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4183:             if ($mime_type =~ m{^image/}) {
                   4184: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4185:             }  
1.977     amueller 4186: 	}
1.258     www      4187:     }
1.1152    raeburn  4188:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4189:         if (ref($mimetype)) {
                   4190:             if ($$mimetype eq '') {
                   4191:                 my $mm = new File::MMagic;
                   4192:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4193:                 $$mimetype = $type;
                   4194:             }
                   4195:         }
                   4196:     }
1.1172.2.109  raeburn  4197:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4198:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4199:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4200:                                                        $allfiles,$codebase);
                   4201:             unless ($parse_result eq 'ok') {
                   4202:                 &logthis('Failed to parse '.$filepath.$file.
                   4203: 	   	         ' for embedded media: '.$parse_result); 
                   4204:             }
1.637     raeburn  4205:         }
1.1172.2.109  raeburn  4206:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4207:         my $format = $env{'form.scantron_format'};
                   4208:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4209:     }
1.860     raeburn  4210:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4211:         my $input = $filepath.'/'.$file;
                   4212:         my $output = $filepath.'/'.'tn-'.$file;
                   4213:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.96  raeburn  4214:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4215:         system({$args[0]} @args);
1.860     raeburn  4216:         if (-e $filepath.'/'.'tn-'.$file) {
                   4217:             $fetchthumb  = 1; 
                   4218:         }
                   4219:     }
1.858     raeburn  4220:  
1.259     www      4221: # Notify homeserver to grep it
                   4222: #
1.984     neumanie 4223:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4224:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4225:     if ($fetchresult eq 'ok') {
1.860     raeburn  4226:         if ($fetchthumb) {
                   4227:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4228:             if ($thumbresult ne 'ok') {
                   4229:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4230:                          $docuhome.': '.$thumbresult);
                   4231:             }
                   4232:         }
1.259     www      4233: #
1.258     www      4234: # Return the URL to it
1.494     albertel 4235:         return '/uploaded/'.$path.$file;
1.263     www      4236:     } else {
1.494     albertel 4237:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4238: 		 ': '.$fetchresult);
1.263     www      4239:         return '/adm/notfound.html';
1.858     raeburn  4240:     }
1.493     albertel 4241: }
                   4242: 
1.637     raeburn  4243: sub extract_embedded_items {
1.961     raeburn  4244:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4245:     my @state = ();
1.1164    raeburn  4246:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4247:     my %javafiles = (
                   4248:                       codebase => '',
                   4249:                       code => '',
                   4250:                       archive => ''
                   4251:                     );
                   4252:     my %mediafiles = (
                   4253:                       src => '',
                   4254:                       movie => '',
                   4255:                      );
1.648     raeburn  4256:     my $p;
                   4257:     if ($content) {
                   4258:         $p = HTML::LCParser->new($content);
                   4259:     } else {
1.961     raeburn  4260:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4261:     }
1.641     albertel 4262:     while (my $t=$p->get_token()) {
1.640     albertel 4263: 	if ($t->[0] eq 'S') {
                   4264: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4265: 	    push(@state, $tagname);
1.648     raeburn  4266:             if (lc($tagname) eq 'allow') {
                   4267:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4268:             }
1.640     albertel 4269: 	    if (lc($tagname) eq 'img') {
                   4270: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4271: 	    }
1.886     albertel 4272: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  4273:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   4274: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   4275:                 }
1.886     albertel 4276: 	    }
1.645     raeburn  4277:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4278:                 my $src;
1.645     raeburn  4279:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4280:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4281:                 } else {
1.1164    raeburn  4282:                     if ($attr->{'src'} ne '') {
                   4283:                         $src = $attr->{'src'};
                   4284:                         &add_filetype($allfiles,$src,'src');
                   4285:                     }
                   4286:                 }
                   4287:                 my $text = $p->get_trimmed_text();
                   4288:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4289:                     my @swfargs = split(/,/,$1);
                   4290:                     foreach my $item (@swfargs) {
                   4291:                         $item =~ s/["']//g;
                   4292:                         $item =~ s/^\s+//;
                   4293:                         $item =~ s/\s+$//;
                   4294:                     }
                   4295:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4296:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4297:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4298:                         } else {
                   4299:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4300:                         }
                   4301:                     }
1.645     raeburn  4302:                 }
                   4303:             }
                   4304:             if (lc($tagname) eq 'link') {
                   4305:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4306:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4307:                 }
                   4308:             }
1.640     albertel 4309: 	    if (lc($tagname) eq 'object' ||
                   4310: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4311: 		foreach my $item (keys(%javafiles)) {
                   4312: 		    $javafiles{$item} = '';
                   4313: 		}
1.1164    raeburn  4314:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4315:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4316:                 }
1.640     albertel 4317: 	    }
                   4318: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4319: 		my $name = lc($attr->{'name'});
                   4320: 		foreach my $item (keys(%javafiles)) {
                   4321: 		    if ($name eq $item) {
                   4322: 			$javafiles{$item} = $attr->{'value'};
                   4323: 			last;
                   4324: 		    }
                   4325: 		}
1.1164    raeburn  4326:                 my $pathfrom;
1.640     albertel 4327: 		foreach my $item (keys(%mediafiles)) {
                   4328: 		    if ($name eq $item) {
1.1164    raeburn  4329:                         $pathfrom = $attr->{'value'};
                   4330:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4331: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4332: 			last;
                   4333: 		    }
                   4334: 		}
1.1164    raeburn  4335:                 if ($name eq 'flashvars') {
                   4336:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4337:                 }
                   4338:                 if ($pathfrom ne '') {
                   4339:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4340:                                          $pathfrom);
                   4341:                 }
1.640     albertel 4342: 	    }
                   4343: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4344: 		foreach my $item (keys(%javafiles)) {
                   4345: 		    if ($attr->{$item}) {
                   4346: 			$javafiles{$item} = $attr->{$item};
                   4347: 			last;
                   4348: 		    }
                   4349: 		}
                   4350: 		foreach my $item (keys(%mediafiles)) {
                   4351: 		    if ($attr->{$item}) {
                   4352: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4353: 			last;
                   4354: 		    }
                   4355: 		}
1.1164    raeburn  4356:                 if (lc($tagname) eq 'embed') {
                   4357:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4358:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4359:                                              $attr->{'src'});
                   4360:                     }
                   4361:                 }
1.640     albertel 4362: 	    }
1.1172.2.35  raeburn  4363:             if (lc($tagname) eq 'iframe') {
                   4364:                 my $src = $attr->{'src'} ;
                   4365:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4366:                     &add_filetype($allfiles,$src,'src');
                   4367:                 } elsif ($src =~ m{^/}) {
                   4368:                     if ($env{'request.course.id'}) {
                   4369:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4370:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4371:                         my $url = &hreflocation('',$fullpath);
                   4372:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4373:                             my $relpath = $1;
                   4374:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4375:                                 &add_filetype($allfiles,$1,'src');
                   4376:                             }
                   4377:                         }
                   4378:                     }
                   4379:                 }
                   4380:             }
1.1164    raeburn  4381:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4382:                 pop(@state);
1.1164    raeburn  4383:             }
1.640     albertel 4384: 	} elsif ($t->[0] eq 'E') {
                   4385: 	    my ($tagname) = ($t->[1]);
                   4386: 	    if ($javafiles{'codebase'} ne '') {
                   4387: 		$javafiles{'codebase'} .= '/';
                   4388: 	    }  
                   4389: 	    if (lc($tagname) eq 'applet' ||
                   4390: 		lc($tagname) eq 'object' ||
                   4391: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4392: 		) {
                   4393: 		foreach my $item (keys(%javafiles)) {
                   4394: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4395: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4396: 			&add_filetype($allfiles,$file,$item);
                   4397: 		    }
                   4398: 		}
                   4399: 	    } 
                   4400: 	    pop @state;
                   4401: 	}
                   4402:     }
1.1164    raeburn  4403:     foreach my $id (sort(keys(%flashvars))) {
                   4404:         if ($shockwave{$id} ne '') {
                   4405:             my @pairs = split(/\&/,$flashvars{$id});
                   4406:             foreach my $pair (@pairs) {
                   4407:                 my ($key,$value) = split(/\=/,$pair);
                   4408:                 if ($key eq 'thumb') {
                   4409:                     &add_filetype($allfiles,$value,$key);
                   4410:                 } elsif ($key eq 'content') {
                   4411:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4412:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4413:                     if ($ext ne '') {
                   4414:                         &add_filetype($allfiles,$path.$value,$ext);
                   4415:                     }
                   4416:                 }
                   4417:             }
                   4418:         }
                   4419:     }
1.637     raeburn  4420:     return 'ok';
                   4421: }
                   4422: 
1.639     albertel 4423: sub add_filetype {
                   4424:     my ($allfiles,$file,$type)=@_;
                   4425:     if (exists($allfiles->{$file})) {
                   4426: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4427: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4428: 	}
                   4429:     } else {
                   4430: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4431:     }
                   4432: }
                   4433: 
1.1164    raeburn  4434: sub embedded_dependency {
                   4435:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4436:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4437:         if (($identifier ne '') &&
                   4438:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4439:             ($pathfrom ne '')) {
                   4440:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4441:             foreach my $dep (@{$related->{$identifier}}) {
                   4442:                 &add_filetype($allfiles,$path.$dep,'object');
                   4443:             }
                   4444:         }
                   4445:     }
                   4446:     return;
                   4447: }
                   4448: 
1.1172.2.109  raeburn  4449: sub bubblesheet_converter {
                   4450:     my ($cdom,$fullpath,$config,$format) = @_;
                   4451:     if ((&domain($cdom) ne '') &&
                   4452:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4453:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4454:         my (%csvcols,%csvoptions);
                   4455:         if (ref($config->{'fields'}) eq 'HASH') {
                   4456:             %csvcols = %{$config->{'fields'}};
                   4457:         }
                   4458:         if (ref($config->{'options'}) eq 'HASH') {
                   4459:             %csvoptions = %{$config->{'options'}};
                   4460:         }
                   4461:         my %csvbynum = reverse(%csvcols);
                   4462:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4463:         if (keys(%scantronconf)) {
                   4464:             my %bynum = (
                   4465:                           $scantronconf{CODEstart} => 'CODEstart',
                   4466:                           $scantronconf{IDstart}   => 'IDstart',
                   4467:                           $scantronconf{PaperID}   => 'PaperID',
                   4468:                           $scantronconf{FirstName} => 'FirstName',
                   4469:                           $scantronconf{LastName}  => 'LastName',
                   4470:                           $scantronconf{Qstart}    => 'Qstart',
                   4471:                         );
                   4472:             my @ordered;
                   4473:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4474:                 push(@ordered,$bynum{$item});
                   4475:             }
                   4476:             my %mapstart = (
                   4477:                               CODEstart => 'CODE',
                   4478:                               IDstart   => 'ID',
                   4479:                               PaperID   => 'PaperID',
                   4480:                               FirstName => 'FirstName',
                   4481:                               LastName  => 'LastName',
                   4482:                               Qstart    => 'FirstQuestion',
                   4483:                            );
                   4484:             my %maplength = (
                   4485:                               CODEstart => 'CODElength',
                   4486:                               IDstart   => 'IDlength',
                   4487:                               PaperID   => 'PaperIDlength',
                   4488:                               FirstName => 'FirstNamelength',
                   4489:                               LastName  => 'LastNamelength',
                   4490:             );
                   4491:             if (open(my $fh,'<',$fullpath)) {
                   4492:                 my $output;
                   4493:                 my %lettdig = &letter_to_digits();
                   4494:                 my %diglett = reverse(%lettdig);
                   4495:                 my $numletts = scalar(keys(%lettdig));
                   4496:                 my $num = 0;
                   4497:                 while (my $line=<$fh>) {
                   4498:                     $num ++;
                   4499:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4500:                     $line =~ s{[\r\n]+$}{};
                   4501:                     my %found;
1.1172.2.143  raeburn  4502:                     my @values = split(/,/,$line,-1);
1.1172.2.109  raeburn  4503:                     my ($qstart,$record);
                   4504:                     for (my $i=0; $i<@values; $i++) {
                   4505:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4506:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4507:                             if ($values[$i] eq '') {
                   4508:                                 $values[$i] = $scantronconf{'Qoff'};
                   4509:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4510:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4511:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4512:                                 }
                   4513:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4514:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4515:                                     $values[$i] = $diglett{$values[$i]};
                   4516:                                 }
                   4517:                             } else {
                   4518:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4519:                                     my $digit;
                   4520:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4521:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4522:                                         if ($values[$i] eq 'J') {
                   4523:                                             $digit += $numletts;
                   4524:                                         }
                   4525:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4526:                                         $digit = $values[$i]-1;
                   4527:                                         if ($values[$i] eq '0') {
                   4528:                                             $digit += $numletts;
                   4529:                                         }
                   4530:                                     }
                   4531:                                     my $qval='';
                   4532:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4533:                                         if ($j == $digit) {
                   4534:                                             $qval .= $scantronconf{'Qon'};
                   4535:                                         } else {
                   4536:                                             $qval .= $scantronconf{'Qoff'};
                   4537:                                         }
                   4538:                                     }
                   4539:                                     $values[$i] = $qval;
                   4540:                                 }
                   4541:                             }
                   4542:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4543:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4544:                             }
                   4545:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4546:                             if ($numblank > 0) {
                   4547:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4548:                             }
                   4549:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4550:                                 $qstart = $i;
                   4551:                                 $found{$csvbynum{$i}} = $values[$i];
                   4552:                             } else {
                   4553:                                 $found{'FirstQuestion'} .= $values[$i];
                   4554:                             }
                   4555:                         } elsif (exists($csvbynum{$i})) {
                   4556:                             if ($csvoptions{'rem'}) {
                   4557:                                 $values[$i] =~ s/^\s+//;
                   4558:                             }
                   4559:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4560:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4561:                                     $values[$i] = '0'.$values[$i];
                   4562:                                 }
                   4563:                             }
                   4564:                             $found{$csvbynum{$i}} = $values[$i];
                   4565:                         }
                   4566:                     }
                   4567:                     foreach my $item (@ordered) {
                   4568:                         my $currlength = 1+length($record);
                   4569:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4570:                         if ($numspaces > 0) {
                   4571:                             $record .= (' ' x $numspaces);
                   4572:                         }
                   4573:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4574:                             unless ($item eq 'Qstart') {
                   4575:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4576:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4577:                                 }
                   4578:                             }
                   4579:                             $record .= $found{$mapstart{$item}};
                   4580:                         }
                   4581:                     }
                   4582:                     $output .= "$record\n";
                   4583:                 }
                   4584:                 close($fh);
                   4585:                 if ($output) {
                   4586:                     if (open(my $fh,'>',$fullpath)) {
                   4587:                         print $fh $output;
                   4588:                         close($fh);
                   4589:                     }
                   4590:                 }
                   4591:             }
                   4592:         }
                   4593:         return;
                   4594:     }
                   4595: }
                   4596: 
                   4597: sub letter_to_digits {
                   4598:     my %lettdig = (
                   4599:                     A => 1,
                   4600:                     B => 2,
                   4601:                     C => 3,
                   4602:                     D => 4,
                   4603:                     E => 5,
                   4604:                     F => 6,
                   4605:                     G => 7,
                   4606:                     H => 8,
                   4607:                     I => 9,
                   4608:                     J => 0,
                   4609:                   );
                   4610:     return %lettdig;
                   4611: }
                   4612: 
                   4613: sub get_scantron_config {
                   4614:     my ($which,$cdom) = @_;
                   4615:     my @lines = &get_scantronformat_file($cdom);
                   4616:     my %config;
                   4617:     #FIXME probably should move to XML it has already gotten a bit much now
                   4618:     foreach my $line (@lines) {
                   4619:         my ($name,$descrip)=split(/:/,$line);
                   4620:         if ($name ne $which ) { next; }
                   4621:         chomp($line);
                   4622:         my @config=split(/:/,$line);
                   4623:         $config{'name'}=$config[0];
                   4624:         $config{'description'}=$config[1];
                   4625:         $config{'CODElocation'}=$config[2];
                   4626:         $config{'CODEstart'}=$config[3];
                   4627:         $config{'CODElength'}=$config[4];
                   4628:         $config{'IDstart'}=$config[5];
                   4629:         $config{'IDlength'}=$config[6];
                   4630:         $config{'Qstart'}=$config[7];
                   4631:         $config{'Qlength'}=$config[8];
                   4632:         $config{'Qoff'}=$config[9];
                   4633:         $config{'Qon'}=$config[10];
                   4634:         $config{'PaperID'}=$config[11];
                   4635:         $config{'PaperIDlength'}=$config[12];
                   4636:         $config{'FirstName'}=$config[13];
                   4637:         $config{'FirstNamelength'}=$config[14];
                   4638:         $config{'LastName'}=$config[15];
                   4639:         $config{'LastNamelength'}=$config[16];
                   4640:         $config{'BubblesPerRow'}=$config[17];
                   4641:         last;
                   4642:     }
                   4643:     return %config;
                   4644: }
                   4645: 
                   4646: sub get_scantronformat_file {
                   4647:     my ($cdom) = @_;
                   4648:     if ($cdom eq '') {
                   4649:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4650:     }
                   4651:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4652:     my $gottab = 0;
                   4653:     my @lines;
                   4654:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4655:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4656:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4657:             if ($formatfile ne '-1') {
                   4658:                 @lines = split("\n",$formatfile,-1);
                   4659:                 $gottab = 1;
                   4660:             }
                   4661:         }
                   4662:     }
                   4663:     if (!$gottab) {
                   4664:         my $confname = $cdom.'-domainconfig';
                   4665:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4666:         my $formatfile = &getfile($default);
                   4667:         if ($formatfile ne '-1') {
                   4668:             @lines = split("\n",$formatfile,-1);
                   4669:             $gottab = 1;
                   4670:         }
                   4671:     }
                   4672:     if (!$gottab) {
                   4673:         my @domains = &current_machine_domains();
                   4674:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4675:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4676:                 @lines = <$fh>;
                   4677:                 close($fh);
                   4678:             }
                   4679:         } else {
                   4680:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4681:                 @lines = <$fh>;
                   4682:                 close($fh);
                   4683:             }
                   4684:         }
1.1172.2.146.  .8(raebu 4685:23):         chomp(@lines);
1.1172.2.109  raeburn  4686:     }
                   4687:     return @lines;
                   4688: }
                   4689: 
1.493     albertel 4690: sub removeuploadedurl {
1.984     neumanie 4691:     my ($url)=@_;	
                   4692:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4693:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4694: }
                   4695: 
                   4696: sub removeuserfile {
                   4697:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4698:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4699:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4700:     if ($result eq 'ok') {	
1.798     raeburn  4701:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4702:             my $metafile = $fname.'.meta';
                   4703:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4704: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4705:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4706:             my $sqlresult = 
1.823     albertel 4707:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4708:                                         'portfolio_metadata',$group,
                   4709:                                         'delete');
1.798     raeburn  4710:         }
                   4711:     }
                   4712:     return $result;
1.257     www      4713: }
1.15      www      4714: 
1.530     albertel 4715: sub mkdiruserfile {
                   4716:     my ($docuname,$docudom,$dir)=@_;
                   4717:     my $home=&homeserver($docuname,$docudom);
                   4718:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4719: }
                   4720: 
1.531     albertel 4721: sub renameuserfile {
                   4722:     my ($docuname,$docudom,$old,$new)=@_;
                   4723:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4724:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4725:                         &escape("$old").':'.&escape("$new"),$home);
                   4726:     if ($result eq 'ok') {
                   4727:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4728:             my $oldmeta = $old.'.meta';
                   4729:             my $newmeta = $new.'.meta';
                   4730:             my $metaresult = 
                   4731:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4732: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4733:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4734:             my $sqlresult = 
1.823     albertel 4735:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4736:                                         'portfolio_metadata',$group,
                   4737:                                         'delete');
1.798     raeburn  4738:         }
                   4739:     }
                   4740:     return $result;
1.531     albertel 4741: }
                   4742: 
1.14      www      4743: # ------------------------------------------------------------------------- Log
                   4744: 
                   4745: sub log {
                   4746:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4747:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4748: }
                   4749: 
                   4750: # ------------------------------------------------------------------ Course Log
1.352     www      4751: #
                   4752: # This routine flushes several buffers of non-mission-critical nature
                   4753: #
1.157     www      4754: 
                   4755: sub flushcourselogs {
1.352     www      4756:     &logthis('Flushing log buffers');
                   4757: #
                   4758: # course logs
                   4759: # This is a log of all transactions in a course, which can be used
                   4760: # for data mining purposes
                   4761: #
                   4762: # It also collects the courseid database, which lists last transaction
                   4763: # times and course titles for all courseids
                   4764: #
                   4765:     my %courseidbuffer=();
1.921     raeburn  4766:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4767:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4768: 		          &escape($courselogs{$crsid}),
                   4769: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4770: 	    delete $courselogs{$crsid};
                   4771:         } else {
                   4772:             &logthis('Failed to flush log buffer for '.$crsid);
                   4773:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4774:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4775:                         " exceeded maximum size, deleting.</font>");
                   4776:                delete $courselogs{$crsid};
                   4777:             }
1.352     www      4778:         }
1.920     raeburn  4779:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4780:             'description' => $coursedescrbuf{$crsid},
                   4781:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4782:             'type'        => $coursetypebuf{$crsid},
                   4783:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4784:         };
1.191     harris41 4785:     }
1.352     www      4786: #
                   4787: # Write course id database (reverse lookup) to homeserver of courses 
                   4788: # Is used in pickcourse
                   4789: #
1.840     albertel 4790:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4791:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4792:                                     $courseidbuffer{$crs_home},
                   4793:                                     $crs_home,'timeonly');
1.352     www      4794:     }
                   4795: #
                   4796: # File accesses
                   4797: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4798: #
1.449     matthew  4799:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4800:         if ($entry =~ /___count$/) {
                   4801:             my ($dom,$name);
1.807     albertel 4802:             ($dom,$name,undef)=
1.811     albertel 4803: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4804:             if (! defined($dom) || $dom eq '' || 
                   4805:                 ! defined($name) || $name eq '') {
1.620     albertel 4806:                 my $cid = $env{'request.course.id'};
1.1172.2.142  raeburn  4807: #
                   4808: # FIXME 11/29/2021
                   4809: # Typo in rev. 1.458 (2003/12/09)??
                   4810: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
                   4811: #
                   4812: # While these ramain as  $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
                   4813: # $dom and $name will always be null, so the &inc() call will default to storing this data
                   4814: # in a nohist_accesscount.db file for the user rather than the course.
                   4815: #
                   4816: # That said there is a lot of noise in the data being stored.
                   4817: # So counts for prtspool/  and adm/ etc. are recorded.
                   4818: #
                   4819: # A review of which items ending '___count' are written to %accesshash should likely be
                   4820: # made before deciding whether to set these to 'course.' instead of 'request.'
                   4821: #
                   4822: # Under the current scheme each user receives a nohist_accesscount.db file listing
                   4823: # accesses for things which are not published resources, regardless of course, and
                   4824: # there is not a nohist_accesscount.db file in a course, which might log accesses from
                   4825: # anyone in the course for things which are not published resources.
                   4826: #
                   4827: # For an author, nohist_accesscount.db ends up having records for other items
                   4828: # mixed up with the legitimate access counts for the author's published resources.
                   4829: #
1.620     albertel 4830:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4831:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4832:             }
1.450     matthew  4833:             my $value = $accesshash{$entry};
                   4834:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4835:             my %temphash=($url => $value);
1.449     matthew  4836:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4837:             if ($result eq 'ok') {
                   4838:                 delete $accesshash{$entry};
                   4839:             }
                   4840:         } else {
1.811     albertel 4841:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4842:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4843:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4844:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4845:                 delete $accesshash{$entry};
                   4846:             }
1.185     www      4847:         }
1.191     harris41 4848:     }
1.352     www      4849: #
                   4850: # Roles
                   4851: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4852: #
1.800     albertel 4853:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4854:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4855: 	    split(/\:/,$entry);
                   4856:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4857:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4858:                 $rudom,$runame) eq 'ok') {
                   4859: 	    delete $userrolehash{$entry};
                   4860:         }
                   4861:     }
1.662     raeburn  4862: #
1.1172.2.90  raeburn  4863: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4864: #
                   4865:     my %domrolebuffer = ();
1.1000    raeburn  4866:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4867:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4868:         if ($domrolebuffer{$rudom}) {
                   4869:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4870:                       '='.&escape($domainrolehash{$entry});
                   4871:         } else {
                   4872:             $domrolebuffer{$rudom}.=&escape($entry).
                   4873:                       '='.&escape($domainrolehash{$entry});
                   4874:         }
                   4875:         delete $domainrolehash{$entry};
                   4876:     }
                   4877:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  4878:         my %servers;
                   4879:         if (defined(&domain($dom,'primary'))) {
                   4880:             my $primary=&domain($dom,'primary');
                   4881:             my $hostname=&hostname($primary);
                   4882:             $servers{$primary} = $hostname;
                   4883:         } else {
                   4884:             %servers = &get_servers($dom,'library');
                   4885:         }
1.841     albertel 4886: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  4887: 	    if (&reply('domroleput:'.$dom.':'.
                   4888: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4889: 	        last;
                   4890: 	    } else {
1.841     albertel 4891: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4892: 	    }
1.662     raeburn  4893:         }
                   4894:     }
1.186     www      4895:     $dumpcount++;
1.157     www      4896: }
                   4897: 
                   4898: sub courselog {
                   4899:     my $what=shift;
1.158     www      4900:     $what=time.':'.$what;
1.620     albertel 4901:     unless ($env{'request.course.id'}) { return ''; }
                   4902:     $coursedombuf{$env{'request.course.id'}}=
                   4903:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4904:     $coursenumbuf{$env{'request.course.id'}}=
                   4905:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4906:     $coursehombuf{$env{'request.course.id'}}=
                   4907:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4908:     $coursedescrbuf{$env{'request.course.id'}}=
                   4909:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4910:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4911:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4912:     $courseownerbuf{$env{'request.course.id'}}=
                   4913:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4914:     $coursetypebuf{$env{'request.course.id'}}=
                   4915:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4916:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4917: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4918:     } else {
1.620     albertel 4919: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4920:     }
1.620     albertel 4921:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4922: 	&flushcourselogs();
                   4923:     }
1.158     www      4924: }
                   4925: 
                   4926: sub courseacclog {
                   4927:     my $fnsymb=shift;
1.620     albertel 4928:     unless ($env{'request.course.id'}) { return ''; }
                   4929:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4930:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4931:         $what.=':POST';
1.583     matthew  4932:         # FIXME: Probably ought to escape things....
1.800     albertel 4933: 	foreach my $key (keys(%env)) {
                   4934:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4935:                 my $formitem = $1;
                   4936:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4937:                     $what.=':'.$formitem.'='.$env{$key};
                   4938:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.131  raeburn  4939:                     if ($formitem eq 'proctorpassword') {
1.1172.2.132  raeburn  4940:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1172.2.131  raeburn  4941:                     } else {
                   4942:                         $what.=':'.$formitem.'='.$env{$key};
                   4943:                     }
1.975     raeburn  4944:                 }
1.158     www      4945:             }
1.191     harris41 4946:         }
1.583     matthew  4947:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4948:         # FIXME: We should not be depending on a form parameter that someone
                   4949:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4950:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4951:             $what.= ':POST';
                   4952:             # FIXME: Probably ought to escape things....
                   4953:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4954:                                  'crsdiscuss') {
1.620     albertel 4955:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4956:             }
                   4957:         }
1.158     www      4958:     }
                   4959:     &courselog($what);
1.149     www      4960: }
                   4961: 
1.185     www      4962: sub countacc {
                   4963:     my $url=&declutter(shift);
1.458     matthew  4964:     return if (! defined($url) || $url eq '');
1.620     albertel 4965:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4966: #
                   4967: # Mark that this url was used in this course
                   4968: #
1.620     albertel 4969:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4970: #
                   4971: # Increase the access count for this resource in this child process
                   4972: #
1.281     www      4973:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4974:     $accesshash{$key}++;
1.185     www      4975: }
1.349     www      4976: 
1.361     www      4977: sub linklog {
                   4978:     my ($from,$to)=@_;
                   4979:     $from=&declutter($from);
                   4980:     $to=&declutter($to);
                   4981:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4982:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4983: }
1.1160    www      4984: 
                   4985: sub statslog {
                   4986:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4987:     if ($users<2) { return; }
                   4988:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4989:             'course'       => $env{'request.course.id'},
                   4990:             'sections'     => '"all"',
                   4991:             'num_students' => $users,
                   4992:             'part'         => $part,
                   4993:             'symb'         => $symb,
                   4994:             'mean_tries'   => $av_attempts,
                   4995:             'deg_of_diff'  => $degdiff});
                   4996:     foreach my $key (keys(%dynstore)) {
                   4997:         $accesshash{$key}=$dynstore{$key};
                   4998:     }
                   4999: }
1.361     www      5000:   
1.349     www      5001: sub userrolelog {
                   5002:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 5003:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      5004:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5005:        $userrolehash
                   5006:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      5007:                     =$tend.':'.$tstart;
1.662     raeburn  5008:     }
1.1169    droeschl 5009:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 5010:        $userrolehash
                   5011:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   5012:                     =$tend.':'.$tstart;
                   5013:     }
1.1172.2.90  raeburn  5014:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  5015:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5016:        $domainrolehash
                   5017:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   5018:                     = $tend.':'.$tstart;
                   5019:     }
1.351     www      5020: }
                   5021: 
1.957     raeburn  5022: sub courserolelog {
                   5023:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  5024:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   5025:         my $cdom = $1;
                   5026:         my $cnum = $2;
                   5027:         my $sec = $3;
                   5028:         my $namespace = 'rolelog';
                   5029:         my %storehash = (
                   5030:                            role    => $trole,
                   5031:                            start   => $tstart,
                   5032:                            end     => $tend,
                   5033:                            selfenroll => $selfenroll,
                   5034:                            context    => $context,
                   5035:                         );
                   5036:         if ($trole eq 'gr') {
                   5037:             $namespace = 'groupslog';
                   5038:             $storehash{'group'} = $sec;
                   5039:         } else {
                   5040:             $storehash{'section'} = $sec;
                   5041:         }
                   5042:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   5043:                    $domain,$cnum,$cdom);
                   5044:         if (($trole ne 'st') || ($sec ne '')) {
                   5045:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  5046:         }
                   5047:     }
                   5048:     return;
                   5049: }
                   5050: 
1.1172.2.9  raeburn  5051: sub domainrolelog {
                   5052:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5053:     if ($area =~ m{^/($match_domain)/$}) {
                   5054:         my $cdom = $1;
                   5055:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   5056:         my $namespace = 'rolelog';
                   5057:         my %storehash = (
                   5058:                            role    => $trole,
                   5059:                            start   => $tstart,
                   5060:                            end     => $tend,
                   5061:                            context => $context,
                   5062:                         );
                   5063:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   5064:                    $domain,$domconfiguser,$cdom);
                   5065:     }
                   5066:     return;
                   5067: 
                   5068: }
                   5069: 
                   5070: sub coauthorrolelog {
                   5071:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5072:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   5073:         my $audom = $1;
                   5074:         my $auname = $2;
                   5075:         my $namespace = 'rolelog';
                   5076:         my %storehash = (
                   5077:                            role    => $trole,
                   5078:                            start   => $tstart,
                   5079:                            end     => $tend,
                   5080:                            context => $context,
                   5081:                         );
                   5082:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   5083:                    $domain,$auname,$audom);
                   5084:     }
                   5085:     return;
                   5086: }
                   5087: 
1.351     www      5088: sub get_course_adv_roles {
1.948     raeburn  5089:     my ($cid,$codes) = @_;
1.620     albertel 5090:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      5091:     my %coursehash=&coursedescription($cid);
1.988     raeburn  5092:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      5093:     my %nothide=();
1.800     albertel 5094:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  5095:         if ($user !~ /:/) {
                   5096: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   5097:         } else {
                   5098:             $nothide{$user}=1;
                   5099:         }
1.470     www      5100:     }
1.1172.2.23  raeburn  5101:     my @possdoms = ($coursehash{'domain'});
                   5102:     if ($coursehash{'checkforpriv'}) {
                   5103:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   5104:     }
1.351     www      5105:     my %returnhash=();
                   5106:     my %dumphash=
                   5107:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   5108:     my $now=time;
1.997     raeburn  5109:     my %privileged;
1.1000    raeburn  5110:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 5111: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      5112:         if (($tstart) && ($tstart<0)) { next; }
                   5113:         if (($tend) && ($tend<$now)) { next; }
                   5114:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 5115:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 5116: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  5117:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  5118:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 5119: 	if ($role eq 'cr') { next; }
1.948     raeburn  5120:         if ($codes) {
                   5121:             if ($section) { $role .= ':'.$section; }
                   5122:             if ($returnhash{$role}) {
                   5123:                 $returnhash{$role}.=','.$username.':'.$domain;
                   5124:             } else {
                   5125:                 $returnhash{$role}=$username.':'.$domain;
                   5126:             }
1.351     www      5127:         } else {
1.988     raeburn  5128:             my $key=&plaintext($role,$crstype);
1.973     bisitz   5129:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  5130:             if ($returnhash{$key}) {
                   5131: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   5132:             } else {
                   5133:                 $returnhash{$key}=$username.':'.$domain;
                   5134:             }
1.351     www      5135:         }
1.948     raeburn  5136:     }
1.400     www      5137:     return %returnhash;
                   5138: }
                   5139: 
                   5140: sub get_my_roles {
1.937     raeburn  5141:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 5142:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   5143:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  5144:     my (%dumphash,%nothide);
1.1086    raeburn  5145:     if ($context eq 'userroles') {
1.1166    raeburn  5146:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  5147:     } else {
1.1172.2.23  raeburn  5148:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  5149:         if ($hidepriv) {
                   5150:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   5151:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   5152:                 if ($user !~ /:/) {
                   5153:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   5154:                 } else {
                   5155:                     $nothide{$user} = 1;
                   5156:                 }
                   5157:             }
                   5158:         }
1.858     raeburn  5159:     }
1.400     www      5160:     my %returnhash=();
                   5161:     my $now=time;
1.999     raeburn  5162:     my %privileged;
1.800     albertel 5163:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  5164:         my ($role,$tend,$tstart);
                   5165:         if ($context eq 'userroles') {
1.1149    raeburn  5166:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  5167: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   5168:         } else {
                   5169:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   5170:         }
1.400     www      5171:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  5172:         my $status = 'active';
1.939     raeburn  5173:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  5174:             $status = 'previous';
                   5175:         } 
                   5176:         if (($tstart) && ($now<$tstart)) {
                   5177:             $status = 'future';
                   5178:         }
                   5179:         if (ref($types) eq 'ARRAY') {
                   5180:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   5181:                 next;
                   5182:             } 
                   5183:         } else {
                   5184:             if ($status ne 'active') {
                   5185:                 next;
                   5186:             }
                   5187:         }
1.867     raeburn  5188:         my ($rolecode,$username,$domain,$section,$area);
                   5189:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  5190:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5191:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5192:         } else {
                   5193:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5194:         }
1.832     raeburn  5195:         if (ref($roledoms) eq 'ARRAY') {
                   5196:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5197:                 next;
                   5198:             }
                   5199:         }
                   5200:         if (ref($roles) eq 'ARRAY') {
                   5201:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5202:                 if ($role =~ /^cr\//) {
                   5203:                     if (!grep(/^cr$/,@{$roles})) {
                   5204:                         next;
                   5205:                     }
1.1104    raeburn  5206:                 } elsif ($role =~ /^gr\//) {
                   5207:                     if (!grep(/^gr$/,@{$roles})) {
                   5208:                         next;
                   5209:                     }
1.922     raeburn  5210:                 } else {
                   5211:                     next;
                   5212:                 }
1.832     raeburn  5213:             }
1.867     raeburn  5214:         }
1.937     raeburn  5215:         if ($hidepriv) {
1.1172.2.23  raeburn  5216:             my @privroles = ('dc','su');
1.999     raeburn  5217:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  5218:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5219:             } else {
1.1172.2.23  raeburn  5220:                 my $possdoms = [$domain];
                   5221:                 if (ref($roledoms) eq 'ARRAY') {
                   5222:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  5223:                 }
1.1172.2.23  raeburn  5224:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5225:                     if (!$nothide{$username.':'.$domain}) {
                   5226:                         next;
                   5227:                     }
                   5228:                 }
1.937     raeburn  5229:             }
                   5230:         }
1.933     raeburn  5231:         if ($withsec) {
                   5232:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5233:                 $tstart.':'.$tend;
                   5234:         } else {
                   5235:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5236:         }
1.832     raeburn  5237:     }
1.373     www      5238:     return %returnhash;
1.399     www      5239: }
                   5240: 
1.1172.2.89  raeburn  5241: sub get_all_adhocroles {
                   5242:     my ($dom) = @_;
                   5243:     my @roles_by_num = ();
                   5244:     my %domdefaults = &get_domain_defaults($dom);
                   5245:     my (%description,%access_in_dom,%access_info);
                   5246:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5247:         my $count = 0;
                   5248:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5249:         my %ordered;
                   5250:         foreach my $role (sort(keys(%domcurrent))) {
                   5251:             my ($order,$desc,$access_in_dom);
                   5252:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5253:                 $order = $domcurrent{$role}{'order'};
                   5254:                 $desc = $domcurrent{$role}{'desc'};
                   5255:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5256:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5257:             }
                   5258:             if ($order eq '') {
                   5259:                 $order = $count;
                   5260:             }
                   5261:             $ordered{$order} = $role;
                   5262:             if ($desc ne '') {
                   5263:                 $description{$role} = $desc;
                   5264:             } else {
                   5265:                 $description{$role}= $role;
                   5266:             }
                   5267:             $count++;
                   5268:         }
                   5269:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5270:             push(@roles_by_num,$ordered{$item});
                   5271:         }
                   5272:     }
                   5273:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5274: }
                   5275: 
                   5276: sub get_my_adhocroles {
                   5277:     my ($cid,$checkreg) = @_;
                   5278:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5279:     if ($env{'request.course.id'} eq $cid) {
                   5280:         $cdom = $env{'course.'.$cid.'.domain'};
                   5281:         $cnum = $env{'course.'.$cid.'.num'};
                   5282:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5283:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5284:         $cdom = $1;
                   5285:         $cnum = $2;
                   5286:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5287:                                      $cdom,$cnum);
                   5288:     }
                   5289:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5290:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5291:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5292:         if ($rosterhash{$user} ne '') {
                   5293:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5294:             return ([],{}) if ($type eq 'auto');
                   5295:         }
                   5296:     }
                   5297:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5298:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5299:             my $then=$env{'user.login.time'};
                   5300:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5301:             if (!$update) {
                   5302:                 $update = $then;
                   5303:             }
                   5304:             my @liveroles;
                   5305:             foreach my $role ('dh','da') {
                   5306:                 if ($env{"user.role.$role./$cdom/"}) {
                   5307:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5308:                     my $limit = $update;
                   5309:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5310:                         $limit = $then;
                   5311:                     }
                   5312:                     my $activerole = 1;
                   5313:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5314:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5315:                     if ($activerole) {
                   5316:                         push(@liveroles,$role);
                   5317:                     }
                   5318:                 }
                   5319:             }
                   5320:             if (@liveroles) {
1.1172.2.89  raeburn  5321:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5322:                     my ($accessref,$accessinfo,%access_in_dom);
                   5323:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5324:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5325:                         if (@{$roles_by_num}) {
                   5326:                             my %settings;
                   5327:                             if ($env{'request.course.id'} eq $cid) {
                   5328:                                 foreach my $envkey (keys(%env)) {
                   5329:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5330:                                         $settings{$1} = $env{$envkey};
                   5331:                                     }
                   5332:                                 }
                   5333:                             } else {
                   5334:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5335:                             }
                   5336:                             my %setincrs;
                   5337:                             if ($settings{'internal.adhocaccess'}) {
                   5338:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5339:                             }
                   5340:                             my @statuses;
                   5341:                             if ($env{'environment.inststatus'}) {
                   5342:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5343:                             }
                   5344:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5345:                             if (ref($accessref) eq 'HASH') {
                   5346:                                 %access_in_dom = %{$accessref};
                   5347:                             }
                   5348:                             foreach my $role (@{$roles_by_num}) {
                   5349:                                 my ($curraccess,@okstatus,@personnel);
                   5350:                                 if ($setincrs{$role}) {
                   5351:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5352:                                     if ($curraccess eq 'status') {
                   5353:                                         @okstatus = split(/\&/,$rest);
                   5354:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5355:                                         @personnel = split(/\&/,$rest);
                   5356:                                     }
                   5357:                                 } else {
                   5358:                                     $curraccess = $access_in_dom{$role};
                   5359:                                     if (ref($accessinfo) eq 'HASH') {
                   5360:                                         if ($curraccess eq 'status') {
                   5361:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5362:                                                 @okstatus = @{$accessinfo->{$role}};
                   5363:                                             }
                   5364:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5365:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5366:                                                 @personnel = @{$accessinfo->{$role}};
                   5367:                                             }
                   5368:                                         }
                   5369:                                     }
                   5370:                                 }
                   5371:                                 if ($curraccess eq 'none') {
                   5372:                                     next;
                   5373:                                 } elsif ($curraccess eq 'all') {
                   5374:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5375:                                 } elsif ($curraccess eq 'dh') {
                   5376:                                     if (grep(/^dh$/,@liveroles)) {
                   5377:                                         push(@possroles,$role);
                   5378:                                     } else {
                   5379:                                         next;
                   5380:                                     }
                   5381:                                 } elsif ($curraccess eq 'da') {
                   5382:                                     if (grep(/^da$/,@liveroles)) {
                   5383:                                         push(@possroles,$role);
                   5384:                                     } else {
                   5385:                                         next;
                   5386:                                     }
1.1172.2.89  raeburn  5387:                                 } elsif ($curraccess eq 'status') {
                   5388:                                     if (@okstatus) {
                   5389:                                         if (!@statuses) {
                   5390:                                             if (grep(/^default$/,@okstatus)) {
                   5391:                                                 push(@possroles,$role);
                   5392:                                             }
                   5393:                                         } else {
                   5394:                                             foreach my $status (@okstatus) {
                   5395:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5396:                                                     push(@possroles,$role);
                   5397:                                                     last;
                   5398:                                                 }
                   5399:                                             }
                   5400:                                         }
                   5401:                                     }
                   5402:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5403:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5404:                                         if ($curraccess eq 'exc') {
                   5405:                                             push(@possroles,$role);
                   5406:                                         }
                   5407:                                     } elsif ($curraccess eq 'inc') {
                   5408:                                         push(@possroles,$role);
                   5409:                                     }
                   5410:                                 }
                   5411:                             }
                   5412:                         }
                   5413:                     }
                   5414:                 }
                   5415:             }
                   5416:         }
                   5417:     }
                   5418:     unless (ref($description) eq 'HASH') {
                   5419:         if (ref($roles_by_num) eq 'ARRAY') {
                   5420:             my %desc;
                   5421:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5422:             $description = \%desc;
                   5423:         } else {
                   5424:             $description = {};
                   5425:         }
                   5426:     }
                   5427:     return (\@possroles,$description);
                   5428: }
                   5429: 
1.399     www      5430: # ----------------------------------------------------- Frontpage Announcements
                   5431: #
                   5432: #
                   5433: 
                   5434: sub postannounce {
                   5435:     my ($server,$text)=@_;
1.844     albertel 5436:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5437:     unless ($text=~/\w/) { $text=''; }
                   5438:     return &reply('setannounce:'.&escape($text),$server);
                   5439: }
                   5440: 
                   5441: sub getannounce {
1.448     albertel 5442: 
1.1172.2.96  raeburn  5443:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5444: 	my $announcement='';
1.800     albertel 5445: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5446: 	close($fh);
1.399     www      5447: 	if ($announcement=~/\w/) { 
                   5448: 	    return 
                   5449:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5450:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5451: 	} else {
                   5452: 	    return '';
                   5453: 	}
                   5454:     } else {
                   5455: 	return '';
                   5456:     }
1.351     www      5457: }
1.353     www      5458: 
                   5459: # ---------------------------------------------------------- Course ID routines
                   5460: # Deal with domain's nohist_courseid.db files
                   5461: #
                   5462: 
                   5463: sub courseidput {
1.921     raeburn  5464:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5465:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5466:     my $outcome;
                   5467:     if ($caller eq 'timeonly') {
                   5468:         my $cids = '';
                   5469:         foreach my $item (keys(%$storehash)) {
                   5470:             $cids.=&escape($item).'&';
                   5471:         }
                   5472:         $cids=~s/\&$//;
                   5473:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5474:                           $coursehome);       
                   5475:     } else {
                   5476:         my $items = '';
                   5477:         foreach my $item (keys(%$storehash)) {
                   5478:             $items.= &escape($item).'='.
                   5479:                      &freeze_escape($$storehash{$item}).'&';
                   5480:         }
                   5481:         $items=~s/\&$//;
                   5482:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5483:                           $coursehome);
1.918     raeburn  5484:     }
                   5485:     if ($outcome eq 'unknown_cmd') {
                   5486:         my $what;
                   5487:         foreach my $cid (keys(%$storehash)) {
                   5488:             $what .= &escape($cid).'=';
1.921     raeburn  5489:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5490:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5491:             }
                   5492:             $what =~ s/\:$/&/;
                   5493:         }
                   5494:         $what =~ s/\&$//;  
                   5495:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5496:     } else {
                   5497:         return $outcome;
                   5498:     }
1.353     www      5499: }
                   5500: 
                   5501: sub courseiddump {
1.921     raeburn  5502:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5503:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5504:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5505:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5506:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5507:     my $as_hash = 1;
                   5508:     my %returnhash;
                   5509:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5510:     my %libserv = &all_library();
                   5511:     foreach my $tryserver (keys(%libserv)) {
                   5512:         if ( (  $hostidflag == 1 
                   5513: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5514: 	     || (!defined($hostidflag)) ) {
                   5515: 
1.918     raeburn  5516: 	    if (($domfilter eq '') ||
                   5517: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5518:                 my $rep;
                   5519:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5520:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5521:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5522:                                 &escape($descfilter), &escape($instcodefilter),
                   5523:                                 &escape($ownerfilter), &escape($coursefilter),
                   5524:                                 &escape($typefilter), &escape($regexp_ok),
                   5525:                                 $as_hash, &escape($selfenrollonly),
                   5526:                                 &escape($catfilter), $showhidden, $caller,
                   5527:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5528:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5529:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5530:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5531:                 } else {
                   5532:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5533:                              $sincefilter.':'.&escape($descfilter).':'.
                   5534:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5535:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5536:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5537:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5538:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5539:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5540:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5541:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5542:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5543:                 }
                   5544: 
1.918     raeburn  5545:                 my @pairs=split(/\&/,$rep);
                   5546:                 foreach my $item (@pairs) {
                   5547:                     my ($key,$value)=split(/\=/,$item,2);
                   5548:                     $key = &unescape($key);
                   5549:                     next if ($key =~ /^error: 2 /);
                   5550:                     my $result = &thaw_unescape($value);
                   5551:                     if (ref($result) eq 'HASH') {
                   5552:                         $returnhash{$key}=$result;
                   5553:                     } else {
1.921     raeburn  5554:                         my @responses = split(/:/,$value);
                   5555:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5556:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5557:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5558:                         }
1.1008    raeburn  5559:                     }
1.353     www      5560:                 }
                   5561:             }
                   5562:         }
                   5563:     }
                   5564:     return %returnhash;
                   5565: }
                   5566: 
1.1055    raeburn  5567: sub courselastaccess {
                   5568:     my ($cdom,$cnum,$hostidref) = @_;
                   5569:     my %returnhash;
                   5570:     if ($cdom && $cnum) {
                   5571:         my $chome = &homeserver($cnum,$cdom);
                   5572:         if ($chome ne 'no_host') {
                   5573:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5574:             &extract_lastaccess(\%returnhash,$rep);
                   5575:         }
                   5576:     } else {
                   5577:         if (!$cdom) { $cdom=''; }
                   5578:         my %libserv = &all_library();
                   5579:         foreach my $tryserver (keys(%libserv)) {
                   5580:             if (ref($hostidref) eq 'ARRAY') {
                   5581:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5582:             } 
                   5583:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5584:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5585:                 &extract_lastaccess(\%returnhash,$rep);
                   5586:             }
                   5587:         }
                   5588:     }
                   5589:     return %returnhash;
                   5590: }
                   5591: 
                   5592: sub extract_lastaccess {
                   5593:     my ($returnhash,$rep) = @_;
                   5594:     if (ref($returnhash) eq 'HASH') {
                   5595:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5596:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5597:                  $rep eq '') {
                   5598:             my @pairs=split(/\&/,$rep);
                   5599:             foreach my $item (@pairs) {
                   5600:                 my ($key,$value)=split(/\=/,$item,2);
                   5601:                 $key = &unescape($key);
                   5602:                 next if ($key =~ /^error: 2 /);
                   5603:                 $returnhash->{$key} = &thaw_unescape($value);
                   5604:             }
                   5605:         }
                   5606:     }
                   5607:     return;
                   5608: }
                   5609: 
1.658     raeburn  5610: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5611: 
                   5612: sub dcmailput {
1.685     raeburn  5613:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5614:     my $status = &Apache::lonnet::critical(
1.740     www      5615:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5616:        &escape($message),$server);
1.662     raeburn  5617:     return $status;
                   5618: }
                   5619: 
1.658     raeburn  5620: sub dcmaildump {
                   5621:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5622:     my %returnhash=();
1.846     albertel 5623: 
                   5624:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5625:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5626:                                                          &escape($enddate).':';
                   5627: 	my @esc_senders=map { &escape($_)} @$senders;
                   5628: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5629: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5630:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5631:             if (($key) && ($value)) {
                   5632:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5633:             }
                   5634:         }
                   5635:     }
                   5636:     return %returnhash;
                   5637: }
1.662     raeburn  5638: # ---------------------------------------------------------- Domain roles
                   5639: 
                   5640: sub get_domain_roles {
                   5641:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5642:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5643:         $startdate = '.';
                   5644:     }
1.1018    raeburn  5645:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5646:         $enddate = '.';
                   5647:     }
1.922     raeburn  5648:     my $rolelist;
                   5649:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5650:         $rolelist = join('&',@{$roles});
1.922     raeburn  5651:     }
1.662     raeburn  5652:     my %personnel = ();
1.841     albertel 5653: 
                   5654:     my %servers = &get_servers($dom,'library');
                   5655:     foreach my $tryserver (keys(%servers)) {
                   5656: 	%{$personnel{$tryserver}}=();
                   5657: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5658: 					    &escape($startdate).':'.
                   5659: 					    &escape($enddate).':'.
                   5660: 					    &escape($rolelist), $tryserver))) {
                   5661: 	    my ($key,$value) = split(/\=/,$line,2);
                   5662: 	    if (($key) && ($value)) {
                   5663: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5664: 	    }
                   5665: 	}
1.662     raeburn  5666:     }
                   5667:     return %personnel;
                   5668: }
1.658     raeburn  5669: 
1.1172.2.89  raeburn  5670: sub get_active_domroles {
                   5671:     my ($dom,$roles) = @_;
                   5672:     return () unless (ref($roles) eq 'ARRAY');
                   5673:     my $now = time;
                   5674:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5675:     my %domroles;
                   5676:     foreach my $server (keys(%dompersonnel)) {
                   5677:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5678:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5679:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5680:         }
                   5681:     }
                   5682:     return %domroles;
                   5683: }
                   5684: 
1.1057    www      5685: # ----------------------------------------------------------- Interval timing 
1.149     www      5686: 
1.1153    www      5687: {
                   5688: # Caches needed for speedup of navmaps
                   5689: # We don't want to cache this for very long at all (5 seconds at most)
                   5690: # 
                   5691: # The user for whom we cache
                   5692: my $cachedkey='';
                   5693: # The cached times for this user
                   5694: my %cachedtimes=();
                   5695: # When this was last done
1.1172.2.66  raeburn  5696: my $cachedtime='';
1.1153    www      5697: 
                   5698: sub load_all_first_access {
1.1172.2.146.  .1(raebu 5699:22):     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5700:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.146.  .1(raebu 5701:22):         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5702:22):         (!$ignorecache)) {
1.1154    raeburn  5703:         return;
                   5704:     }
                   5705:     $cachedtime=time;
                   5706:     $cachedkey=$uname.':'.$udom;
                   5707:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5708: }
                   5709: 
1.504     albertel 5710: sub get_first_access {
1.1172.2.146.  .1(raebu 5711:22):     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5712:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5713:     if ($argsymb) { $symb=$argsymb; }
                   5714:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5715:     if ($argmap) { $map = $argmap; }
1.926     albertel 5716:     if ($type eq 'course') {
                   5717: 	$res='course';
                   5718:     } elsif ($type eq 'map') {
1.588     albertel 5719: 	$res=&symbread($map);
                   5720:     } else {
                   5721: 	$res=$symb;
                   5722:     }
1.1172.2.146.  .1(raebu 5723:22):     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5724:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5725: }
                   5726: 
                   5727: sub set_first_access {
1.1162    raeburn  5728:     my ($type,$interval)=@_;
1.790     albertel 5729:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5730:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5731:     if ($type eq 'course') {
                   5732: 	$res='course';
                   5733:     } elsif ($type eq 'map') {
1.588     albertel 5734: 	$res=&symbread($map);
                   5735:     } else {
                   5736: 	$res=$symb;
                   5737:     }
1.1153    www      5738:     $cachedkey='';
1.1162    raeburn  5739:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5740:     if ($firstaccess) {
                   5741:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5742:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5743:                  "in $courseid");
                   5744:         return 'already_set';
                   5745:     } else {
1.1162    raeburn  5746:         my $start = time;
                   5747: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5748:                           $udom,$uname);
                   5749:         if ($putres eq 'ok') {
                   5750:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5751:                  $udom,$uname); 
                   5752:             &appenv(
                   5753:                      {
                   5754:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5755:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5756:                      }
                   5757:                   );
1.1172.2.97  raeburn  5758:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5759:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5760:             }
1.1172.2.102  raeburn  5761:         } elsif ($putres ne 'refused') {
                   5762:             &logthis("Result: $putres when attempting to set first access time ".
                   5763:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5764:         }
                   5765:         return $putres;
1.505     albertel 5766:     }
                   5767:     return 'already_set';
1.504     albertel 5768: }
1.1153    www      5769: }
1.1172.2.32  raeburn  5770: 
                   5771: sub checkout {
                   5772:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5773:     my $now=time;
                   5774:     my $lonhost=$perlvar{'lonHostID'};
1.1172.2.134  raeburn  5775:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5776:     my $infostr=&escape(
                   5777:                  'CHECKOUTTOKEN&'.
                   5778:                  $tuname.'&'.
                   5779:                  $tudom.'&'.
                   5780:                  $tcrsid.'&'.
                   5781:                  $symb.'&'.
1.1172.2.134  raeburn  5782:                  $now.'&'.$ip);
1.1172.2.32  raeburn  5783:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5784:     if ($token=~/^error\:/) {
                   5785:         &logthis("<font color=\"blue\">WARNING: ".
                   5786:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5787:                  "</font>");
                   5788:         return '';
                   5789:     }
                   5790: 
                   5791:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5792:     $token=~tr/a-z/A-Z/;
                   5793: 
                   5794:     my %infohash=('resource.0.outtoken' => $token,
                   5795:                   'resource.0.checkouttime' => $now,
1.1172.2.134  raeburn  5796:                   'resource.0.outremote' => $ip);
1.1172.2.32  raeburn  5797: 
                   5798:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5799:        return '';
                   5800:     } else {
                   5801:         &logthis("<font color=\"blue\">WARNING: ".
                   5802:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5803:                  "</font>");
                   5804:     }
                   5805: 
                   5806:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5807:                          &escape('Checkout '.$infostr.' - '.
                   5808:                                                  $token)) ne 'ok') {
                   5809:         return '';
                   5810:     } else {
                   5811:         &logthis("<font color=\"blue\">WARNING: ".
                   5812:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5813:                  "</font>");
                   5814:     }
                   5815:     return $token;
                   5816: }
                   5817: 
                   5818: # ------------------------------------------------------------ Check in an item
                   5819: 
                   5820: sub checkin {
                   5821:     my $token=shift;
                   5822:     my $now=time;
                   5823:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5824:     $lonhost=~tr/A-Z/a-z/;
                   5825:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5826:     $dtoken=~s/\W/\_/g;
1.1172.2.134  raeburn  5827:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5828:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5829:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5830: 
                   5831:     unless (($tuname) && ($tudom)) {
                   5832:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5833:         return '';
                   5834:     }
                   5835: 
                   5836:     unless (&allowed('mgr',$tcrsid)) {
                   5837:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5838:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5839:         return '';
                   5840:     }
                   5841: 
                   5842:     my %infohash=('resource.0.intoken' => $token,
                   5843:                   'resource.0.checkintime' => $now,
1.1172.2.134  raeburn  5844:                   'resource.0.inremote' => $ip);
1.1172.2.32  raeburn  5845: 
                   5846:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5847:        return '';
                   5848:     }
                   5849: 
                   5850:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5851:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5852:         return '';
                   5853:     }
                   5854: 
                   5855:     return ($symb,$tuname,$tudom,$tcrsid);
                   5856: }
                   5857: 
1.110     www      5858: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5859: 
                   5860: sub expirespread {
                   5861:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5862:     my $cid=$env{'request.course.id'}; 
1.110     www      5863:     if ($cid) {
                   5864:        my $now=time;
                   5865:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5866:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5867:                             $env{'course.'.$cid.'.num'}.
1.110     www      5868: 	        	    ':nohist_expirationdates:'.
                   5869:                             &escape($key).'='.$now,
1.620     albertel 5870:                             $env{'course.'.$cid.'.home'})
1.110     www      5871:     }
                   5872:     return 'ok';
1.14      www      5873: }
                   5874: 
1.109     www      5875: # ----------------------------------------------------- Devalidate Spreadsheets
                   5876: 
                   5877: sub devalidate {
1.325     www      5878:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5879:     my $cid=$env{'request.course.id'}; 
1.109     www      5880:     if ($cid) {
1.391     matthew  5881:         # delete the stored spreadsheets for
                   5882:         # - the student level sheet of this user in course's homespace
                   5883:         # - the assessment level sheet for this resource 
                   5884:         #   for this user in user's homespace
1.553     albertel 5885: 	# - current conditional state info
1.325     www      5886: 	my $key=$uname.':'.$udom.':';
1.109     www      5887:         my $status=
1.299     matthew  5888: 	    &del('nohist_calculatedsheets',
1.391     matthew  5889: 		 [$key.'studentcalc:'],
1.620     albertel 5890: 		 $env{'course.'.$cid.'.domain'},
                   5891: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5892: 		.' '.
                   5893: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5894: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5895:         unless ($status eq 'ok ok') {
                   5896:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5897:                     $uname.' at '.$udom.' for '.
1.109     www      5898: 		    $symb.': '.$status);
1.133     albertel 5899:         }
1.553     albertel 5900: 	&delenv('user.state.'.$cid);
1.109     www      5901:     }
                   5902: }
                   5903: 
1.265     albertel 5904: sub get_scalar {
                   5905:     my ($string,$end) = @_;
                   5906:     my $value;
                   5907:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5908: 	$value = $1;
                   5909:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5910: 	$value = $1;
                   5911:     }
                   5912:     return &unescape($value);
                   5913: }
                   5914: 
                   5915: sub array2str {
                   5916:   my (@array) = @_;
                   5917:   my $result=&arrayref2str(\@array);
                   5918:   $result=~s/^__ARRAY_REF__//;
                   5919:   $result=~s/__END_ARRAY_REF__$//;
                   5920:   return $result;
                   5921: }
                   5922: 
1.204     albertel 5923: sub arrayref2str {
                   5924:   my ($arrayref) = @_;
1.265     albertel 5925:   my $result='__ARRAY_REF__';
1.204     albertel 5926:   foreach my $elem (@$arrayref) {
1.265     albertel 5927:     if(ref($elem) eq 'ARRAY') {
                   5928:       $result.=&arrayref2str($elem).'&';
                   5929:     } elsif(ref($elem) eq 'HASH') {
                   5930:       $result.=&hashref2str($elem).'&';
                   5931:     } elsif(ref($elem)) {
                   5932:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5933:     } else {
                   5934:       $result.=&escape($elem).'&';
                   5935:     }
                   5936:   }
                   5937:   $result=~s/\&$//;
1.265     albertel 5938:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5939:   return $result;
                   5940: }
                   5941: 
1.168     albertel 5942: sub hash2str {
1.204     albertel 5943:   my (%hash) = @_;
                   5944:   my $result=&hashref2str(\%hash);
1.265     albertel 5945:   $result=~s/^__HASH_REF__//;
                   5946:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5947:   return $result;
                   5948: }
                   5949: 
                   5950: sub hashref2str {
                   5951:   my ($hashref)=@_;
1.265     albertel 5952:   my $result='__HASH_REF__';
1.800     albertel 5953:   foreach my $key (sort(keys(%$hashref))) {
                   5954:     if (ref($key) eq 'ARRAY') {
                   5955:       $result.=&arrayref2str($key).'=';
                   5956:     } elsif (ref($key) eq 'HASH') {
                   5957:       $result.=&hashref2str($key).'=';
                   5958:     } elsif (ref($key)) {
1.265     albertel 5959:       $result.='=';
1.800     albertel 5960:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5961:     } else {
1.1132    raeburn  5962: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5963:     }
                   5964: 
1.800     albertel 5965:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5966:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5967:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5968:       $result.=&hashref2str($hashref->{$key}).'&';
                   5969:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5970:        $result.='&';
1.800     albertel 5971:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5972:     } else {
1.800     albertel 5973:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5974:     }
                   5975:   }
1.168     albertel 5976:   $result=~s/\&$//;
1.265     albertel 5977:   $result .= '__END_HASH_REF__';
1.168     albertel 5978:   return $result;
                   5979: }
                   5980: 
                   5981: sub str2hash {
1.265     albertel 5982:     my ($string)=@_;
                   5983:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5984:     return %$hash;
                   5985: }
                   5986: 
                   5987: sub str2hashref {
1.168     albertel 5988:   my ($string) = @_;
1.265     albertel 5989: 
                   5990:   my %hash;
                   5991: 
                   5992:   if($string !~ /^__HASH_REF__/) {
                   5993:       if (! ($string eq '' || !defined($string))) {
                   5994: 	  $hash{'error'}='Not hash reference';
                   5995:       }
                   5996:       return (\%hash, $string);
                   5997:   }
                   5998: 
                   5999:   $string =~ s/^__HASH_REF__//;
                   6000: 
                   6001:   while($string !~ /^__END_HASH_REF__/) {
                   6002:       #key
                   6003:       my $key='';
                   6004:       if($string =~ /^__HASH_REF__/) {
                   6005:           ($key, $string)=&str2hashref($string);
                   6006:           if(defined($key->{'error'})) {
                   6007:               $hash{'error'}='Bad data';
                   6008:               return (\%hash, $string);
                   6009:           }
                   6010:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6011:           ($key, $string)=&str2arrayref($string);
                   6012:           if($key->[0] eq 'Array reference error') {
                   6013:               $hash{'error'}='Bad data';
                   6014:               return (\%hash, $string);
                   6015:           }
                   6016:       } else {
                   6017:           $string =~ s/^(.*?)=//;
1.267     albertel 6018: 	  $key=&unescape($1);
1.265     albertel 6019:       }
                   6020:       $string =~ s/^=//;
                   6021: 
                   6022:       #value
                   6023:       my $value='';
                   6024:       if($string =~ /^__HASH_REF__/) {
                   6025:           ($value, $string)=&str2hashref($string);
                   6026:           if(defined($value->{'error'})) {
                   6027:               $hash{'error'}='Bad data';
                   6028:               return (\%hash, $string);
                   6029:           }
                   6030:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6031:           ($value, $string)=&str2arrayref($string);
                   6032:           if($value->[0] eq 'Array reference error') {
                   6033:               $hash{'error'}='Bad data';
                   6034:               return (\%hash, $string);
                   6035:           }
                   6036:       } else {
                   6037: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   6038:       }
                   6039:       $string =~ s/^&//;
                   6040: 
                   6041:       $hash{$key}=$value;
1.204     albertel 6042:   }
1.265     albertel 6043: 
                   6044:   $string =~ s/^__END_HASH_REF__//;
                   6045: 
                   6046:   return (\%hash, $string);
1.204     albertel 6047: }
                   6048: 
                   6049: sub str2array {
1.265     albertel 6050:     my ($string)=@_;
                   6051:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   6052:     return @$array;
                   6053: }
                   6054: 
                   6055: sub str2arrayref {
1.204     albertel 6056:   my ($string) = @_;
1.265     albertel 6057:   my @array;
                   6058: 
                   6059:   if($string !~ /^__ARRAY_REF__/) {
                   6060:       if (! ($string eq '' || !defined($string))) {
                   6061: 	  $array[0]='Array reference error';
                   6062:       }
                   6063:       return (\@array, $string);
                   6064:   }
                   6065: 
                   6066:   $string =~ s/^__ARRAY_REF__//;
                   6067: 
                   6068:   while($string !~ /^__END_ARRAY_REF__/) {
                   6069:       my $value='';
                   6070:       if($string =~ /^__HASH_REF__/) {
                   6071:           ($value, $string)=&str2hashref($string);
                   6072:           if(defined($value->{'error'})) {
                   6073:               $array[0] ='Array reference error';
                   6074:               return (\@array, $string);
                   6075:           }
                   6076:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6077:           ($value, $string)=&str2arrayref($string);
                   6078:           if($value->[0] eq 'Array reference error') {
                   6079:               $array[0] ='Array reference error';
                   6080:               return (\@array, $string);
                   6081:           }
                   6082:       } else {
                   6083: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   6084:       }
                   6085:       $string =~ s/^&//;
                   6086: 
                   6087:       push(@array, $value);
1.191     harris41 6088:   }
1.265     albertel 6089: 
                   6090:   $string =~ s/^__END_ARRAY_REF__//;
                   6091: 
                   6092:   return (\@array, $string);
1.168     albertel 6093: }
                   6094: 
1.167     albertel 6095: # -------------------------------------------------------------------Temp Store
                   6096: 
1.168     albertel 6097: sub tmpreset {
                   6098:   my ($symb,$namespace,$domain,$stuname) = @_;
                   6099:   if (!$symb) {
                   6100:     $symb=&symbread();
1.620     albertel 6101:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6102:   }
                   6103:   $symb=escape($symb);
                   6104: 
1.620     albertel 6105:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 6106:   $namespace=~s/\//\_/g;
                   6107:   $namespace=~s/\W//g;
                   6108: 
1.620     albertel 6109:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6110:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6111:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6112:       $stuname=&get_requestor_ip();
1.591     albertel 6113:   }
1.1117    foxr     6114:   my $path=LONCAPA::tempdir();
1.168     albertel 6115:   my %hash;
                   6116:   if (tie(%hash,'GDBM_File',
                   6117: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6118: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  6119:     foreach my $key (keys(%hash)) {
1.180     albertel 6120:       if ($key=~ /:$symb/) {
1.168     albertel 6121: 	delete($hash{$key});
                   6122:       }
                   6123:     }
                   6124:   }
                   6125: }
                   6126: 
1.167     albertel 6127: sub tmpstore {
1.168     albertel 6128:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   6129: 
                   6130:   if (!$symb) {
                   6131:     $symb=&symbread();
1.620     albertel 6132:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6133:   }
                   6134:   $symb=escape($symb);
                   6135: 
                   6136:   if (!$namespace) {
                   6137:     # I don't think we would ever want to store this for a course.
                   6138:     # it seems this will only be used if we don't have a course.
1.620     albertel 6139:     #$namespace=$env{'request.course.id'};
1.168     albertel 6140:     #if (!$namespace) {
1.620     albertel 6141:       $namespace=$env{'request.state'};
1.168     albertel 6142:     #}
                   6143:   }
                   6144:   $namespace=~s/\//\_/g;
                   6145:   $namespace=~s/\W//g;
1.620     albertel 6146:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6147:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6148:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6149:       $stuname=&get_requestor_ip();
1.591     albertel 6150:   }
1.168     albertel 6151:   my $now=time;
                   6152:   my %hash;
1.1117    foxr     6153:   my $path=LONCAPA::tempdir();
1.168     albertel 6154:   if (tie(%hash,'GDBM_File',
                   6155: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6156: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 6157:     $hash{"version:$symb"}++;
                   6158:     my $version=$hash{"version:$symb"};
                   6159:     my $allkeys=''; 
                   6160:     foreach my $key (keys(%$storehash)) {
                   6161:       $allkeys.=$key.':';
1.591     albertel 6162:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 6163:     }
                   6164:     $hash{"$version:$symb:timestamp"}=$now;
                   6165:     $allkeys.='timestamp';
                   6166:     $hash{"$version:keys:$symb"}=$allkeys;
                   6167:     if (untie(%hash)) {
                   6168:       return 'ok';
                   6169:     } else {
                   6170:       return "error:$!";
                   6171:     }
                   6172:   } else {
                   6173:     return "error:$!";
                   6174:   }
                   6175: }
1.167     albertel 6176: 
1.168     albertel 6177: # -----------------------------------------------------------------Temp Restore
1.167     albertel 6178: 
1.168     albertel 6179: sub tmprestore {
                   6180:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 6181: 
1.168     albertel 6182:   if (!$symb) {
                   6183:     $symb=&symbread();
1.620     albertel 6184:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6185:   }
                   6186:   $symb=escape($symb);
                   6187: 
1.620     albertel 6188:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 6189: 
1.620     albertel 6190:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6191:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6192:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6193:       $stuname=&get_requestor_ip();
1.591     albertel 6194:   }
1.168     albertel 6195:   my %returnhash;
                   6196:   $namespace=~s/\//\_/g;
                   6197:   $namespace=~s/\W//g;
                   6198:   my %hash;
1.1117    foxr     6199:   my $path=LONCAPA::tempdir();
1.168     albertel 6200:   if (tie(%hash,'GDBM_File',
                   6201: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6202: 	  &GDBM_READER(),0640)) {
1.168     albertel 6203:     my $version=$hash{"version:$symb"};
                   6204:     $returnhash{'version'}=$version;
                   6205:     my $scope;
                   6206:     for ($scope=1;$scope<=$version;$scope++) {
                   6207:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6208:       my @keys=split(/:/,$vkeys);
                   6209:       my $key;
                   6210:       $returnhash{"$scope:keys"}=$vkeys;
                   6211:       foreach $key (@keys) {
1.591     albertel 6212: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6213: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6214:       }
                   6215:     }
1.168     albertel 6216:     if (!(untie(%hash))) {
                   6217:       return "error:$!";
                   6218:     }
                   6219:   } else {
                   6220:     return "error:$!";
                   6221:   }
                   6222:   return %returnhash;
1.167     albertel 6223: }
                   6224: 
1.9       www      6225: # ----------------------------------------------------------------------- Store
                   6226: 
                   6227: sub store {
1.1172.2.64  raeburn  6228:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6229:     my $home='';
                   6230: 
1.168     albertel 6231:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6232: 
1.213     www      6233:     $symb=&symbclean($symb);
1.122     albertel 6234:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6235: 
1.620     albertel 6236:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6237:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6238: 
                   6239:     &devalidate($symb,$stuname,$domain);
1.109     www      6240: 
                   6241:     $symb=escape($symb);
1.187     www      6242:     if (!$namespace) { 
1.620     albertel 6243:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6244:           return ''; 
                   6245:        } 
                   6246:     }
1.620     albertel 6247:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6248: 
1.1172.2.138  raeburn  6249:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6250:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6251: 
1.12      www      6252:     my $namevalue='';
1.800     albertel 6253:     foreach my $key (keys(%$storehash)) {
                   6254:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6255:     }
1.12      www      6256:     $namevalue=~s/\&$//;
1.187     www      6257:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  6258:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6259: }
                   6260: 
1.47      www      6261: # -------------------------------------------------------------- Critical Store
                   6262: 
                   6263: sub cstore {
1.1172.2.64  raeburn  6264:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6265:     my $home='';
                   6266: 
1.168     albertel 6267:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6268: 
1.213     www      6269:     $symb=&symbclean($symb);
1.122     albertel 6270:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6271: 
1.620     albertel 6272:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6273:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6274: 
                   6275:     &devalidate($symb,$stuname,$domain);
1.109     www      6276: 
                   6277:     $symb=escape($symb);
1.187     www      6278:     if (!$namespace) { 
1.620     albertel 6279:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6280:           return ''; 
                   6281:        } 
                   6282:     }
1.620     albertel 6283:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6284: 
1.1172.2.138  raeburn  6285:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6286:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6287: 
1.47      www      6288:     my $namevalue='';
1.800     albertel 6289:     foreach my $key (keys(%$storehash)) {
                   6290:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6291:     }
1.47      www      6292:     $namevalue=~s/\&$//;
1.187     www      6293:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6294:     return critical
1.1172.2.64  raeburn  6295:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6296: }
                   6297: 
1.9       www      6298: # --------------------------------------------------------------------- Restore
                   6299: 
                   6300: sub restore {
1.124     www      6301:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6302:     my $home='';
                   6303: 
1.168     albertel 6304:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6305: 
1.122     albertel 6306:     if (!$symb) {
1.1172.2.26  raeburn  6307:         return if ($namespace eq 'courserequests');
                   6308:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6309:     } else {
1.1172.2.26  raeburn  6310:         unless ($namespace eq 'courserequests') {
                   6311:             $symb=&escape(&symbclean($symb));
                   6312:         }
1.122     albertel 6313:     }
1.188     www      6314:     if (!$namespace) { 
1.620     albertel 6315:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6316:           return ''; 
                   6317:        } 
                   6318:     }
1.620     albertel 6319:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6320:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6321:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6322:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6323: 
1.12      www      6324:     my %returnhash=();
1.800     albertel 6325:     foreach my $line (split(/\&/,$answer)) {
                   6326: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6327:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6328:     }
1.75      www      6329:     my $version;
                   6330:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6331:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6332:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6333:        }
1.75      www      6334:     }
1.13      www      6335:     return %returnhash;
1.34      www      6336: }
                   6337: 
                   6338: # ---------------------------------------------------------- Course Description
1.1118    foxr     6339: #
                   6340: #  
1.34      www      6341: 
                   6342: sub coursedescription {
1.731     albertel 6343:     my ($courseid,$args)=@_;
1.34      www      6344:     $courseid=~s/^\///;
1.49      www      6345:     $courseid=~s/\_/\//g;
1.34      www      6346:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6347:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6348:     my $normalid=$cdomain.'_'.$cnum;
                   6349:     # need to always cache even if we get errors otherwise we keep 
                   6350:     # trying and trying and trying to get the course description.
                   6351:     my %envhash=();
                   6352:     my %returnhash=();
1.731     albertel 6353:     
                   6354:     my $expiretime=600;
                   6355:     if ($env{'request.course.id'} eq $normalid) {
                   6356: 	$expiretime=120;
                   6357:     }
                   6358: 
                   6359:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6360:     if (!$args->{'freshen_cache'}
                   6361: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6362: 	foreach my $key (keys(%env)) {
                   6363: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6364: 	    my ($setting) = $1;
                   6365: 	    $returnhash{$setting} = $env{$key};
                   6366: 	}
                   6367: 	return %returnhash;
                   6368:     }
                   6369: 
1.1118    foxr     6370:     # get the data again
                   6371: 
1.731     albertel 6372:     if (!$args->{'one_time'}) {
                   6373: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6374:     }
1.811     albertel 6375: 
1.34      www      6376:     if ($chome ne 'no_host') {
1.302     albertel 6377:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6378:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6379: 	   my $username = $env{'user.name'}; # Defult username
                   6380: 	   if(defined $args->{'user'}) {
                   6381: 	       $username = $args->{'user'};
                   6382: 	   }
1.129     albertel 6383:            $returnhash{'home'}= $chome;
                   6384: 	   $returnhash{'domain'} = $cdomain;
                   6385: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6386:            if (!defined($returnhash{'type'})) {
                   6387:                $returnhash{'type'} = 'Course';
                   6388:            }
1.130     albertel 6389:            while (my ($name,$value) = each %returnhash) {
1.53      www      6390:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6391:            }
1.270     www      6392:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6393:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6394: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6395:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6396:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6397:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6398:        }
                   6399:     }
1.731     albertel 6400:     if (!$args->{'one_time'}) {
1.949     raeburn  6401: 	&appenv(\%envhash);
1.731     albertel 6402:     }
1.302     albertel 6403:     return %returnhash;
1.461     www      6404: }
                   6405: 
1.1080    raeburn  6406: sub update_released_required {
                   6407:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6408:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6409:         $cid = $env{'request.course.id'};
                   6410:         $cdom = $env{'course.'.$cid.'.domain'};
                   6411:         $cnum = $env{'course.'.$cid.'.num'};
                   6412:         $chome = $env{'course.'.$cid.'.home'};
                   6413:     }
                   6414:     if ($needsrelease) {
                   6415:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6416:         my $needsupdate;
                   6417:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6418:             $needsupdate = 1;
                   6419:         } else {
                   6420:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6421:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6422:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6423:                 $needsupdate = 1;
                   6424:             }
                   6425:         }
                   6426:         if ($needsupdate) {
                   6427:             my %needshash = (
                   6428:                              'internal.releaserequired' => $needsrelease,
                   6429:                             );
                   6430:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6431:             if ($putresult eq 'ok') {
                   6432:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6433:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6434:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6435:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6436:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6437:                 }
                   6438:             }
                   6439:         }
                   6440:     }
                   6441:     return;
                   6442: }
                   6443: 
1.461     www      6444: # -------------------------------------------------See if a user is privileged
                   6445: 
                   6446: sub privileged {
1.1172.2.23  raeburn  6447:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6448:     my $now = time;
1.1172.2.23  raeburn  6449:     my $roles;
                   6450:     if (ref($possroles) eq 'ARRAY') {
                   6451:         $roles = $possroles;
                   6452:     } else {
                   6453:         $roles = ['dc','su'];
                   6454:     }
                   6455:     if (ref($possdomains) eq 'ARRAY') {
                   6456:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6457:         foreach my $dom (@{$possdomains}) {
                   6458:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6459:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6460:                 foreach my $role (@{$roles}) {
                   6461:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6462:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6463:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6464:                             return 1 unless (($end && $end < $now) ||
                   6465:                                              ($start && $start > $now));
                   6466:                         }
                   6467:                     }
                   6468:                 }
                   6469:             }
                   6470:         }
                   6471:     } else {
                   6472:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6473:         my $now = time;
1.1170    droeschl 6474: 
1.1172.2.58  raeburn  6475:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6476:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6477:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6478:                 return 1 unless ($tend && $tend < $now)
                   6479:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6480:             }
1.1172.2.23  raeburn  6481:         }
                   6482:     }
1.461     www      6483:     return 0;
1.9       www      6484: }
1.1       albertel 6485: 
1.1172.2.23  raeburn  6486: sub privileged_by_domain {
                   6487:     my ($domains,$roles) = @_;
                   6488:     my %privileged = ();
                   6489:     my $cachetime = 60*60*24;
                   6490:     my $now = time;
                   6491:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6492:         return %privileged;
                   6493:     }
                   6494:     foreach my $dom (@{$domains}) {
                   6495:         next if (ref($privileged{$dom}) eq 'HASH');
                   6496:         my $needroles;
                   6497:         foreach my $role (@{$roles}) {
                   6498:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6499:             if (defined($cached)) {
                   6500:                 if (ref($result) eq 'HASH') {
                   6501:                     $privileged{$dom}{$role} = $result;
                   6502:                 }
                   6503:             } else {
                   6504:                 $needroles = 1;
                   6505:             }
                   6506:         }
                   6507:         if ($needroles) {
                   6508:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6509:             $privileged{$dom} = {};
                   6510:             foreach my $server (keys(%dompersonnel)) {
                   6511:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6512:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6513:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6514:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6515:                         next if ($end && $end < $now);
                   6516:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6517:                             $dompersonnel{$server}{$item};
                   6518:                     }
                   6519:                 }
                   6520:             }
                   6521:             if (ref($privileged{$dom}) eq 'HASH') {
                   6522:                 foreach my $role (@{$roles}) {
                   6523:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6524:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6525:                     } else {
                   6526:                         my %hash = ();
                   6527:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6528:                     }
                   6529:                 }
                   6530:             }
                   6531:         }
                   6532:     }
                   6533:     return %privileged;
                   6534: }
                   6535: 
1.103     harris41 6536: # -------------------------------------------------------- Get user privileges
1.11      www      6537: 
                   6538: sub rolesinit {
1.1169    droeschl 6539:     my ($domain, $username) = @_;
                   6540:     my %userroles = ('user.login.time' => time);
                   6541:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6542: 
                   6543:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6544:     # also, blocking can be triggered by an activating timer
                   6545:     # it's saved in the user's %env.
                   6546:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6547:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6548:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6549:         %timerintchk, %timerintenv);
                   6550: 
1.1162    raeburn  6551:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6552:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6553:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6554:     }
1.1169    droeschl 6555: 
1.1162    raeburn  6556:     foreach my $key (keys(%timerinterval)) {
                   6557:         my ($cid,$rest) = split(/\0/,$key);
                   6558:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6559:     }
1.1169    droeschl 6560: 
1.11      www      6561:     my %allroles=();
1.1162    raeburn  6562:     my %allgroups=();
1.11      www      6563: 
1.1172.2.58  raeburn  6564:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6565:         my $role = $rolesdump{$area};
                   6566:         $area =~ s/\_\w\w$//;
                   6567: 
                   6568:         my ($trole, $tend, $tstart, $group_privs);
                   6569: 
                   6570:         if ($role =~ /^cr/) {
                   6571:         # Custom role, defined by a user 
                   6572:         # e.g., user.role.cr/msu/smith/mynewrole
                   6573:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6574:                 $trole = $1;
                   6575:                 ($tend, $tstart) = split('_', $2);
                   6576:             } else {
                   6577:                 $trole = $role;
                   6578:             }
                   6579:         } elsif ($role =~ m|^gr/|) {
                   6580:         # Role of member in a group, defined within a course/community
                   6581:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6582:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6583:             next if $tstart eq '-1';
                   6584:             ($trole, $group_privs) = split(/\//, $trole);
                   6585:             $group_privs = &unescape($group_privs);
                   6586:         } else {
                   6587:         # Just a normal role, defined in roles.tab
                   6588:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6589:         }
                   6590: 
                   6591:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6592:                  $username);
                   6593:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6594: 
                   6595:         # role expired or not available yet?
                   6596:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6597:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6598: 
                   6599:         next if $area eq '' or $trole eq '';
                   6600: 
                   6601:         my $spec = "$trole.$area";
                   6602:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6603: 
                   6604:         if ($trole =~ /^cr\//) {
                   6605:         # Custom role, defined by a user
                   6606:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6607:         } elsif ($trole eq 'gr') {
                   6608:         # Role of a member in a group, defined within a course/community
                   6609:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6610:             next;
                   6611:         } else {
                   6612:         # Normal role, defined in roles.tab
                   6613:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6614:         }
                   6615: 
                   6616:         my $cid = $tdomain.'_'.$trest;
                   6617:         unless ($firstaccchk{$cid}) {
                   6618:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6619:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6620:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6621:                         $coursetimerstarts{$cid}{$item}; 
                   6622:                 }
                   6623:             }
                   6624:             $firstaccchk{$cid} = 1;
                   6625:         }
                   6626:         unless ($timerintchk{$cid}) {
                   6627:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6628:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6629:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6630:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6631:                 }
1.12      www      6632:             }
1.1169    droeschl 6633:             $timerintchk{$cid} = 1;
1.191     harris41 6634:         }
1.11      www      6635:     }
1.1169    droeschl 6636: 
1.1172.2.91  raeburn  6637:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6638:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6639:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6640:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6641: 
1.1162    raeburn  6642:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6643: }
                   6644: 
1.567     raeburn  6645: sub set_arearole {
1.1172.2.19  raeburn  6646:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6647:     unless ($nolog) {
1.567     raeburn  6648: # log the associated role with the area
1.1172.2.19  raeburn  6649:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6650:     }
1.743     albertel 6651:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6652: }
                   6653: 
                   6654: sub custom_roleprivs {
                   6655:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6656:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6657:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6658:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6659:         my ($rdummy,$roledef)=
                   6660:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6661:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6662:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6663:             if (defined($syspriv)) {
1.1043    raeburn  6664:                 if ($trest =~ /^$match_community$/) {
                   6665:                     $syspriv =~ s/bre\&S//; 
                   6666:                 }
1.567     raeburn  6667:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6668:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6669:             }
                   6670:             if ($tdomain ne '') {
                   6671:                 if (defined($dompriv)) {
                   6672:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6673:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6674:                 }
                   6675:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6676:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6677:                         my $rolename = $1;
                   6678:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6679:                     }
1.567     raeburn  6680:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6681:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6682:                 }
                   6683:             }
                   6684:         }
                   6685:     }
                   6686: }
                   6687: 
1.1172.2.89  raeburn  6688: sub course_adhocrole_privs {
                   6689:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6690:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6691:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6692:         my (%currprivs,%storeprivs);
                   6693:         foreach my $item (split(/:/,$coursepriv)) {
                   6694:             my ($priv,$restrict) = split(/\&/,$item);
                   6695:             $currprivs{$priv} = $restrict;
                   6696:         }
                   6697:         my (%possadd,%possremove,%full);
                   6698:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6699:             my ($priv,$restrict)=split(/\&/,$item);
                   6700:             $full{$priv} = $restrict;
                   6701:         }
                   6702:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
1.1172.2.146.  .6(raebu 6703:22):             next if ($item eq '');
                   6704:22):             my ($rule,$rest) = split(/=/,$item);
                   6705:22):             next unless (($rule eq 'off') || ($rule eq 'on'));
                   6706:22):             foreach my $priv (split(/:/,$rest)) {
                   6707:22):                 if ($priv ne '') {
                   6708:22):                     if ($rule eq 'off') {
                   6709:22):                         $possremove{$priv} = 1;
                   6710:22):                     } else {
                   6711:22):                         $possadd{$priv} = 1;
                   6712:22):                     }
                   6713:22):                 }
                   6714:22):             }
                   6715:22):         }
                   6716:22):         foreach my $priv (sort(keys(%full))) {
                   6717:22):             if (exists($currprivs{$priv})) {
                   6718:22):                 unless (exists($possremove{$priv})) {
                   6719:22):                     $storeprivs{$priv} = $currprivs{$priv};
                   6720:22):                 }
                   6721:22):             } elsif (exists($possadd{$priv})) {
                   6722:22):                 $storeprivs{$priv} = $full{$priv};
                   6723:22):             }
                   6724:22):         }
                   6725:22):         $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6726:22):     }
                   6727:22):     return $coursepriv;
1.1172.2.89  raeburn  6728: }
                   6729: 
1.678     raeburn  6730: sub group_roleprivs {
                   6731:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6732:     my $access = 1;
                   6733:     my $now = time;
                   6734:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6735:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6736:     if ($access) {
1.811     albertel 6737:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6738:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6739:     }
                   6740: }
1.567     raeburn  6741: 
                   6742: sub standard_roleprivs {
                   6743:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6744:     if (defined($pr{$trole.':s'})) {
                   6745:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6746:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6747:     }
                   6748:     if ($tdomain ne '') {
                   6749:         if (defined($pr{$trole.':d'})) {
                   6750:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6751:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6752:         }
                   6753:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6754:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6755:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6756:         }
                   6757:     }
                   6758: }
                   6759: 
                   6760: sub set_userprivs {
1.1064    raeburn  6761:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6762:     my $author=0;
                   6763:     my $adv=0;
1.1172.2.91  raeburn  6764:     my $rar=0;
1.678     raeburn  6765:     my %grouproles = ();
                   6766:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6767:         my @groupkeys; 
1.1000    raeburn  6768:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6769:             push(@groupkeys,$role);
                   6770:         }
                   6771:         if (ref($groups_roles) eq 'HASH') {
                   6772:             foreach my $key (keys(%{$groups_roles})) {
                   6773:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6774:                     push(@groupkeys,$key);
                   6775:                 }
                   6776:             }
                   6777:         }
                   6778:         if (@groupkeys > 0) {
                   6779:             foreach my $role (@groupkeys) {
                   6780:                 my ($trole,$area,$sec,$extendedarea);
                   6781:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6782:                     $trole = $1;
                   6783:                     $area = $2;
                   6784:                     $sec = $3;
                   6785:                     $extendedarea = $area.$sec;
                   6786:                     if (exists($$allgroups{$area})) {
                   6787:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6788:                             my $spec = $trole.'.'.$extendedarea;
                   6789:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6790:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6791:                         }
1.678     raeburn  6792:                     }
                   6793:                 }
                   6794:             }
                   6795:         }
                   6796:     }
1.800     albertel 6797:     foreach my $group (keys(%grouproles)) {
                   6798:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6799:     }
1.800     albertel 6800:     foreach my $role (keys(%{$allroles})) {
                   6801:         my %thesepriv;
1.941     raeburn  6802:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6803:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6804:             if ($item ne '') {
                   6805:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6806:                 if ($restrictions eq '') {
                   6807:                     $thesepriv{$privilege}='F';
                   6808:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6809:                     $thesepriv{$privilege}.=$restrictions;
                   6810:                 }
                   6811:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6812:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6813:             }
                   6814:         }
                   6815:         my $thesestr='';
1.1104    raeburn  6816:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6817: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6818: 	}
                   6819:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6820:     }
1.1172.2.91  raeburn  6821:     return ($author,$adv,$rar);
1.567     raeburn  6822: }
                   6823: 
1.994     raeburn  6824: sub role_status {
1.1104    raeburn  6825:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6826:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6827:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6828:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6829:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6830:             $$where = '/'.$two;
1.994     raeburn  6831:             $$trolecode=$$role.'.'.$$where;
                   6832:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6833:             $$tstatus='is';
1.1104    raeburn  6834:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6835:                 $$tstatus='future';
1.1034    raeburn  6836:                 if ($$tstart<$now) {
                   6837:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6838:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6839:                             my (%allroles,%allgroups,$group_privs,
                   6840:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6841:                             my %userroles = (
                   6842:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6843:                             );
1.1064    raeburn  6844:                             @rolecodes = ('cm'); 
1.1002    raeburn  6845:                             my $spec=$$role.'.'.$$where;
                   6846:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6847:                             if ($$role =~ /^cr\//) {
                   6848:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6849:                                 push(@rolecodes,'cr');
1.1002    raeburn  6850:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6851:                                 push(@rolecodes,$$role);
1.1002    raeburn  6852:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6853:                                                     $env{'user.name'});
1.1064    raeburn  6854:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6855:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6856:                                 $group_privs = &unescape($group_privs);
                   6857:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6858:                                 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  6859:                                 &get_groups_roles($tdomain,$trest,
                   6860:                                                   \%course_roles,\@rolecodes,
                   6861:                                                   \%groups_roles);
1.1002    raeburn  6862:                             } else {
1.1064    raeburn  6863:                                 push(@rolecodes,$$role);
1.1002    raeburn  6864:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6865:                             }
1.1172.2.91  raeburn  6866:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6867:                                                                    \%groups_roles);
1.1064    raeburn  6868:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  6869:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6870:                         }
                   6871:                     }
1.1034    raeburn  6872:                     $$tstatus = 'is';
1.1002    raeburn  6873:                 }
1.994     raeburn  6874:             }
                   6875:             if ($$tend) {
1.1104    raeburn  6876:                 if ($$tend<$update) {
1.994     raeburn  6877:                     $$tstatus='expired';
                   6878:                 } elsif ($$tend<$now) {
                   6879:                     $$tstatus='will_not';
                   6880:                 }
                   6881:             }
                   6882:         }
                   6883:     }
                   6884: }
                   6885: 
1.1104    raeburn  6886: sub get_groups_roles {
                   6887:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6888:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6889:                   (ref($rolecodes) eq 'ARRAY') && 
                   6890:                   (ref($groups_roles) eq 'HASH')); 
                   6891:     if (keys(%{$cdom_courseroles}) > 0) {
                   6892:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6893:         if ($cdom ne '' && $cnum ne '') {
                   6894:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6895:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6896:                     my $crsrole = $1;
                   6897:                     my $crssec = $2;
                   6898:                     if ($crsrole =~ /^cr/) {
                   6899:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6900:                             push(@{$rolecodes},'cr');
                   6901:                         }
                   6902:                     } else {
                   6903:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6904:                             push(@{$rolecodes},$crsrole);
                   6905:                         }
                   6906:                     }
                   6907:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6908:                     if ($crssec ne '') {
                   6909:                         $rolekey .= "/$crssec";
                   6910:                     }
                   6911:                     $rolekey .= './';
                   6912:                     $groups_roles->{$rolekey} = $rolecodes;
                   6913:                 }
                   6914:             }
                   6915:         }
                   6916:     }
                   6917:     return;
                   6918: }
                   6919: 
                   6920: sub delete_env_groupprivs {
                   6921:     my ($where,$courseroles,$possroles) = @_;
                   6922:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6923:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6924:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6925:         %{$courseroles->{$udom}} =
                   6926:             &get_my_roles('','','userroles',['active'],
                   6927:                           $possroles,[$udom],1);
                   6928:     }
                   6929:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6930:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6931:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6932:             my $area = '/'.$cdom.'/'.$cnum;
                   6933:             my $privkey = "user.priv.$crsrole.$area";
                   6934:             if ($crssec ne '') {
                   6935:                 $privkey .= '/'.$crssec;
                   6936:             }
                   6937:             $privkey .= ".$area/$group";
                   6938:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6939:         }
                   6940:     }
                   6941:     return;
                   6942: }
                   6943: 
1.994     raeburn  6944: sub check_adhoc_privs {
1.1172.2.86  raeburn  6945:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6946:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  6947:     if ($sec) {
                   6948:         $cckey .= '/'.$sec;
                   6949:     }
1.1172.2.9  raeburn  6950:     my $setprivs;
1.994     raeburn  6951:     if ($env{$cckey}) {
                   6952:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6953:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6954:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  6955:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6956:             $setprivs = 1;
1.994     raeburn  6957:         }
                   6958:     } else {
1.1172.2.87  raeburn  6959:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  6960:         $setprivs = 1;
1.994     raeburn  6961:     }
1.1172.2.9  raeburn  6962:     return $setprivs;
1.994     raeburn  6963: }
                   6964: 
                   6965: sub set_adhoc_privileges {
1.1172.2.84  raeburn  6966: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  6967:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6968:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  6969:     if ($sec ne '') {
                   6970:         $area .= '/'.$sec;
                   6971:     }
1.994     raeburn  6972:     my $spec = $role.'.'.$area;
                   6973:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  6974:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  6975:     my %rolehash = ();
1.1172.2.89  raeburn  6976:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6977:         my $rolename = $1;
1.1172.2.84  raeburn  6978:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  6979:         my %domdef = &get_domain_defaults($dcdom);
                   6980:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6981:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6982:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6983:             }
                   6984:         }
1.1172.2.84  raeburn  6985:     } else {
                   6986:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6987:     }
1.1172.2.91  raeburn  6988:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6989:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  6990:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1172.2.146.  .1(raebu 6991:22):     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
                   6992:22):             ($caller eq 'tiny')) {
1.1088    raeburn  6993:         &appenv( {'request.role'        => $spec,
                   6994:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  6995:                   'request.course.sec'  => $sec, 
1.1088    raeburn  6996:                  }
                   6997:                );
                   6998:         my $tadv=0;
                   6999:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   7000:         &appenv({'request.role.adv'    => $tadv});
                   7001:     }
1.994     raeburn  7002: }
                   7003: 
1.12      www      7004: # --------------------------------------------------------------- get interface
                   7005: 
                   7006: sub get {
1.131     albertel 7007:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7008:    my $items='';
1.800     albertel 7009:    foreach my $item (@$storearr) {
                   7010:        $items.=&escape($item).'&';
1.191     harris41 7011:    }
1.12      www      7012:    $items=~s/\&$//;
1.620     albertel 7013:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7014:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 7015:    my $uhome=&homeserver($uname,$udomain);
                   7016: 
1.133     albertel 7017:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7018:    my @pairs=split(/\&/,$rep);
1.273     albertel 7019:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   7020:      return @pairs;
                   7021:    }
1.15      www      7022:    my %returnhash=();
1.42      www      7023:    my $i=0;
1.800     albertel 7024:    foreach my $item (@$storearr) {
                   7025:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7026:       $i++;
1.191     harris41 7027:    }
1.15      www      7028:    return %returnhash;
1.27      www      7029: }
                   7030: 
                   7031: # --------------------------------------------------------------- del interface
                   7032: 
                   7033: sub del {
1.133     albertel 7034:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      7035:    my $items='';
1.800     albertel 7036:    foreach my $item (@$storearr) {
                   7037:        $items.=&escape($item).'&';
1.191     harris41 7038:    }
1.984     neumanie 7039: 
1.27      www      7040:    $items=~s/\&$//;
1.620     albertel 7041:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7042:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7043:    my $uhome=&homeserver($uname,$udomain);
                   7044:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7045: }
                   7046: 
                   7047: # -------------------------------------------------------------- dump interface
                   7048: 
1.1172.2.22  raeburn  7049: sub unserialize {
                   7050:     my ($rep, $escapedkeys) = @_;
                   7051: 
                   7052:     return {} if $rep =~ /^error/;
                   7053: 
                   7054:     my %returnhash=();
                   7055:     foreach my $item (split(/\&/,$rep)) {
                   7056:         my ($key, $value) = split(/=/, $item, 2);
                   7057:         $key = unescape($key) unless $escapedkeys;
                   7058:         next if $key =~ /^error: 2 /;
                   7059:         $returnhash{$key} = &thaw_unescape($value);
                   7060:     }
                   7061:     return \%returnhash;
                   7062: }
                   7063: 
                   7064: # see Lond::dump_with_regexp
                   7065: # if $escapedkeys hash keys won't get unescaped.
1.15      www      7066: sub dump {
1.1172.2.146.  .1(raebu 7067:22):     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
1.755     albertel 7068:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7069:     if (!$uname) { $uname=$env{'user.name'}; }
                   7070:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 7071: 
1.1172.2.55  raeburn  7072:     if ($regexp) {
                   7073:         $regexp=&escape($regexp);
                   7074:     } else {
                   7075:         $regexp='.';
                   7076:     }
1.1172.2.22  raeburn  7077:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   7078:         # user is hosted on this machine
1.1172.2.55  raeburn  7079:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  7080:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  7081:         return %{&unserialize($reply, $escapedkeys)};
                   7082:     }
1.1172.2.146.  .1(raebu 7083:22):     my $rep;
                   7084:22):     if ($encrypt) {
                   7085:22):         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   7086:22):     } else {
                   7087:22):         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   7088:22):     }
1.755     albertel 7089:     my @pairs=split(/\&/,$rep);
                   7090:     my %returnhash=();
1.1098    foxr     7091:     if (!($rep =~ /^error/ )) {
                   7092: 	foreach my $item (@pairs) {
                   7093: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  7094:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     7095: 	    next if ($key =~ /^error: 2 /);
                   7096: 	    $returnhash{$key}=&thaw_unescape($value);
                   7097: 	}
1.755     albertel 7098:     }
                   7099:     return %returnhash;
1.407     www      7100: }
                   7101: 
1.1098    foxr     7102: 
1.717     albertel 7103: # --------------------------------------------------------- dumpstore interface
                   7104: 
                   7105: sub dumpstore {
                   7106:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  7107:    # same as dump but keys must be escaped. They may contain colon separated
                   7108:    # lists of values that may themself contain colons (e.g. symbs).
                   7109:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 7110: }
                   7111: 
1.407     www      7112: # -------------------------------------------------------------- keys interface
                   7113: 
                   7114: sub getkeys {
                   7115:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 7116:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7117:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      7118:    my $uhome=&homeserver($uname,$udomain);
                   7119:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   7120:    my @keyarray=();
1.800     albertel 7121:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  7122:       next if ($key =~ /^error: 2 /);
1.800     albertel 7123:       push(@keyarray,&unescape($key));
1.407     www      7124:    }
                   7125:    return @keyarray;
1.318     matthew  7126: }
                   7127: 
1.319     matthew  7128: # --------------------------------------------------------------- currentdump
                   7129: sub currentdump {
1.328     matthew  7130:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 7131:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   7132:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   7133:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  7134:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  7135:    my $rep;
                   7136: 
                   7137:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   7138:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   7139:                    $courseid)));
                   7140:    } else {
                   7141:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   7142:    }
                   7143: 
1.318     matthew  7144:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  7145:    #
1.318     matthew  7146:    my %returnhash=();
1.319     matthew  7147:    #
                   7148:    if ($rep eq "unknown_cmd") { 
                   7149:        # an old lond will not know currentdump
                   7150:        # Do a dump and make it look like a currentdump
1.822     albertel 7151:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  7152:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   7153:        my %hash = @tmp;
                   7154:        @tmp=();
1.424     matthew  7155:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  7156:    } else {
                   7157:        my @pairs=split(/\&/,$rep);
1.800     albertel 7158:        foreach my $pair (@pairs) {
                   7159:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  7160:            my ($symb,$param) = split(/:/,$key);
                   7161:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 7162:                                                         &thaw_unescape($value);
1.319     matthew  7163:        }
1.191     harris41 7164:    }
1.12      www      7165:    return %returnhash;
1.424     matthew  7166: }
                   7167: 
                   7168: sub convert_dump_to_currentdump{
                   7169:     my %hash = %{shift()};
                   7170:     my %returnhash;
                   7171:     # Code ripped from lond, essentially.  The only difference
                   7172:     # here is the unescaping done by lonnet::dump().  Conceivably
                   7173:     # we might run in to problems with parameter names =~ /^v\./
                   7174:     while (my ($key,$value) = each(%hash)) {
                   7175:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 7176: 	$symb  = &unescape($symb);
                   7177: 	$param = &unescape($param);
1.424     matthew  7178:         next if ($v eq 'version' || $symb eq 'keys');
                   7179:         next if (exists($returnhash{$symb}) &&
                   7180:                  exists($returnhash{$symb}->{$param}) &&
                   7181:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   7182:         $returnhash{$symb}->{$param}=$value;
                   7183:         $returnhash{$symb}->{'v.'.$param}=$v;
                   7184:     }
                   7185:     #
                   7186:     # Remove all of the keys in the hashes which keep track of
                   7187:     # the version of the parameter.
                   7188:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   7189:         # use a foreach because we are going to delete from the hash.
                   7190:         foreach my $key (keys(%$param_hash)) {
                   7191:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   7192:         }
                   7193:     }
                   7194:     return \%returnhash;
1.12      www      7195: }
                   7196: 
1.627     albertel 7197: # ------------------------------------------------------ critical inc interface
                   7198: 
                   7199: sub cinc {
                   7200:     return &inc(@_,'critical');
                   7201: }
                   7202: 
1.449     matthew  7203: # --------------------------------------------------------------- inc interface
                   7204: 
                   7205: sub inc {
1.627     albertel 7206:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7207:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7208:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7209:     my $uhome=&homeserver($uname,$udomain);
                   7210:     my $items='';
                   7211:     if (! ref($store)) {
                   7212:         # got a single value, so use that instead
                   7213:         $items = &escape($store).'=&';
                   7214:     } elsif (ref($store) eq 'SCALAR') {
                   7215:         $items = &escape($$store).'=&';        
                   7216:     } elsif (ref($store) eq 'ARRAY') {
                   7217:         $items = join('=&',map {&escape($_);} @{$store});
                   7218:     } elsif (ref($store) eq 'HASH') {
                   7219:         while (my($key,$value) = each(%{$store})) {
                   7220:             $items.= &escape($key).'='.&escape($value).'&';
                   7221:         }
                   7222:     }
                   7223:     $items=~s/\&$//;
1.627     albertel 7224:     if ($critical) {
                   7225: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7226:     } else {
                   7227: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7228:     }
1.449     matthew  7229: }
                   7230: 
1.12      www      7231: # --------------------------------------------------------------- put interface
                   7232: 
                   7233: sub put {
1.1172.2.146.  .1(raebu 7234:22):    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
1.620     albertel 7235:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7236:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7237:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7238:    my $items='';
1.800     albertel 7239:    foreach my $item (keys(%$storehash)) {
                   7240:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7241:    }
1.12      www      7242:    $items=~s/\&$//;
1.1172.2.146.  .1(raebu 7243:22):    if ($encrypt) {
                   7244:22):        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
                   7245:22):    } else {
                   7246:22):        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
                   7247:22):    }
1.47      www      7248: }
                   7249: 
1.631     albertel 7250: # ------------------------------------------------------------ newput interface
                   7251: 
                   7252: sub newput {
                   7253:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7254:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7255:    if (!$uname) { $uname=$env{'user.name'}; }
                   7256:    my $uhome=&homeserver($uname,$udomain);
                   7257:    my $items='';
                   7258:    foreach my $key (keys(%$storehash)) {
                   7259:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7260:    }
                   7261:    $items=~s/\&$//;
                   7262:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7263: }
                   7264: 
                   7265: # ---------------------------------------------------------  putstore interface
                   7266: 
1.524     raeburn  7267: sub putstore {
1.1172.2.59  raeburn  7268:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7269:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7270:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7271:    my $uhome=&homeserver($uname,$udomain);
                   7272:    my $items='';
1.715     albertel 7273:    foreach my $key (keys(%$storehash)) {
                   7274:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7275:    }
1.715     albertel 7276:    $items=~s/\&$//;
1.716     albertel 7277:    my $esc_symb=&escape($symb);
                   7278:    my $esc_v=&escape($version);
1.715     albertel 7279:    my $reply =
1.716     albertel 7280:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7281: 	      $uhome);
1.1172.2.59  raeburn  7282:    if (($tolog) && ($reply eq 'ok')) {
                   7283:        my $namevalue='';
                   7284:        foreach my $key (keys(%{$storehash})) {
                   7285:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7286:        }
1.1172.2.134  raeburn  7287:        my $ip = &get_requestor_ip();
1.1172.2.135  raeburn  7288:        $namevalue .= 'ip='.&escape($ip).
1.1172.2.59  raeburn  7289:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7290:                      '&version='.$esc_v.
                   7291:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7292:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7293:    }
1.715     albertel 7294:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7295:        # gfall back to way things use to be done
1.715     albertel 7296:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7297: 			    $uname);
1.524     raeburn  7298:    }
1.715     albertel 7299:    return $reply;
                   7300: }
                   7301: 
                   7302: sub old_putstore {
1.716     albertel 7303:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7304:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7305:     if (!$uname) { $uname=$env{'user.name'}; }
                   7306:     my $uhome=&homeserver($uname,$udomain);
                   7307:     my %newstorehash;
1.800     albertel 7308:     foreach my $item (keys(%$storehash)) {
                   7309: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7310: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7311:     }
                   7312:     my $items='';
                   7313:     my %allitems = ();
1.800     albertel 7314:     foreach my $item (keys(%newstorehash)) {
                   7315: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7316: 	    my $key = $1.':keys:'.$2;
                   7317: 	    $allitems{$key} .= $3.':';
                   7318: 	}
1.800     albertel 7319: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7320:     }
1.800     albertel 7321:     foreach my $item (keys(%allitems)) {
                   7322: 	$allitems{$item} =~ s/\:$//;
                   7323: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7324:     }
                   7325:     $items=~s/\&$//;
                   7326:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7327: }
                   7328: 
1.47      www      7329: # ------------------------------------------------------ critical put interface
                   7330: 
                   7331: sub cput {
1.134     albertel 7332:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7333:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7334:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7335:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7336:    my $items='';
1.800     albertel 7337:    foreach my $item (keys(%$storehash)) {
                   7338:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7339:    }
1.47      www      7340:    $items=~s/\&$//;
1.134     albertel 7341:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7342: }
                   7343: 
                   7344: # -------------------------------------------------------------- eget interface
                   7345: 
                   7346: sub eget {
1.133     albertel 7347:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7348:    my $items='';
1.800     albertel 7349:    foreach my $item (@$storearr) {
                   7350:        $items.=&escape($item).'&';
1.191     harris41 7351:    }
1.12      www      7352:    $items=~s/\&$//;
1.620     albertel 7353:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7354:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7355:    my $uhome=&homeserver($uname,$udomain);
                   7356:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7357:    my @pairs=split(/\&/,$rep);
                   7358:    my %returnhash=();
1.42      www      7359:    my $i=0;
1.800     albertel 7360:    foreach my $item (@$storearr) {
                   7361:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7362:       $i++;
1.191     harris41 7363:    }
1.12      www      7364:    return %returnhash;
                   7365: }
                   7366: 
1.667     albertel 7367: # ------------------------------------------------------------ tmpput interface
                   7368: sub tmpput {
1.802     raeburn  7369:     my ($storehash,$server,$context)=@_;
1.667     albertel 7370:     my $items='';
1.800     albertel 7371:     foreach my $item (keys(%$storehash)) {
                   7372: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7373:     }
                   7374:     $items=~s/\&$//;
1.802     raeburn  7375:     if (defined($context)) {
                   7376:         $items .= ':'.&escape($context);
                   7377:     }
1.667     albertel 7378:     return &reply("tmpput:$items",$server);
                   7379: }
                   7380: 
                   7381: # ------------------------------------------------------------ tmpget interface
                   7382: sub tmpget {
1.688     albertel 7383:     my ($token,$server)=@_;
                   7384:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7385:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7386:     my %returnhash;
1.1172.2.85  raeburn  7387:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7388:         return %returnhash;
                   7389:     }
1.667     albertel 7390:     foreach my $item (split(/\&/,$rep)) {
                   7391: 	my ($key,$value)=split(/=/,$item);
                   7392: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7393:     }
                   7394:     return %returnhash;
                   7395: }
                   7396: 
1.1113    raeburn  7397: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7398: sub tmpdel {
                   7399:     my ($token,$server)=@_;
                   7400:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7401:     return &reply("tmpdel:$token",$server);
                   7402: }
                   7403: 
1.1172.2.13  raeburn  7404: # ------------------------------------------------------------ get_timebased_id
                   7405: 
                   7406: sub get_timebased_id {
                   7407:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7408:         $maxtries) = @_;
                   7409:     my ($newid,$error,$dellock);
                   7410:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7411:         return ('','ok','invalid call to get suffix');
                   7412:     }
                   7413: 
                   7414: # set defaults for any optional args for which values were not supplied
                   7415:     if ($who eq '') {
                   7416:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7417:     }
                   7418:     if (!$locktries) {
                   7419:         $locktries = 3;
                   7420:     }
                   7421:     if (!$maxtries) {
                   7422:         $maxtries = 10;
                   7423:     }
                   7424: 
                   7425:     if (($cdom eq '') || ($cnum eq '')) {
                   7426:         if ($env{'request.course.id'}) {
                   7427:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7428:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7429:         }
                   7430:         if (($cdom eq '') || ($cnum eq '')) {
                   7431:             return ('','ok','call to get suffix not in course context');
                   7432:         }
                   7433:     }
                   7434: 
                   7435: # construct locking item
                   7436:     my $lockhash = {
                   7437:                       $prefix."\0".'locked_'.$keyid => $who,
                   7438:                    };
                   7439:     my $tries = 0;
                   7440: 
                   7441: # attempt to get lock on nohist_$namespace file
                   7442:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7443:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7444:         $tries ++;
                   7445:         sleep 1;
                   7446:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7447:     }
                   7448: 
                   7449: # attempt to get unique identifier, based on current timestamp
                   7450:     if ($gotlock eq 'ok') {
                   7451:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7452:         my $id = time;
                   7453:         $newid = $id;
1.1172.2.56  raeburn  7454:         if ($idtype eq 'addcode') {
                   7455:             $newid .= &sixnum_code();
                   7456:         }
1.1172.2.13  raeburn  7457:         my $idtries = 0;
                   7458:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7459:             if ($idtype eq 'concat') {
                   7460:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7461:             } elsif ($idtype eq 'addcode') {
                   7462:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7463:             } else {
                   7464:                 $newid ++;
                   7465:             }
                   7466:             $idtries ++;
                   7467:         }
                   7468:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7469:             my %new_item =  (
                   7470:                               $prefix."\0".$newid => $who,
                   7471:                             );
                   7472:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7473:                                                  $cdom,$cnum);
                   7474:             if ($putresult ne 'ok') {
                   7475:                 undef($newid);
                   7476:                 $error = 'error saving new item: '.$putresult;
                   7477:             }
                   7478:         } else {
1.1172.2.56  raeburn  7479:              undef($newid);
1.1172.2.13  raeburn  7480:              $error = ('error: no unique suffix available for the new item ');
                   7481:         }
                   7482: #  remove lock
                   7483:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7484:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7485:     } else {
                   7486:         $error = "error: could not obtain lockfile\n";
                   7487:         $dellock = 'ok';
1.1172.2.58  raeburn  7488:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7489:             $dellock = 'nolock';
                   7490:         }
1.1172.2.13  raeburn  7491:     }
                   7492:     return ($newid,$dellock,$error);
                   7493: }
                   7494: 
1.1172.2.56  raeburn  7495: sub sixnum_code {
                   7496:     my $code;
                   7497:     for (0..6) {
                   7498:         $code .= int( rand(9) );
                   7499:     }
                   7500:     return $code;
                   7501: }
                   7502: 
1.765     albertel 7503: # -------------------------------------------------- portfolio access checking
                   7504: 
                   7505: sub portfolio_access {
1.1172.2.77  raeburn  7506:     my ($requrl,$clientip) = @_;
1.765     albertel 7507:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7508:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7509:     if ($result) {
                   7510:         my %setters;
                   7511:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1172.2.142  raeburn  7512:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
                   7513:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
                   7514:             if (($startblock && $endblock) || ($by_ip))  {
1.814     raeburn  7515:                 return 'B';
                   7516:             }
                   7517:         } else {
1.1172.2.142  raeburn  7518:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdo) =
                   7519:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   7520:             if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  7521:                 return 'B';
                   7522:             }
                   7523:         }
                   7524:     }
1.765     albertel 7525:     if ($result eq 'ok') {
1.766     albertel 7526:        return 'F';
1.765     albertel 7527:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7528:        return 'A';
1.765     albertel 7529:     }
1.766     albertel 7530:     return '';
1.765     albertel 7531: }
                   7532: 
                   7533: sub get_portfolio_access {
1.1172.2.77  raeburn  7534:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7535: 
                   7536:     if (!ref($access_hash)) {
                   7537: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7538: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7539: 						   $file_name);
                   7540: 	$access_hash = $access_controls{$file_name};
                   7541:     }
                   7542: 
1.1172.2.77  raeburn  7543:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7544:     my $now = time;
                   7545:     if (ref($access_hash) eq 'HASH') {
                   7546:         foreach my $key (keys(%{$access_hash})) {
                   7547:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7548:             if ($start > $now) {
                   7549:                 next;
                   7550:             }
                   7551:             if ($end && $end<$now) {
                   7552:                 next;
                   7553:             }
                   7554:             if ($scope eq 'public') {
                   7555:                 $public = $key;
                   7556:                 last;
                   7557:             } elsif ($scope eq 'guest') {
                   7558:                 $guest = $key;
                   7559:             } elsif ($scope eq 'domains') {
                   7560:                 push(@domains,$key);
                   7561:             } elsif ($scope eq 'users') {
                   7562:                 push(@users,$key);
                   7563:             } elsif ($scope eq 'course') {
                   7564:                 push(@courses,$key);
                   7565:             } elsif ($scope eq 'group') {
                   7566:                 push(@groups,$key);
1.1172.2.77  raeburn  7567:             } elsif ($scope eq 'ip') {
                   7568:                 push(@ips,$key);
1.765     albertel 7569:             }
                   7570:         }
                   7571:         if ($public) {
                   7572:             return 'ok';
1.1172.2.77  raeburn  7573:         } elsif (@ips > 0) {
                   7574:             my $allowed;
                   7575:             foreach my $ipkey (@ips) {
                   7576:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7577:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7578:                         $allowed = 1;
                   7579:                         last;
                   7580:                     }
                   7581:                 }
                   7582:             }
                   7583:             if ($allowed) {
                   7584:                 return 'ok';
                   7585:             }
1.765     albertel 7586:         }
                   7587:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7588:             if ($guest) {
                   7589:                 return $guest;
                   7590:             }
                   7591:         } else {
                   7592:             if (@domains > 0) {
                   7593:                 foreach my $domkey (@domains) {
                   7594:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7595:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7596:                             return 'ok';
                   7597:                         }
                   7598:                     }
                   7599:                 }
                   7600:             }
                   7601:             if (@users > 0) {
                   7602:                 foreach my $userkey (@users) {
1.865     raeburn  7603:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7604:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7605:                             if (ref($item) eq 'HASH') {
                   7606:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7607:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7608:                                     return 'ok';
                   7609:                                 }
                   7610:                             }
                   7611:                         }
                   7612:                     } 
1.765     albertel 7613:                 }
                   7614:             }
                   7615:             my %roleshash;
                   7616:             my @courses_and_groups = @courses;
                   7617:             push(@courses_and_groups,@groups); 
                   7618:             if (@courses_and_groups > 0) {
                   7619:                 my (%allgroups,%allroles); 
                   7620:                 my ($start,$end,$role,$sec,$group);
                   7621:                 foreach my $envkey (%env) {
1.1060    raeburn  7622:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7623:                         my $cid = $2.'_'.$3; 
                   7624:                         if ($1 eq 'gr') {
                   7625:                             $group = $4;
                   7626:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7627:                         } else {
                   7628:                             if ($4 eq '') {
                   7629:                                 $sec = 'none';
                   7630:                             } else {
                   7631:                                 $sec = $4;
                   7632:                             }
                   7633:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7634:                         }
1.811     albertel 7635:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7636:                         my $cid = $2.'_'.$3;
                   7637:                         if ($4 eq '') {
                   7638:                             $sec = 'none';
                   7639:                         } else {
                   7640:                             $sec = $4;
                   7641:                         }
                   7642:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7643:                     }
                   7644:                 }
                   7645:                 if (keys(%allroles) == 0) {
                   7646:                     return;
                   7647:                 }
                   7648:                 foreach my $key (@courses_and_groups) {
                   7649:                     my %content = %{$$access_hash{$key}};
                   7650:                     my $cnum = $content{'number'};
                   7651:                     my $cdom = $content{'domain'};
                   7652:                     my $cid = $cdom.'_'.$cnum;
                   7653:                     if (!exists($allroles{$cid})) {
                   7654:                         next;
                   7655:                     }    
                   7656:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7657:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7658:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7659:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7660:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7661:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7662:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7663:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7664:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7665:                                         if (grep/^all$/,@sections) {
                   7666:                                             return 'ok';
                   7667:                                         } else {
                   7668:                                             if (grep/^$sec$/,@sections) {
                   7669:                                                 return 'ok';
                   7670:                                             }
                   7671:                                         }
                   7672:                                     }
                   7673:                                 }
                   7674:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7675:                                     if (grep/^none$/,@groups) {
                   7676:                                         return 'ok';
                   7677:                                     }
                   7678:                                 } else {
                   7679:                                     if (grep/^all$/,@groups) {
                   7680:                                         return 'ok';
                   7681:                                     } 
                   7682:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7683:                                         if (grep/^$group$/,@groups) {
                   7684:                                             return 'ok';
                   7685:                                         }
                   7686:                                     }
                   7687:                                 } 
                   7688:                             }
                   7689:                         }
                   7690:                     }
                   7691:                 }
                   7692:             }
                   7693:             if ($guest) {
                   7694:                 return $guest;
                   7695:             }
                   7696:         }
                   7697:     }
                   7698:     return;
                   7699: }
                   7700: 
                   7701: sub course_group_datechecker {
                   7702:     my ($dates,$now,$status) = @_;
                   7703:     my ($start,$end) = split(/\./,$dates);
                   7704:     if (!$start && !$end) {
                   7705:         return 'ok';
                   7706:     }
                   7707:     if (grep/^active$/,@{$status}) {
                   7708:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7709:             return 'ok';
                   7710:         }
                   7711:     }
                   7712:     if (grep/^previous$/,@{$status}) {
                   7713:         if ($end > $now ) {
                   7714:             return 'ok';
                   7715:         }
                   7716:     }
                   7717:     if (grep/^future$/,@{$status}) {
                   7718:         if ($start > $now) {
                   7719:             return 'ok';
                   7720:         }
                   7721:     }
                   7722:     return; 
                   7723: }
                   7724: 
                   7725: sub parse_portfolio_url {
                   7726:     my ($url) = @_;
                   7727: 
                   7728:     my ($type,$udom,$unum,$group,$file_name);
                   7729:     
1.823     albertel 7730:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7731: 	$type = 1;
                   7732:         $udom = $1;
                   7733:         $unum = $2;
                   7734:         $file_name = $3;
1.823     albertel 7735:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7736: 	$type = 2;
                   7737:         $udom = $1;
                   7738:         $unum = $2;
                   7739:         $group = $3;
                   7740:         $file_name = $3.'/'.$4;
                   7741:     }
                   7742:     if (wantarray) {
                   7743: 	return ($type,$udom,$unum,$file_name,$group);
                   7744:     }
                   7745:     return $type;
                   7746: }
                   7747: 
                   7748: sub is_portfolio_url {
                   7749:     my ($url) = @_;
                   7750:     return scalar(&parse_portfolio_url($url));
                   7751: }
                   7752: 
1.798     raeburn  7753: sub is_portfolio_file {
                   7754:     my ($file) = @_;
1.820     raeburn  7755:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7756:         return 1;
                   7757:     }
                   7758:     return;
                   7759: }
                   7760: 
1.976     raeburn  7761: sub usertools_access {
1.1084    raeburn  7762:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7763:     my ($access,%tools);
                   7764:     if ($context eq '') {
                   7765:         $context = 'tools';
                   7766:     }
                   7767:     if ($context eq 'requestcourses') {
                   7768:         %tools = (
                   7769:                       official   => 1,
                   7770:                       unofficial => 1,
1.1006    raeburn  7771:                       community  => 1,
1.1172.2.37  raeburn  7772:                       textbook   => 1,
1.985     raeburn  7773:                  );
1.1172.2.9  raeburn  7774:     } elsif ($context eq 'requestauthor') {
                   7775:         %tools = (
                   7776:                       requestauthor => 1,
                   7777:                  );
1.985     raeburn  7778:     } else {
                   7779:         %tools = (
                   7780:                       aboutme   => 1,
                   7781:                       blog      => 1,
1.1172.2.6  raeburn  7782:                       webdav    => 1,
1.985     raeburn  7783:                       portfolio => 1,
1.1172.2.146.  .6(raebu 7784:22):                       timezone  => 1,
1.985     raeburn  7785:                  );
                   7786:     }
1.976     raeburn  7787:     return if (!defined($tools{$tool}));
                   7788: 
1.1172.2.35  raeburn  7789:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7790:         $udom = $env{'user.domain'};
                   7791:         $uname = $env{'user.name'};
                   7792:     }
                   7793: 
1.978     raeburn  7794:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7795:         if ($action ne 'reload') {
1.985     raeburn  7796:             if ($context eq 'requestcourses') {
                   7797:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7798:             } elsif ($context eq 'requestauthor') {
                   7799:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7800:             } else {
                   7801:                 return $env{'environment.availabletools.'.$tool};
                   7802:             }
                   7803:         }
1.976     raeburn  7804:     }
                   7805: 
1.1172.2.9  raeburn  7806:     my ($toolstatus,$inststatus,$envkey);
                   7807:     if ($context eq 'requestauthor') {
                   7808:         $envkey = $context;
                   7809:     } else {
                   7810:         $envkey = $context.'.'.$tool;
                   7811:     }
1.976     raeburn  7812: 
1.985     raeburn  7813:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7814:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7815:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7816:         $inststatus = $env{'environment.inststatus'};
                   7817:     } else {
1.1084    raeburn  7818:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7819:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7820:             $inststatus = $userenvref->{'inststatus'};
                   7821:         } else {
1.1172.2.9  raeburn  7822:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7823:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7824:             $inststatus = $userenv{'inststatus'};
                   7825:         }
1.976     raeburn  7826:     }
                   7827: 
                   7828:     if ($toolstatus ne '') {
                   7829:         if ($toolstatus) {
                   7830:             $access = 1;
                   7831:         } else {
                   7832:             $access = 0;
                   7833:         }
                   7834:         return $access;
                   7835:     }
                   7836: 
1.1084    raeburn  7837:     my ($is_adv,%domdef);
                   7838:     if (ref($is_advref) eq 'HASH') {
                   7839:         $is_adv = $is_advref->{'is_adv'};
                   7840:     } else {
                   7841:         $is_adv = &is_advanced_user($udom,$uname);
                   7842:     }
                   7843:     if (ref($domdefref) eq 'HASH') {
                   7844:         %domdef = %{$domdefref};
                   7845:     } else {
                   7846:         %domdef = &get_domain_defaults($udom);
                   7847:     }
1.976     raeburn  7848:     if (ref($domdef{$tool}) eq 'HASH') {
                   7849:         if ($is_adv) {
                   7850:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7851:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7852:                     $access = 1;
                   7853:                 } else {
                   7854:                     $access = 0;
                   7855:                 }
                   7856:                 return $access;
                   7857:             }
                   7858:         }
                   7859:         if ($inststatus ne '') {
                   7860:             my ($hasaccess,$hasnoaccess);
                   7861:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7862:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7863:                     if ($domdef{$tool}{$affiliation}) {
                   7864:                         $hasaccess = 1;
                   7865:                     } else {
                   7866:                         $hasnoaccess = 1;
                   7867:                     }
                   7868:                 }
                   7869:             }
                   7870:             if ($hasaccess || $hasnoaccess) {
                   7871:                 if ($hasaccess) {
                   7872:                     $access = 1;
                   7873:                 } elsif ($hasnoaccess) {
                   7874:                     $access = 0; 
                   7875:                 }
                   7876:                 return $access;
                   7877:             }
                   7878:         } else {
                   7879:             if ($domdef{$tool}{'default'} ne '') {
                   7880:                 if ($domdef{$tool}{'default'}) {
                   7881:                     $access = 1;
                   7882:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7883:                     $access = 0;
                   7884:                 }
                   7885:                 return $access;
                   7886:             }
                   7887:         }
                   7888:     } else {
1.1172.2.6  raeburn  7889:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7890:             $access = 1;
                   7891:         } else {
                   7892:             $access = 0;
                   7893:         }
1.976     raeburn  7894:         return $access;
                   7895:     }
                   7896: }
                   7897: 
1.1050    raeburn  7898: sub is_course_owner {
                   7899:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7900:     if (($udom eq '') || ($uname eq '')) {
                   7901:         $udom = $env{'user.domain'};
                   7902:         $uname = $env{'user.name'};
                   7903:     }
                   7904:     unless (($udom eq '') || ($uname eq '')) {
                   7905:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7906:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7907:                 return 1;
                   7908:             } else {
                   7909:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7910:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7911:                     return 1;
                   7912:                 }
                   7913:             }
                   7914:         }
                   7915:     }
                   7916:     return;
                   7917: }
                   7918: 
1.976     raeburn  7919: sub is_advanced_user {
                   7920:     my ($udom,$uname) = @_;
1.1085    raeburn  7921:     if ($udom ne '' && $uname ne '') {
                   7922:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7923:             if (wantarray) {
                   7924:                 return ($env{'user.adv'},$env{'user.author'});
                   7925:             } else {
                   7926:                 return $env{'user.adv'};
                   7927:             }
1.1085    raeburn  7928:         }
                   7929:     }
1.976     raeburn  7930:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7931:     my %allroles;
1.1128    raeburn  7932:     my ($is_adv,$is_author);
1.976     raeburn  7933:     foreach my $role (keys(%roleshash)) {
                   7934:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7935:         my $area = '/'.$tdomain.'/'.$trest;
                   7936:         if ($sec ne '') {
                   7937:             $area .= '/'.$sec;
                   7938:         }
                   7939:         if (($area ne '') && ($trole ne '')) {
                   7940:             my $spec=$trole.'.'.$area;
                   7941:             if ($trole =~ /^cr\//) {
                   7942:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7943:             } elsif ($trole ne 'gr') {
                   7944:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7945:             }
1.1128    raeburn  7946:             if ($trole eq 'au') {
                   7947:                 $is_author = 1;
                   7948:             }
1.976     raeburn  7949:         }
                   7950:     }
                   7951:     foreach my $role (keys(%allroles)) {
                   7952:         last if ($is_adv);
                   7953:         foreach my $item (split(/:/,$allroles{$role})) {
                   7954:             if ($item ne '') {
                   7955:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7956:                 if ($privilege eq 'adv') {
                   7957:                     $is_adv = 1;
                   7958:                     last;
                   7959:                 }
                   7960:             }
                   7961:         }
                   7962:     }
1.1128    raeburn  7963:     if (wantarray) {
                   7964:         return ($is_adv,$is_author);
                   7965:     }
1.976     raeburn  7966:     return $is_adv;
                   7967: }
1.798     raeburn  7968: 
1.1035    raeburn  7969: sub check_can_request {
1.1036    raeburn  7970:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7971:     my $canreq = 0;
                   7972:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7973:     my @options = ('approval','validate','autolimit');
                   7974:     my $optregex = join('|',@options);
                   7975:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7976:         foreach my $type (@{$types}) {
                   7977:             if (&usertools_access($env{'user.name'},
                   7978:                                   $env{'user.domain'},
                   7979:                                   $type,undef,'requestcourses')) {
                   7980:                 $canreq ++;
1.1036    raeburn  7981:                 if (ref($request_domains) eq 'HASH') {
                   7982:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7983:                 }
1.1035    raeburn  7984:                 if ($dom eq $env{'user.domain'}) {
                   7985:                     $can_request->{$type} = 1;
                   7986:                 }
                   7987:             }
                   7988:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7989:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7990:                 if (@curr > 0) {
1.1036    raeburn  7991:                     foreach my $item (@curr) {
                   7992:                         if (ref($request_domains) eq 'HASH') {
                   7993:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7994:                             if ($otherdom ne '') {
                   7995:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7996:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7997:                                         push(@{$request_domains->{$type}},$otherdom);
                   7998:                                     }
                   7999:                                 } else {
                   8000:                                     push(@{$request_domains->{$type}},$otherdom);
                   8001:                                 }
                   8002:                             }
                   8003:                         }
                   8004:                     }
                   8005:                     unless($dom eq $env{'user.domain'}) {
                   8006:                         $canreq ++;
1.1035    raeburn  8007:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   8008:                             $can_request->{$type} = 1;
                   8009:                         }
                   8010:                     }
                   8011:                 }
                   8012:             }
                   8013:         }
                   8014:     }
                   8015:     return $canreq;
                   8016: }
                   8017: 
1.341     www      8018: # ---------------------------------------------- Custom access rule evaluation
                   8019: 
                   8020: sub customaccess {
                   8021:     my ($priv,$uri)=@_;
1.807     albertel 8022:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      8023:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 8024:     $udom = &LONCAPA::clean_domain($udom);
                   8025:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      8026:     my $access=0;
1.800     albertel 8027:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 8028: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   8029: 	if ($type eq 'user') {
                   8030: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 8031: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 8032: 		if ($tdom) {
                   8033: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   8034: 		}
1.896     albertel 8035: 		if ($tuname) {
                   8036: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 8037: 		}
                   8038: 		$access=($effect eq 'allow');
                   8039: 		last;
                   8040: 	    }
                   8041: 	} else {
                   8042: 	    if ($role) {
                   8043: 		if ($role ne $urole) { next; }
                   8044: 	    }
                   8045: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   8046: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   8047: 		if ($tdom) {
                   8048: 		    if ($tdom ne $udom) { next; }
                   8049: 		}
                   8050: 		if ($tcrs) {
                   8051: 		    if ($tcrs ne $ucrs) { next; }
                   8052: 		}
                   8053: 		if ($tsec) {
                   8054: 		    if ($tsec ne $usec) { next; }
                   8055: 		}
                   8056: 		$access=($effect eq 'allow');
                   8057: 		last;
                   8058: 	    }
                   8059: 	    if ($realm eq '' && $role eq '') {
                   8060: 		$access=($effect eq 'allow');
                   8061: 	    }
1.402     bowersj2 8062: 	}
1.341     www      8063:     }
                   8064:     return $access;
                   8065: }
                   8066: 
1.103     harris41 8067: # ------------------------------------------------- Check for a user privilege
1.12      www      8068: 
                   8069: sub allowed {
1.1172.2.146.  .1(raebu 8070:22):     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
1.705     albertel 8071:     my $ver_orguri=$uri;
1.439     www      8072:     $uri=&deversion($uri);
1.152     www      8073:     my $orguri=$uri;
1.52      www      8074:     $uri=&declutter($uri);
1.809     raeburn  8075: 
1.810     raeburn  8076:     if ($priv eq 'evb') {
1.1172.2.146.  .3(raebu 8077:22): # Evade communication block restrictions for specified role in a course or domain
1.810     raeburn  8078:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   8079:             return $1;
                   8080:         } else {
                   8081:             return;
                   8082:         }
                   8083:     }
                   8084: 
1.620     albertel 8085:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      8086: # Free bre access to adm and meta resources
1.1172.2.146.  .1(raebu 8087:22):     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
1.769     albertel 8088: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   8089: 	&& ($priv eq 'bre')) {
1.14      www      8090: 	return 'F';
1.159     www      8091:     }
                   8092: 
1.545     banghart 8093: # Free bre access to user's own portfolio contents
1.714     raeburn  8094:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  8095:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  8096: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  8097:         my %setters;
1.1172.2.142  raeburn  8098:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   8099:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   8100:         if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  8101:             return 'B';
                   8102:         } else {
                   8103:             return 'F';
                   8104:         }
1.545     banghart 8105:     }
                   8106: 
1.762     raeburn  8107: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  8108:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   8109:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   8110:         if (exists($env{'request.course.id'})) {
                   8111:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8112:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8113:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   8114:                 my $courseprivid=$env{'request.course.id'};
                   8115:                 $courseprivid=~s/\_/\//;
                   8116:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   8117:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   8118:                     return $1; 
1.762     raeburn  8119:                 } else {
                   8120:                     if ($env{'request.course.sec'}) {
                   8121:                         $courseprivid.='/'.$env{'request.course.sec'};
                   8122:                     }
                   8123:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   8124:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   8125:                         return $2;
                   8126:                     }
1.714     raeburn  8127:                 }
                   8128:             }
                   8129:         }
                   8130:     }
                   8131: 
1.159     www      8132: # Free bre to public access
                   8133: 
                   8134:     if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8135:22):         my $copyright;
                   8136:22):         unless ($uri =~ /ext\.tool/) {
                   8137:22):             $copyright=&metadata($uri,'copyright');
                   8138:22):         }
1.620     albertel 8139: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      8140:            return 'F'; 
                   8141:         }
1.238     www      8142:         if ($copyright eq 'priv') {
                   8143:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8144: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      8145: 		return '';
                   8146:             }
                   8147:         }
                   8148:         if ($copyright eq 'domain') {
                   8149:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8150: 	    unless (($env{'user.domain'} eq $1) ||
                   8151:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      8152: 		return '';
                   8153:             }
1.262     matthew  8154:         }
1.620     albertel 8155:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  8156:             # Library role, so allow browsing of resources in this domain.
                   8157:             return 'F';
1.238     www      8158:         }
1.341     www      8159:         if ($copyright eq 'custom') {
                   8160: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   8161:         }
1.14      www      8162:     }
1.264     matthew  8163:     # Domain coordinator is trying to create a course
1.620     albertel 8164:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  8165:         # uri is the requested domain in this case.
                   8166:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  8167:         # a role of dc for the domain in question.
1.620     albertel 8168:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  8169:     }
1.29      www      8170: 
1.52      www      8171:     my $thisallowed='';
                   8172:     my $statecond=0;
                   8173:     my $courseprivid='';
                   8174: 
1.1039    raeburn  8175:     my $ownaccess;
1.1043    raeburn  8176:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  8177:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   8178:         if ($uri eq '') {
                   8179:             $ownaccess = 1;
                   8180:         } else {
                   8181:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   8182:                 my $udom = $env{'user.domain'};
                   8183:                 my $uname = $env{'user.name'};
                   8184:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   8185:                     $ownaccess = 1;
1.1040    raeburn  8186:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  8187:                     unless ($uri =~ m{\.\./}) {
                   8188:                         $ownaccess = 1;
                   8189:                     }
                   8190:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   8191:                     my $now = time;
                   8192:                     if ($uri =~ m{^([^/]+)/?$}) {
                   8193:                         my $adom = $1;
                   8194:                         foreach my $key (keys(%env)) {
1.1042    raeburn  8195:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1172.2.142  raeburn  8196:                                 my ($start,$end) = split(/\./,$env{$key});
                   8197:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1039    raeburn  8198:                                     $ownaccess = 1;
                   8199:                                     last;
                   8200:                                 }
                   8201:                             }
                   8202:                         }
                   8203:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8204:                         my $adom = $1;
                   8205:                         my $aname = $2;
1.1042    raeburn  8206:                         foreach my $role ('ca','aa') { 
                   8207:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8208:                                 my ($start,$end) =
1.1172.2.142  raeburn  8209:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
                   8210:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1042    raeburn  8211:                                     $ownaccess = 1;
                   8212:                                     last;
                   8213:                                 }
1.1039    raeburn  8214:                             }
                   8215:                         }
                   8216:                     }
                   8217:                 }
                   8218:             }
                   8219:         }
                   8220:     }
                   8221: 
1.52      www      8222: # Course
                   8223: 
1.620     albertel 8224:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8225:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8226:             $thisallowed.=$1;
                   8227:         }
1.52      www      8228:     }
1.29      www      8229: 
1.52      www      8230: # Domain
                   8231: 
1.620     albertel 8232:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8233:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8234:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8235:             $thisallowed.=$1;
                   8236:         }
1.12      www      8237:     }
1.52      www      8238: 
1.1141    raeburn  8239: # User who is not author or co-author might still be able to edit
                   8240: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8241:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8242:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8243:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8244:             $thisallowed.=$1;
                   8245:         }
                   8246:     }
                   8247: 
1.52      www      8248: # Course: uri itself is a course
1.66      www      8249:     my $courseuri=$uri;
                   8250:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8251:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8252: 
1.620     albertel 8253:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8254:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  8255:         if ($priv eq 'mip') {
                   8256:             my $rem = $1;
                   8257:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8258:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8259:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8260:                 if ($cdom ne '') {
                   8261:                     my %passwdconf = &get_passwdconf($cdom);
                   8262:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8263:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8264:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8265:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8266:                                 unless (@inststatuses) {
                   8267:                                     @inststatuses = ('default');
                   8268:                                 }
                   8269:                                 foreach my $status (@inststatuses) {
                   8270:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8271:                                         $thisallowed.=$rem;
                   8272:                                     }
                   8273:                                 }
                   8274:                             }
                   8275:                         }
                   8276:                     }
                   8277:                 }
                   8278:             }
                   8279:         } else {
                   8280:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8281:                 $thisallowed.=$1;
                   8282:             }
1.1039    raeburn  8283:         }
1.12      www      8284:     }
1.29      www      8285: 
1.665     albertel 8286: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8287: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8288:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8289: 	$thisallowed='';
1.671     raeburn  8290:         my ($match)=&is_on_map($uri);
                   8291:         if ($match) {
                   8292:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8293:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  8294:                 my $value = $1;
1.1172.2.146.  .1(raebu 8295:22):                 my $deeplinkblock;
                   8296:22):                 unless ($nodeeplinkcheck) {
                   8297:22):                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8298:22):                 }
                   8299:22):                 if ($deeplinkblock) {
                   8300:22):                     $thisallowed='D';
                   8301:22):                 } elsif ($noblockcheck) {
1.1172.2.65  raeburn  8302:                     $thisallowed.=$value;
1.1162    raeburn  8303:                 } else {
1.1172.2.126  raeburn  8304:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8305:                     if (@blockers > 0) {
                   8306:                         $thisallowed = 'B';
                   8307:                     } else {
                   8308:                         $thisallowed.=$value;
                   8309:                     }
1.1162    raeburn  8310:                 }
1.671     raeburn  8311:             }
                   8312:         } else {
1.705     albertel 8313:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8314:             if ($refuri) {
                   8315:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8316:                     $thisallowed='F';
1.671     raeburn  8317:                 } else {
                   8318:                     $refuri=&declutter($refuri);
                   8319:                     my ($match) = &is_on_map($refuri);
                   8320:                     if ($match) {
1.1172.2.146.  .1(raebu 8321:22):                         my $deeplinkblock;
                   8322:22):                         unless ($nodeeplinkcheck) {
                   8323:22):                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8324:22):                         }
                   8325:22):                         if ($deeplinkblock) {
                   8326:22):                             $thisallowed='D';
                   8327:22):                         } elsif ($noblockcheck) {
1.1162    raeburn  8328:                             $thisallowed='F';
1.1172.2.65  raeburn  8329:                         } else {
1.1172.2.127  raeburn  8330:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8331:                             if (@blockers > 0) {
                   8332:                                 $thisallowed = 'B';
                   8333:                             } else {
                   8334:                                 $thisallowed='F';
                   8335:                             }
1.1162    raeburn  8336:                         }
1.671     raeburn  8337:                     }
1.669     raeburn  8338:                 }
1.671     raeburn  8339:             }
                   8340:         }
1.314     www      8341:     }
1.492     albertel 8342: 
1.766     albertel 8343:     if ($priv eq 'bre'
                   8344: 	&& $thisallowed ne 'F' 
                   8345: 	&& $thisallowed ne '2'
                   8346: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8347: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8348:     }
                   8349:     
1.52      www      8350: # Full access at system, domain or course-wide level? Exit.
1.29      www      8351:     if ($thisallowed=~/F/) {
                   8352: 	return 'F';
                   8353:     }
                   8354: 
1.52      www      8355: # If this is generating or modifying users, exit with special codes
1.29      www      8356: 
1.643     www      8357:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8358: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8359: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8360: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8361: 	    unless ($auname) { return $thisallowed; }
                   8362: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8363: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8364: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8365: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8366: 	}
1.52      www      8367: 	return $thisallowed;
                   8368:     }
                   8369: #
1.103     harris41 8370: # Gathered so far: system, domain and course wide privileges
1.52      www      8371: #
                   8372: # Course: See if uri or referer is an individual resource that is part of 
                   8373: # the course
                   8374: 
1.620     albertel 8375:     if ($env{'request.course.id'}) {
1.232     www      8376: 
1.1172.2.115  raeburn  8377: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8378: 
                   8379:         if ($priv eq 'mip') {
                   8380:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8381:                 return $thisallowed;
                   8382:             } else {
                   8383:                 return '';
                   8384:             }
                   8385:         }
                   8386: 
1.620     albertel 8387:        $courseprivid=$env{'request.course.id'};
                   8388:        if ($env{'request.course.sec'}) {
                   8389:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8390:        }
                   8391:        $courseprivid=~s/\_/\//;
                   8392:        my $checkreferer=1;
1.232     www      8393:        my ($match,$cond)=&is_on_map($uri);
                   8394:        if ($match) {
                   8395:            $statecond=$cond;
1.620     albertel 8396:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8397:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8398:                my $value = $1;
                   8399:                if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8400:22):                    my $deeplinkblock;
                   8401:22):                    unless ($nodeeplinkcheck) {
                   8402:22):                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8403:22):                    }
                   8404:22):                    if ($deeplinkblock) {
                   8405:22):                        $thisallowed = 'D';
                   8406:22):                    } elsif ($noblockcheck) {
1.1162    raeburn  8407:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8408:                    } else {
1.1172.2.126  raeburn  8409:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8410:                        if (@blockers > 0) {
                   8411:                            $thisallowed = 'B';
                   8412:                        } else {
                   8413:                            $thisallowed.=$value;
                   8414:                        }
1.1162    raeburn  8415:                    }
                   8416:                } else {
                   8417:                    $thisallowed.=$value;
                   8418:                }
1.52      www      8419:                $checkreferer=0;
                   8420:            }
1.29      www      8421:        }
1.1172.2.126  raeburn  8422: 
1.148     www      8423:        if ($checkreferer) {
1.620     albertel 8424: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8425:             unless ($refuri) {
1.800     albertel 8426:                 foreach my $key (keys(%env)) {
                   8427: 		    if ($key=~/^httpref\..*\*/) {
                   8428: 			my $pattern=$key;
1.156     www      8429:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8430:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8431:                         $pattern=~s/\//\\\//g;
1.152     www      8432:                         if ($orguri=~/$pattern/) {
1.800     albertel 8433: 			    $refuri=$env{$key};
1.148     www      8434:                         }
                   8435:                     }
1.191     harris41 8436:                 }
1.148     www      8437:             }
1.232     www      8438: 
1.148     www      8439:          if ($refuri) { 
1.152     www      8440: 	  $refuri=&declutter($refuri);
1.232     www      8441:           my ($match,$cond)=&is_on_map($refuri);
                   8442:             if ($match) {
                   8443:               my $refstatecond=$cond;
1.620     albertel 8444:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8445:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8446:                   my $value = $1;
                   8447:                   if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8448:22):                       my $deeplinkblock;
                   8449:22):                       unless ($nodeeplinkcheck) {
                   8450:22):                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8451:22):                       }
                   8452:22):                       if ($deeplinkblock) {
                   8453:22):                           $thisallowed = 'D';
                   8454:22):                       } elsif ($noblockcheck) {
1.1162    raeburn  8455:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8456:                       } else {
1.1172.2.127  raeburn  8457:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8458:                           if (@blockers > 0) {
                   8459:                               $thisallowed = 'B';
                   8460:                           } else {
                   8461:                               $thisallowed.=$value;
                   8462:                           }
1.1162    raeburn  8463:                       }
                   8464:                   } else {
                   8465:                       $thisallowed.=$value;
                   8466:                   }
1.53      www      8467:                   $uri=$refuri;
                   8468:                   $statecond=$refstatecond;
1.52      www      8469:               }
                   8470:           }
1.148     www      8471:         }
1.29      www      8472:        }
1.52      www      8473:    }
1.29      www      8474: 
1.52      www      8475: #
1.103     harris41 8476: # Gathered now: all privileges that could apply, and condition number
1.52      www      8477: # 
                   8478: #
                   8479: # Full or no access?
                   8480: #
1.29      www      8481: 
1.52      www      8482:     if ($thisallowed=~/F/) {
                   8483: 	return 'F';
                   8484:     }
1.29      www      8485: 
1.52      www      8486:     unless ($thisallowed) {
                   8487:         return '';
                   8488:     }
1.29      www      8489: 
1.52      www      8490: # Restrictions exist, deal with them
                   8491: #
                   8492: #   C:according to course preferences
                   8493: #   R:according to resource settings
                   8494: #   L:unless locked
                   8495: #   X:according to user session state
                   8496: #
                   8497: 
                   8498: # Possibly locked functionality, check all courses
1.1172.2.142  raeburn  8499: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54      www      8500: # Locks might take effect only after 10 minutes cache expiration for other
1.1172.2.142  raeburn  8501: # courses, and 2 minutes for current course, in which user has st or ta role
                   8502: # which is neither expired nor a future role (unless current course).
1.52      www      8503: 
1.1172.2.142  raeburn  8504:     my ($needlockcheck,$now,$crsonly);
1.52      www      8505:     if ($thisallowed=~/L/) {
1.1172.2.142  raeburn  8506:         $now = time;
                   8507:         if ($priv eq 'bre') {
                   8508:             if ($uri ne '') {
                   8509:                 if ($orguri =~ m{^/+res/}) {
                   8510:                     if ($uri =~ m{^lib/templates/}) {
                   8511:                         if ($env{'request.course.id'}) {
                   8512:                             $crsonly = 1;
                   8513:                             $needlockcheck = 1;
                   8514:                         }
                   8515:                     } else {
                   8516:                         $needlockcheck = 1;
                   8517:                     }
                   8518:                 } elsif ($env{'request.course.id'}) {
                   8519:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
                   8520:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
                   8521:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
                   8522:                         $crsonly = 1;
                   8523:                     }
                   8524:                     $needlockcheck = 1;
                   8525:                 }
                   8526:             }
                   8527:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
                   8528:             $needlockcheck = 1;
                   8529:         }
                   8530:     }
                   8531:     if ($needlockcheck) {
                   8532:         foreach my $envkey (keys(%env)) {
1.54      www      8533:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8534:                my $courseid=$2;
                   8535:                my $roleid=$1.'.'.$2;
1.92      www      8536:                $courseid=~s/^\///;
1.1172.2.142  raeburn  8537:                unless ($env{'request.role'} eq $roleid) {
                   8538:                    my ($start,$end) = split(/\./,$env{$envkey});
                   8539:                    next unless (($now >= $start) && (!$end || $end > $now));
                   8540:                }
1.54      www      8541:                my $expiretime=600;
1.620     albertel 8542:                if ($env{'request.role'} eq $roleid) {
1.54      www      8543: 		  $expiretime=120;
                   8544:                }
                   8545: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8546:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8547:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8548: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8549:                }
1.620     albertel 8550:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8551:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8552: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8553:                        &log($env{'user.domain'},$env{'user.name'},
                   8554:                             $env{'user.home'},
1.57      www      8555:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8556:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8557:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8558: 		       return '';
                   8559:                    }
                   8560:                }
1.620     albertel 8561:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8562:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1172.2.142  raeburn  8563: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620     albertel 8564:                        &log($env{'user.domain'},$env{'user.name'},
                   8565:                             $env{'user.home'},
1.57      www      8566:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8567:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8568:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8569: 		       return '';
                   8570:                    }
                   8571:                }
                   8572: 	   }
1.29      www      8573:        }
1.52      www      8574:     }
1.1172.2.126  raeburn  8575: 
1.52      www      8576: #
                   8577: # Rest of the restrictions depend on selected course
                   8578: #
                   8579: 
1.620     albertel 8580:     unless ($env{'request.course.id'}) {
1.766     albertel 8581: 	if ($thisallowed eq 'A') {
                   8582: 	    return 'A';
1.814     raeburn  8583:         } elsif ($thisallowed eq 'B') {
                   8584:             return 'B';
1.766     albertel 8585: 	} else {
                   8586: 	    return '1';
                   8587: 	}
1.52      www      8588:     }
1.29      www      8589: 
1.52      www      8590: #
                   8591: # Now user is definitely in a course
                   8592: #
1.53      www      8593: 
                   8594: 
                   8595: # Course preferences
                   8596: 
                   8597:    if ($thisallowed=~/C/) {
1.620     albertel 8598:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8599:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8600:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8601: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8602: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8603: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8604: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8605: 			$env{'request.course.id'});
                   8606: 	   }
1.237     www      8607:            return '';
                   8608:        }
                   8609: 
1.620     albertel 8610:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8611: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8612: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8613: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8614: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8615: 			$env{'request.course.id'});
                   8616: 	   }
1.54      www      8617:            return '';
                   8618:        }
1.53      www      8619:    }
                   8620: 
                   8621: # Resource preferences
                   8622: 
                   8623:    if ($thisallowed=~/R/) {
1.620     albertel 8624:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8625:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8626: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8627: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8628: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8629: 	   }
                   8630: 	   return '';
1.54      www      8631:        }
1.53      www      8632:    }
1.30      www      8633: 
1.1172.2.146.  .1(raebu 8634:22): # Restricted for deeplinked session?
                   8635:22): 
                   8636:22):     if ($env{'request.deeplink.login'}) {
                   8637:22):         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
                   8638:22):             if (!$symb) { $symb=&symbread($uri,1); }
                   8639:22):             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
                   8640:22):                 return '';
                   8641:22):             }
                   8642:22):         }
                   8643:22):     }
                   8644:22): 
1.246     www      8645: # Restricted by state or randomout?
1.30      www      8646: 
1.52      www      8647:    if ($thisallowed=~/X/) {
1.620     albertel 8648:       if ($env{'acc.randomout'}) {
1.579     albertel 8649: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8650:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8651:             return ''; 
                   8652:          }
1.247     www      8653:       }
                   8654:       if (&condval($statecond)) {
1.52      www      8655: 	 return '2';
                   8656:       } else {
                   8657:          return '';
                   8658:       }
                   8659:    }
1.30      www      8660: 
1.766     albertel 8661:     if ($thisallowed eq 'A') {
                   8662: 	return 'A';
1.814     raeburn  8663:     } elsif ($thisallowed eq 'B') {
                   8664:         return 'B';
1.1172.2.146.  .1(raebu 8665:22):     } elsif ($thisallowed eq 'D') {
                   8666:22):         return 'D';
1.766     albertel 8667:     }
1.52      www      8668:    return 'F';
1.232     www      8669: }
1.1162    raeburn  8670: 
1.1172.2.13  raeburn  8671: # ------------------------------------------- Check construction space access
                   8672: 
                   8673: sub constructaccess {
                   8674:     my ($url,$setpriv)=@_;
                   8675: 
                   8676: # We do not allow editing of previous versions of files
                   8677:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8678: 
                   8679: # Get username and domain from URL
                   8680:     my ($ownername,$ownerdomain,$ownerhome);
                   8681: 
                   8682:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8683:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8684: 
                   8685: # The URL does not really point to any authorspace, forget it
                   8686:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8687: 
                   8688: # Now we need to see if the user has access to the authorspace of
                   8689: # $ownername at $ownerdomain
                   8690: 
                   8691:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8692: # Real author for this?
                   8693:        $ownerhome = $env{'user.home'};
                   8694:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8695:           return ($ownername,$ownerdomain,$ownerhome);
                   8696:        }
                   8697:     } else {
                   8698: # Co-author for this?
                   8699:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8700:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8701:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8702:             return ($ownername,$ownerdomain,$ownerhome);
                   8703:         }
                   8704:     }
                   8705: 
                   8706: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8707: # we might as well leave
                   8708:    unless ($setpriv) { return ''; }
                   8709: 
                   8710: # Backdoor access?
                   8711:     my $allowed=&allowed('eco',$ownerdomain);
                   8712: # Nope
                   8713:     unless ($allowed) { return ''; }
                   8714: # Looks like we may have access, but could be locked by the owner of the construction space
                   8715:     if ($allowed eq 'U') {
                   8716:         my %blocked=&get('environment',['domcoord.author'],
                   8717:                          $ownerdomain,$ownername);
                   8718: # Is blocked by owner
                   8719:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8720:     }
                   8721:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8722: # Grant temporary access
                   8723:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8724:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8725:         if (!$update) { $update = $then; }
                   8726:         my $refresh=$env{'user.refresh.time'};
                   8727:         if (!$refresh) { $refresh = $update; }
                   8728:         my $now = time;
                   8729:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8730:                            $now,'ca','constructaccess');
                   8731:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8732:         return($ownername,$ownerdomain,$ownerhome);
                   8733:     }
                   8734: # No business here
                   8735:     return '';
                   8736: }
                   8737: 
1.1172.2.66  raeburn  8738: # ----------------------------------------------------------- Content Blocking
                   8739: 
                   8740: {
                   8741: # Caches for faster Course Contents display where content blocking
                   8742: # is in operation (i.e., interval param set) for timed quiz.
                   8743: #
                   8744: # User for whom data are being temporarily cached.
                   8745: my $cacheduser='';
1.1172.2.126  raeburn  8746: # Course for which data are being temporarily cached.
                   8747: my $cachedcid='';
1.1172.2.66  raeburn  8748: # Cached blockers for this user (a hash of blocking items).
                   8749: my %cachedblockers=();
                   8750: # When the data were last cached.
                   8751: my $cachedlast='';
                   8752: 
                   8753: sub load_all_blockers {
1.1172.2.128  raeburn  8754:     my ($uname,$udom)=@_;
1.1172.2.66  raeburn  8755:     if (($uname ne '') && ($udom ne '')) {
                   8756:         if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126  raeburn  8757:             ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128  raeburn  8758:             (abs($cachedlast-time)<5)) {
1.1172.2.66  raeburn  8759:             return;
                   8760:         }
                   8761:     }
                   8762:     $cachedlast=time;
                   8763:     $cacheduser=$uname.':'.$udom;
1.1172.2.126  raeburn  8764:     $cachedcid=$env{'request.course.id'};
1.1172.2.128  raeburn  8765:     %cachedblockers = &get_commblock_resources();
1.1172.2.126  raeburn  8766:     return;
1.1172.2.66  raeburn  8767: }
                   8768: 
1.1162    raeburn  8769: sub get_comm_blocks {
                   8770:     my ($cdom,$cnum) = @_;
                   8771:     if ($cdom eq '' || $cnum eq '') {
                   8772:         return unless ($env{'request.course.id'});
                   8773:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8774:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8775:     }
                   8776:     my %commblocks;
                   8777:     my $hashid=$cdom.'_'.$cnum;
                   8778:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8779:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8780:         %commblocks = %{$blocksref};
                   8781:     } else {
                   8782:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8783:         my $cachetime = 600;
                   8784:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8785:     }
                   8786:     return %commblocks;
                   8787: }
                   8788: 
1.1172.2.66  raeburn  8789: sub get_commblock_resources {
                   8790:     my ($blocks) = @_;
                   8791:     my %blockers = ();
                   8792:     return %blockers unless ($env{'request.course.id'});
1.1172.2.142  raeburn  8793:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8794:     if ($env{'request.course.sec'}) {
                   8795:         $courseurl .= '/'.$env{'request.course.sec'};
                   8796:     }
                   8797:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162    raeburn  8798:     my %commblocks;
                   8799:     if (ref($blocks) eq 'HASH') {
                   8800:         %commblocks = %{$blocks};
                   8801:     } else {
                   8802:         %commblocks = &get_comm_blocks();
                   8803:     }
1.1172.2.66  raeburn  8804:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8805:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8806:     return %blockers unless (ref($navmap));
                   8807:     my $now = time;
1.1162    raeburn  8808:     foreach my $block (keys(%commblocks)) {
                   8809:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8810:             my ($start,$end) = ($1,$2);
                   8811:             if ($start <= $now && $end >= $now) {
                   8812:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8813:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8814:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8815:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8816:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8817:                             }
                   8818:                         }
                   8819:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8820:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8821:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8822:                             }
                   8823:                         }
                   8824:                     }
                   8825:                 }
                   8826:             }
                   8827:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8828:             my $item = $1;
                   8829:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8830:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.142  raeburn  8831:                     my (@interval,$mapname);
1.1172.2.66  raeburn  8832:                     my $type = 'map';
                   8833:                     if ($item eq 'course') {
                   8834:                         $type = 'course';
                   8835:                         @interval=&EXT("resource.0.interval");
                   8836:                     } else {
                   8837:                         if ($item =~ /___\d+___/) {
                   8838:                             $type = 'resource';
                   8839:                             @interval=&EXT("resource.0.interval",$item);
1.1162    raeburn  8840:                         } else {
1.1172.2.142  raeburn  8841:                             $mapname = &deversion($item);
                   8842:                             if (ref($navmap)) {
                   8843:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
                   8844:                                 @interval = ($timelimit,'map');
1.1162    raeburn  8845:                             }
                   8846:                         }
1.1172.2.66  raeburn  8847:                     }
1.1172.2.146.  .1(raebu 8848:22):                     if ($interval[0] =~ /^(\d+)/) {
                   8849:22):                         my $timelimit = $1;
1.1172.2.66  raeburn  8850:                         my $first_access;
                   8851:                         if ($type eq 'resource') {
                   8852:                             $first_access=&get_first_access($interval[1],$item);
                   8853:                         } elsif ($type eq 'map') {
                   8854:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8855:                         } else {
                   8856:                             $first_access=&get_first_access($interval[1]);
                   8857:                         }
                   8858:                         if ($first_access) {
1.1172.2.146.  .1(raebu 8859:22):                             my $timesup = $first_access+$timelimit;
1.1172.2.66  raeburn  8860:                             if ($timesup > $now) {
                   8861:                                 my $activeblock;
1.1172.2.142  raeburn  8862:                                 if ($type eq 'resource') {
                   8863:                                     if (ref($navmap)) {
                   8864:                                         my $res = $navmap->getBySymb($item);
                   8865:                                         if ($res->answerable()) {
                   8866:                                             $activeblock = 1;
                   8867:                                         }
                   8868:                                     }
                   8869:                                 } elsif ($type eq 'map') {
                   8870:                                     my $mapsymb = &symbread($mapname,1);
                   8871:                                     if (($mapsymb) && (ref($navmap))) {
                   8872:                                         my $mapres = $navmap->getBySymb($mapsymb);
                   8873:                                         if (ref($mapres)) {
                   8874:                                             my $first = $mapres->map_start();
                   8875:                                             my $finish = $mapres->map_finish();
                   8876:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   8877:                                             if (ref($it)) {
                   8878:                                                 my $res;
                   8879:                                                 while ($res = $it->next(undef,1)) {
                   8880:                                                     next unless (ref($res));
                   8881:                                                     my $symb = $res->symb();
                   8882:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
                   8883:                                                     @interval=&EXT("resource.0.interval",$symb);
                   8884:                                                     if ($interval[1] eq 'map') {
                   8885:                                                         if ($res->answerable()) {
                   8886:                                                             $activeblock = 1;
                   8887:                                                             last;
                   8888:                                                         }
                   8889:                                                     }
                   8890:                                                 }
                   8891:                                             }
                   8892:                                         }
1.1172.2.66  raeburn  8893:                                     }
                   8894:                                 }
                   8895:                                 if ($activeblock) {
                   8896:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8897:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8898:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8899:                                          }
                   8900:                                     }
                   8901:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8902:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8903:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8904:                                         }
1.1162    raeburn  8905:                                     }
                   8906:                                 }
                   8907:                             }
                   8908:                         }
                   8909:                     }
                   8910:                 }
                   8911:             }
                   8912:         }
                   8913:     }
1.1172.2.66  raeburn  8914:     return %blockers;
1.1162    raeburn  8915: }
                   8916: 
1.1172.2.66  raeburn  8917: sub has_comm_blocking {
1.1172.2.128  raeburn  8918:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66  raeburn  8919:     my @blockers;
                   8920:     return unless ($env{'request.course.id'});
                   8921:     return unless ($priv eq 'bre');
                   8922:     return if ($env{'request.state'} eq 'construct');
1.1172.2.142  raeburn  8923:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8924:     if ($env{'request.course.sec'}) {
                   8925:         $courseurl .= '/'.$env{'request.course.sec'};
                   8926:     }
                   8927:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1172.2.128  raeburn  8928:     my %blockinfo;
                   8929:     if (ref($blocks) eq 'HASH') {
                   8930:         %blockinfo = &get_commblock_resources($blocks);
                   8931:     } else {
                   8932:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   8933:         %blockinfo = %cachedblockers;
                   8934:     }
                   8935:     return unless (keys(%blockinfo) > 0);
1.1172.2.66  raeburn  8936:     my (%possibles,@symbs);
                   8937:     if (!$symb) {
1.1172.2.128  raeburn  8938:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  8939:     }
1.1172.2.66  raeburn  8940:     if ($symb) {
                   8941:         @symbs = ($symb);
                   8942:     } elsif (keys(%possibles)) {
                   8943:         @symbs = keys(%possibles);
                   8944:     }
                   8945:     my $noblock;
                   8946:     foreach my $symb (@symbs) {
                   8947:         last if ($noblock);
                   8948:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128  raeburn  8949:         foreach my $block (keys(%blockinfo)) {
1.1172.2.66  raeburn  8950:             if ($block =~ /^firstaccess____(.+)$/) {
                   8951:                 my $item = $1;
1.1172.2.126  raeburn  8952:                 unless ($blocked) {
                   8953:                     if (($item eq $map) || ($item eq $symb)) {
                   8954:                         $noblock = 1;
                   8955:                         last;
                   8956:                     }
1.1172.2.66  raeburn  8957:                 }
1.1162    raeburn  8958:             }
1.1172.2.128  raeburn  8959:             if (ref($blockinfo{$block}) eq 'HASH') {
                   8960:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   8961:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66  raeburn  8962:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8963:                             push(@blockers,$block);
                   8964:                         }
                   8965:                     }
                   8966:                 }
1.1172.2.128  raeburn  8967:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   8968:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126  raeburn  8969:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8970:                             push(@blockers,$block);
                   8971:                         }
1.1172.2.66  raeburn  8972:                     }
                   8973:                 }
1.1162    raeburn  8974:             }
                   8975:         }
                   8976:     }
1.1172.2.126  raeburn  8977:     unless ($noblock) {
                   8978:         return @blockers;
                   8979:     }
                   8980:     return;
1.1172.2.66  raeburn  8981: }
1.1162    raeburn  8982: }
                   8983: 
1.1172.2.146.  .1(raebu 8984:22): sub deeplink_check {
                   8985:22):     my ($priv,$symb,$uri) = @_;
                   8986:22):     return unless ($env{'request.course.id'});
                   8987:22):     return unless ($priv eq 'bre');
                   8988:22):     return if ($env{'request.state'} eq 'construct');
                   8989:22):     return if ($env{'request.role.adv'});
                   8990:22):     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8991:22):     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8992:22):     my (%possibles,@symbs);
                   8993:22):     if (!$symb) {
                   8994:22):         $symb = &symbread($uri,1,1,1,\%possibles);
                   8995:22):     }
                   8996:22):     if ($symb) {
                   8997:22):         @symbs = ($symb);
                   8998:22):     } elsif (keys(%possibles)) {
                   8999:22):         @symbs = keys(%possibles);
                   9000:22):     }
                   9001:22): 
                   9002:22):     my ($deeplink_symb,$allow);
                   9003:22):     if ($env{'request.deeplink.login'}) {
                   9004:22):         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
                   9005:22):     }
                   9006:22):     foreach my $symb (@symbs) {
                   9007:22):         last if ($allow);
                   9008:22):         my $deeplink = &EXT("resource.0.deeplink",$symb);
                   9009:22):         if ($deeplink eq '') {
                   9010:22):             $allow = 1;
                   9011:22):         } else {
                   9012:22):             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
                   9013:22):             if ($state ne 'only') {
                   9014:22):                 $allow = 1;
                   9015:22):             } else {
                   9016:22):                 my $check_deeplink_entry;
                   9017:22):                 if ($protect ne 'none') {
                   9018:22):                     my ($acctype,$item) = split(/:/,$protect);
                   9019:22):                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
                   9020:22):                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
                   9021:22):                             $check_deeplink_entry = 1
                   9022:22):                         }
                   9023:22):                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
                   9024:22):                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
                   9025:22):                             $check_deeplink_entry = 1;
                   9026:22):                         }
                   9027:22):                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
                   9028:22):                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
                   9029:22):                             $check_deeplink_entry = 1;
                   9030:22):                         }
                   9031:22):                     }
                   9032:22):                 }
                   9033:22):                 if (($protect eq 'none') || ($check_deeplink_entry)) {
                   9034:22):                     if ($scope eq 'res') {
                   9035:22):                         if ($symb eq $deeplink_symb) {
                   9036:22):                             $allow = 1;
                   9037:22):                         }
                   9038:22):                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
                   9039:22):                         my ($map_from_symb,$map_from_login);
                   9040:22):                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
                   9041:22):                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9042:22):                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
                   9043:22):                         } else {
                   9044:22):                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
                   9045:22):                         }
                   9046:22):                         if (($map_from_symb) && ($map_from_login)) {
                   9047:22):                             if ($map_from_symb eq $map_from_login) {
                   9048:22):                                 $allow = 1;
                   9049:22):                             } elsif ($scope eq 'rec') {
                   9050:22):                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
                   9051:22):                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
                   9052:22):                                     $allow = 1;
                   9053:22):                                 }
                   9054:22):                             }
                   9055:22):                         }
                   9056:22):                     }
                   9057:22):                 }
                   9058:22):             }
                   9059:22):         }
                   9060:22):     }
                   9061:22):     return if ($allow);
                   9062:22):     return 1;
                   9063:22): }
                   9064:22): 
1.1172.2.66  raeburn  9065: # -------------------------------- Deversion and split uri into path an filename
                   9066: 
1.1133    foxr     9067: #
1.1172.2.66  raeburn  9068: #   Removes the version from a URI and
1.1133    foxr     9069: #   splits it in to its filename and path to the filename.
                   9070: #   Seems like File::Basename could have done this more clearly.
                   9071: #   Parameters:
                   9072: #      $uri   - input URI
                   9073: #   Returns:
                   9074: #     Two element list consisting of 
                   9075: #     $pathname  - the URI up to and excluding the trailing /
                   9076: #     $filename  - The part of the URI following the last /
                   9077: #  NOTE:
                   9078: #    Another realization of this is simply:
                   9079: #    use File::Basename;
                   9080: #    ...
                   9081: #    $uri = shift;
                   9082: #    $filename = basename($uri);
                   9083: #    $path     = dirname($uri);
                   9084: #    return ($filename, $path);
                   9085: #
                   9086: #     The implementation below is probably faster however.
                   9087: #
1.710     albertel 9088: sub split_uri_for_cond {
                   9089:     my $uri=&deversion(&declutter(shift));
                   9090:     my @uriparts=split(/\//,$uri);
                   9091:     my $filename=pop(@uriparts);
                   9092:     my $pathname=join('/',@uriparts);
                   9093:     return ($pathname,$filename);
                   9094: }
1.232     www      9095: # --------------------------------------------------- Is a resource on the map?
                   9096: 
                   9097: sub is_on_map {
1.710     albertel 9098:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 9099:     #Trying to find the conditional for the file
1.620     albertel 9100:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 9101: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      9102:     if ($match) {
1.289     bowersj2 9103: 	return (1,$1);
                   9104:     } else {
1.434     www      9105: 	return (0,0);
1.289     bowersj2 9106:     }
1.12      www      9107: }
                   9108: 
1.427     www      9109: # --------------------------------------------------------- Get symb from alias
                   9110: 
                   9111: sub get_symb_from_alias {
                   9112:     my $symb=shift;
                   9113:     my ($map,$resid,$url)=&decode_symb($symb);
                   9114: # Already is a symb
                   9115:     if ($url) { return $symb; }
                   9116: # Must be an alias
                   9117:     my $aliassymb='';
                   9118:     my %bighash;
1.620     albertel 9119:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      9120:                             &GDBM_READER(),0640)) {
                   9121:         my $rid=$bighash{'mapalias_'.$symb};
                   9122: 	if ($rid) {
                   9123: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 9124: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   9125: 				    $resid,$bighash{'src_'.$rid});
1.427     www      9126: 	}
                   9127:         untie %bighash;
                   9128:     }
                   9129:     return $aliassymb;
                   9130: }
                   9131: 
1.12      www      9132: # ----------------------------------------------------------------- Define Role
                   9133: 
                   9134: sub definerole {
                   9135:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  9136:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 9137:     foreach my $role (split(':',$sysrole)) {
                   9138: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9139:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   9140:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   9141: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9142:                return "refused:s:$crole&$cqual"; 
                   9143:             }
                   9144:         }
1.191     harris41 9145:     }
1.800     albertel 9146:     foreach my $role (split(':',$domrole)) {
                   9147: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9148:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   9149:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   9150: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      9151:                return "refused:d:$crole&$cqual"; 
                   9152:             }
                   9153:         }
1.191     harris41 9154:     }
1.800     albertel 9155:     foreach my $role (split(':',$courole)) {
                   9156: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9157:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   9158:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   9159: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9160:                return "refused:c:$crole&$cqual"; 
                   9161:             }
                   9162:         }
1.191     harris41 9163:     }
1.1172.2.84  raeburn  9164:     my $uhome;
                   9165:     if (($uname ne '') && ($udom ne '')) {
                   9166:         $uhome = &homeserver($uname,$udom);
                   9167:         return $uhome if ($uhome eq 'no_host');
                   9168:     } else {
                   9169:         $uname = $env{'user.name'};
                   9170:         $udom = $env{'user.domain'};
                   9171:         $uhome = $env{'user.home'};
                   9172:     }
1.620     albertel 9173:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  9174:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      9175:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  9176:     return reply($command,$uhome);
1.12      www      9177:   } else {
                   9178:     return 'refused';
                   9179:   }
1.105     harris41 9180: }
                   9181: 
                   9182: # ---------------- Make a metadata query against the network of library servers
                   9183: 
                   9184: sub metadata_query {
1.1172.2.33  raeburn  9185:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 9186:     my %rhash;
1.845     albertel 9187:     my %libserv = &all_library();
1.244     matthew  9188:     my @server_list = (defined($server_array) ? @$server_array
                   9189:                                               : keys(%libserv) );
                   9190:     for my $server (@server_list) {
1.1172.2.33  raeburn  9191:         my $domains = '';
                   9192:         if (ref($domains_hash) eq 'HASH') {
                   9193:             $domains = $domains_hash->{$server};    
                   9194:         }
1.118     harris41 9195: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  9196: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 9197: 	    $rhash{$server}=$reply;
                   9198: 	}
                   9199: 	else {
                   9200: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  9201: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 9202: 			     $server);
                   9203: 	    $rhash{$server}=$reply;
                   9204: 	}
1.112     harris41 9205:     }
1.118     harris41 9206:     return \%rhash;
1.240     www      9207: }
                   9208: 
                   9209: # ----------------------------------------- Send log queries and wait for reply
                   9210: 
                   9211: sub log_query {
                   9212:     my ($uname,$udom,$query,%filters)=@_;
                   9213:     my $uhome=&homeserver($uname,$udom);
                   9214:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 9215:     my $uhost=&hostname($uhome);
1.800     albertel 9216:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      9217:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   9218:                        $uhome);
1.479     albertel 9219:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      9220:     return get_query_reply($queryid);
                   9221: }
                   9222: 
1.818     raeburn  9223: # -------------------------- Update MySQL table for portfolio file
                   9224: 
                   9225: sub update_portfolio_table {
1.821     raeburn  9226:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  9227:     if ($group ne '') {
                   9228:         $file_name =~s /^\Q$group\E//;
                   9229:     }
1.818     raeburn  9230:     my $homeserver = &homeserver($uname,$udom);
                   9231:     my $queryid=
1.821     raeburn  9232:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   9233:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  9234:     my $reply = &get_query_reply($queryid);
                   9235:     return $reply;
                   9236: }
                   9237: 
1.899     raeburn  9238: # -------------------------- Update MySQL allusers table
                   9239: 
                   9240: sub update_allusers_table {
                   9241:     my ($uname,$udom,$names) = @_;
                   9242:     my $homeserver = &homeserver($uname,$udom);
                   9243:     my $queryid=
                   9244:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   9245:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   9246:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   9247:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   9248:                'generation='.&escape($names->{'generation'}).'%%'.
                   9249:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   9250:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  9251:     return;
1.899     raeburn  9252: }
                   9253: 
1.508     raeburn  9254: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  9255: 
                   9256: sub fetch_enrollment_query {
1.511     raeburn  9257:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  9258:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  9259:     my $maxtries = 1;
1.508     raeburn  9260:     if ($context eq 'automated') {
                   9261:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  9262:         $sleep = 2;
                   9263:         $loopmax = 100;
1.547     raeburn  9264:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  9265:     } else {
                   9266:         $homeserver = &homeserver($cnum,$dom);
                   9267:     }
1.838     albertel 9268:     my $host=&hostname($homeserver);
1.506     raeburn  9269:     my $cmd = '';
1.1000    raeburn  9270:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 9271:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  9272:     }
                   9273:     $cmd =~ s/%%$//;
                   9274:     $cmd = &escape($cmd);
                   9275:     my $query = 'fetchenrollment';
1.620     albertel 9276:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  9277:     unless ($queryid=~/^\Q$host\E\_/) { 
                   9278:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   9279:         return 'error: '.$queryid;
                   9280:     }
1.1172.2.93  raeburn  9281:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9282:     my $tries = 1;
                   9283:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  9284:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9285:         $tries ++;
                   9286:     }
1.526     raeburn  9287:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 9288:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  9289:     } else {
1.901     albertel 9290:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  9291:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 9292:             foreach my $line (@responses) {
                   9293:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  9294:                 $$replyref{$key} = $value;
                   9295:             }
                   9296:         } else {
1.1117    foxr     9297:             my $pathname = LONCAPA::tempdir();
1.800     albertel 9298:             foreach my $line (@responses) {
                   9299:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  9300:                 $$replyref{$key} = $value;
                   9301:                 if ($value > 0) {
1.800     albertel 9302:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   9303:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  9304:                         my $destname = $pathname.'/'.$filename;
                   9305:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  9306:                         if ($xml_classlist =~ /^error/) {
                   9307:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   9308:                         } else {
1.1172.2.96  raeburn  9309:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  9310:                                 print FILE &unescape($xml_classlist);
                   9311:                                 close(FILE);
1.526     raeburn  9312:                             } else {
                   9313:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  9314:                             }
                   9315:                         }
                   9316:                     }
                   9317:                 }
                   9318:             }
                   9319:         }
                   9320:         return 'ok';
                   9321:     }
                   9322:     return 'error';
                   9323: }
                   9324: 
1.242     www      9325: sub get_query_reply {
1.1172.2.79  raeburn  9326:     my ($queryid,$sleep,$loopmax) = @_;
                   9327:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9328:         $sleep = 0.2;
                   9329:     }
                   9330:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9331:         $loopmax = 100;
                   9332:     }
1.1117    foxr     9333:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9334:     my $reply='';
1.1172.2.79  raeburn  9335:     for (1..$loopmax) {
                   9336: 	sleep($sleep);
1.240     www      9337:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  9338: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9339: 		$reply = join('',<$fh>);
                   9340: 		close($fh);
1.240     www      9341: 	   } else { return 'error: reply_file_error'; }
1.242     www      9342:            return &unescape($reply);
                   9343: 	}
1.240     www      9344:     }
1.242     www      9345:     return 'timeout:'.$queryid;
1.240     www      9346: }
                   9347: 
                   9348: sub courselog_query {
1.241     www      9349: #
                   9350: # possible filters:
                   9351: # url: url or symb
                   9352: # username
                   9353: # domain
                   9354: # action: view, submit, grade
                   9355: # start: timestamp
                   9356: # end: timestamp
                   9357: #
1.240     www      9358:     my (%filters)=@_;
1.620     albertel 9359:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9360:     if ($filters{'url'}) {
                   9361: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9362:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9363:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9364:     }
1.620     albertel 9365:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9366:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9367:     return &log_query($cname,$cdom,'courselog',%filters);
                   9368: }
                   9369: 
                   9370: sub userlog_query {
1.858     raeburn  9371: #
                   9372: # possible filters:
                   9373: # action: log check role
                   9374: # start: timestamp
                   9375: # end: timestamp
                   9376: #
1.240     www      9377:     my ($uname,$udom,%filters)=@_;
                   9378:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9379: }
                   9380: 
1.506     raeburn  9381: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9382: 
                   9383: sub auto_run {
1.508     raeburn  9384:     my ($cnum,$cdom) = @_;
1.876     raeburn  9385:     my $response = 0;
                   9386:     my $settings;
                   9387:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9388:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9389:         $settings = $domconfig{'autoenroll'};
                   9390:         if ($settings->{'run'} eq '1') {
                   9391:             $response = 1;
                   9392:         }
                   9393:     } else {
1.934     raeburn  9394:         my $homeserver;
                   9395:         if (&is_course($cdom,$cnum)) {
                   9396:             $homeserver = &homeserver($cnum,$cdom);
                   9397:         } else {
                   9398:             $homeserver = &domain($cdom,'primary');
                   9399:         }
                   9400:         if ($homeserver ne 'no_host') {
                   9401:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9402:         }
1.876     raeburn  9403:     }
1.506     raeburn  9404:     return $response;
                   9405: }
1.776     albertel 9406: 
1.506     raeburn  9407: sub auto_get_sections {
1.508     raeburn  9408:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9409:     my $homeserver;
                   9410:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9411:         $homeserver = &homeserver($cnum,$cdom);
                   9412:     }
                   9413:     if (!defined($homeserver)) { 
                   9414:         if ($cdom =~ /^$match_domain$/) {
                   9415:             $homeserver = &domain($cdom,'primary');
                   9416:         }
                   9417:     }
                   9418:     my @secs;
                   9419:     if (defined($homeserver)) {
                   9420:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9421:         unless ($response eq 'refused') {
                   9422:             @secs = split(/:/,$response);
                   9423:         }
1.506     raeburn  9424:     }
                   9425:     return @secs;
                   9426: }
1.776     albertel 9427: 
1.506     raeburn  9428: sub auto_new_course {
1.1099    raeburn  9429:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9430:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9431:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9432:     return $response;
                   9433: }
1.776     albertel 9434: 
1.506     raeburn  9435: sub auto_validate_courseID {
1.508     raeburn  9436:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9437:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9438:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9439:     return $response;
                   9440: }
1.776     albertel 9441: 
1.1007    raeburn  9442: sub auto_validate_instcode {
1.1020    raeburn  9443:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9444:     my ($homeserver,$response);
                   9445:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9446:         $homeserver = &homeserver($cnum,$cdom);
                   9447:     }
                   9448:     if (!defined($homeserver)) {
                   9449:         if ($cdom =~ /^$match_domain$/) {
                   9450:             $homeserver = &domain($cdom,'primary');
                   9451:         }
                   9452:     }
1.1065    raeburn  9453:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9454:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  9455:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9456:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9457: }
                   9458: 
1.1172.2.141  raeburn  9459: sub auto_validate_inst_crosslist {
                   9460:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
                   9461:     my ($homeserver,$response);
                   9462:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9463:         $homeserver = &homeserver($cnum,$cdom);
                   9464:     }
                   9465:     if (!defined($homeserver)) {
                   9466:         if ($cdom =~ /^$match_domain$/) {
                   9467:             $homeserver = &domain($cdom,'primary');
                   9468:         }
                   9469:     }
                   9470:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
                   9471:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
                   9472:                          &escape($instcode).':'.&escape($inst_xlist).':'.
                   9473:                          &escape($coowner),$homeserver);
                   9474:     }
                   9475:     return $response;
                   9476: }
                   9477: 
1.506     raeburn  9478: sub auto_create_password {
1.873     raeburn  9479:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9480:     my ($homeserver,$response);
1.506     raeburn  9481:     my $create_passwd = 0;
                   9482:     my $authchk = '';
1.873     raeburn  9483:     if ($udom =~ /^$match_domain$/) {
                   9484:         $homeserver = &domain($udom,'primary');
                   9485:     }
                   9486:     if ($homeserver eq '') {
                   9487:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9488:             $homeserver = &homeserver($cnum,$cdom);
                   9489:         }
                   9490:     }
                   9491:     if ($homeserver eq '') {
                   9492:         $authchk = 'nodomain';
1.506     raeburn  9493:     } else {
1.873     raeburn  9494:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9495:         if ($response eq 'refused') {
                   9496:             $authchk = 'refused';
                   9497:         } else {
1.901     albertel 9498:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9499:         }
1.506     raeburn  9500:     }
                   9501:     return ($authparam,$create_passwd,$authchk);
                   9502: }
                   9503: 
1.706     raeburn  9504: sub auto_photo_permission {
                   9505:     my ($cnum,$cdom,$students) = @_;
                   9506:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9507:     my ($outcome,$perm_reqd,$conditions) = 
                   9508: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9509:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9510: 	return (undef,undef);
                   9511:     }
1.706     raeburn  9512:     return ($outcome,$perm_reqd,$conditions);
                   9513: }
                   9514: 
                   9515: sub auto_checkphotos {
                   9516:     my ($uname,$udom,$pid) = @_;
                   9517:     my $homeserver = &homeserver($uname,$udom);
                   9518:     my ($result,$resulttype);
                   9519:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9520: 				   &escape($uname).':'.&escape($pid),
                   9521: 				   $homeserver));
1.709     albertel 9522:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9523: 	return (undef,undef);
                   9524:     }
1.706     raeburn  9525:     if ($outcome) {
                   9526:         ($result,$resulttype) = split(/:/,$outcome);
                   9527:     } 
                   9528:     return ($result,$resulttype);
                   9529: }
                   9530: 
                   9531: sub auto_photochoice {
                   9532:     my ($cnum,$cdom) = @_;
                   9533:     my $homeserver = &homeserver($cnum,$cdom);
                   9534:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9535: 						       &escape($cdom),
                   9536: 						       $homeserver)));
1.709     albertel 9537:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9538: 	return (undef,undef);
                   9539:     }
1.706     raeburn  9540:     return ($update,$comment);
                   9541: }
                   9542: 
                   9543: sub auto_photoupdate {
                   9544:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9545:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9546:     my $host=&hostname($homeserver);
1.706     raeburn  9547:     my $cmd = '';
                   9548:     my $maxtries = 1;
1.800     albertel 9549:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9550:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9551:     }
                   9552:     $cmd =~ s/%%$//;
                   9553:     $cmd = &escape($cmd);
                   9554:     my $query = 'institutionalphotos';
                   9555:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9556:     unless ($queryid=~/^\Q$host\E\_/) {
                   9557:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9558:         return 'error: '.$queryid;
                   9559:     }
                   9560:     my $reply = &get_query_reply($queryid);
                   9561:     my $tries = 1;
                   9562:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9563:         $reply = &get_query_reply($queryid);
                   9564:         $tries ++;
                   9565:     }
                   9566:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9567:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9568:     } else {
                   9569:         my @responses = split(/:/,$reply);
                   9570:         my $outcome = shift(@responses); 
                   9571:         foreach my $item (@responses) {
                   9572:             my ($key,$value) = split(/=/,$item);
                   9573:             $$photo{$key} = $value;
                   9574:         }
                   9575:         return $outcome;
                   9576:     }
                   9577:     return 'error';
                   9578: }
                   9579: 
1.521     raeburn  9580: sub auto_instcode_format {
1.793     albertel 9581:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9582: 	$cat_order) = @_;
1.521     raeburn  9583:     my $courses = '';
1.772     raeburn  9584:     my @homeservers;
1.521     raeburn  9585:     if ($caller eq 'global') {
1.841     albertel 9586: 	my %servers = &get_servers($codedom,'library');
                   9587: 	foreach my $tryserver (keys(%servers)) {
                   9588: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9589: 		push(@homeservers,$tryserver);
                   9590: 	    }
1.584     raeburn  9591:         }
1.1022    raeburn  9592:     } elsif ($caller eq 'requests') {
                   9593:         if ($codedom =~ /^$match_domain$/) {
                   9594:             my $chome = &domain($codedom,'primary');
                   9595:             unless ($chome eq 'no_host') {
                   9596:                 push(@homeservers,$chome);
                   9597:             }
                   9598:         }
1.521     raeburn  9599:     } else {
1.772     raeburn  9600:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9601:     }
1.793     albertel 9602:     foreach my $code (keys(%{$instcodes})) {
                   9603:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9604:     }
                   9605:     chop($courses);
1.772     raeburn  9606:     my $ok_response = 0;
                   9607:     my $response;
                   9608:     while (@homeservers > 0 && $ok_response == 0) {
                   9609:         my $server = shift(@homeservers); 
                   9610:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9611:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9612:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9613: 		split(/:/,$response);
1.772     raeburn  9614:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9615:             push(@{$codetitles},&str2array($codetitles_str));
                   9616:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9617:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9618:             $ok_response = 1;
                   9619:         }
                   9620:     }
                   9621:     if ($ok_response) {
1.521     raeburn  9622:         return 'ok';
1.772     raeburn  9623:     } else {
                   9624:         return $response;
1.521     raeburn  9625:     }
                   9626: }
                   9627: 
1.792     raeburn  9628: sub auto_instcode_defaults {
                   9629:     my ($domain,$returnhash,$code_order) = @_;
                   9630:     my @homeservers;
1.841     albertel 9631: 
                   9632:     my %servers = &get_servers($domain,'library');
                   9633:     foreach my $tryserver (keys(%servers)) {
                   9634: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9635: 	    push(@homeservers,$tryserver);
                   9636: 	}
1.792     raeburn  9637:     }
1.841     albertel 9638: 
1.792     raeburn  9639:     my $response;
1.841     albertel 9640:     foreach my $server (@homeservers) {
1.792     raeburn  9641:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9642:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9643: 	
                   9644: 	foreach my $pair (split(/\&/,$response)) {
                   9645: 	    my ($name,$value)=split(/\=/,$pair);
                   9646: 	    if ($name eq 'code_order') {
                   9647: 		@{$code_order} = split(/\&/,&unescape($value));
                   9648: 	    } else {
                   9649: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9650: 	    }
                   9651: 	}
                   9652: 	return 'ok';
1.792     raeburn  9653:     }
1.841     albertel 9654: 
                   9655:     return $response;
1.1003    raeburn  9656: }
                   9657: 
                   9658: sub auto_possible_instcodes {
1.1007    raeburn  9659:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9660:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9661:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9662:         return;
                   9663:     }
1.1003    raeburn  9664:     my (@homeservers,$uhome);
                   9665:     if (defined(&domain($domain,'primary'))) {
                   9666:         $uhome=&domain($domain,'primary');
                   9667:         push(@homeservers,&domain($domain,'primary'));
                   9668:     } else {
                   9669:         my %servers = &get_servers($domain,'library');
                   9670:         foreach my $tryserver (keys(%servers)) {
                   9671:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9672:                 push(@homeservers,$tryserver);
                   9673:             }
                   9674:         }
                   9675:     }
                   9676:     my $response;
                   9677:     foreach my $server (@homeservers) {
                   9678:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9679:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9680:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9681:             split(':',$response);
                   9682:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9683:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9684:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9685:             my ($name,$value)=split('=',$item);
                   9686:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9687:         }
                   9688:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9689:             my ($name,$value)=split('=',$item);
                   9690:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9691:         }
                   9692:         return 'ok';
                   9693:     }
                   9694:     return $response;
                   9695: }
1.792     raeburn  9696: 
1.1010    raeburn  9697: sub auto_courserequest_checks {
                   9698:     my ($dom) = @_;
1.1020    raeburn  9699:     my ($homeserver,%validations);
                   9700:     if ($dom =~ /^$match_domain$/) {
                   9701:         $homeserver = &domain($dom,'primary');
                   9702:     }
                   9703:     unless ($homeserver eq 'no_host') {
                   9704:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9705:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9706:             my @items = split(/&/,$response);
                   9707:             foreach my $item (@items) {
                   9708:                 my ($key,$value) = split('=',$item);
                   9709:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9710:             }
                   9711:         }
                   9712:     }
1.1010    raeburn  9713:     return %validations; 
                   9714: }
                   9715: 
1.1020    raeburn  9716: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9717:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9718:     my ($homeserver,$response);
                   9719:     if ($dom =~ /^$match_domain$/) {
                   9720:         $homeserver = &domain($dom,'primary');
                   9721:     }
1.1172.2.43  raeburn  9722:     unless ($homeserver eq 'no_host') {
                   9723:         my $customdata;
                   9724:         if (ref($custominfo) eq 'HASH') {
                   9725:             $customdata = &freeze_escape($custominfo);
                   9726:         }
1.1020    raeburn  9727:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9728:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9729:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9730:                                     $customdata,$homeserver));
1.1020    raeburn  9731:     }
                   9732:     return $response;
                   9733: }
                   9734: 
1.777     albertel 9735: sub auto_validate_class_sec {
1.918     raeburn  9736:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9737:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9738:     my $ownerlist;
                   9739:     if (ref($owners) eq 'ARRAY') {
                   9740:         $ownerlist = join(',',@{$owners});
                   9741:     } else {
                   9742:         $ownerlist = $owners;
                   9743:     }
1.773     raeburn  9744:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9745:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9746:     return $response;
                   9747: }
                   9748: 
1.1172.2.141  raeburn  9749: sub auto_instsec_reformat {
                   9750:     my ($cdom,$action,$instsecref) = @_;
                   9751:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
                   9752:     my @homeservers;
                   9753:     if (defined(&domain($cdom,'primary'))) {
                   9754:         push(@homeservers,&domain($cdom,'primary'));
                   9755:     } else {
                   9756:         my %servers = &get_servers($cdom,'library');
                   9757:         foreach my $tryserver (keys(%servers)) {
                   9758:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9759:                 push(@homeservers,$tryserver);
                   9760:             }
                   9761:         }
                   9762:     }
                   9763:     my $response;
                   9764:     my %reformatted = %{$instsecref};
                   9765:     foreach my $server (@homeservers) {
                   9766:         if (ref($instsecref) eq 'HASH') {
                   9767:             my $info = &freeze_escape($instsecref);
                   9768:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
                   9769:                                 $action.':'.$info,$server);
                   9770:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
                   9771:             my @items = split(/&/,$response);
                   9772:             foreach my $item (@items) {
                   9773:                 my ($key,$value) = split(/=/,$item);
                   9774:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
                   9775:             }
                   9776:         }
                   9777:     }
                   9778:     return %reformatted;
                   9779: }
                   9780: 
1.1172.2.94  raeburn  9781: sub auto_validate_instclasses {
                   9782:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9783:     my ($homeserver,%validations);
                   9784:     $homeserver = &homeserver($cnum,$cdom);
                   9785:     unless ($homeserver eq 'no_host') {
                   9786:         my $ownerlist;
                   9787:         if (ref($owners) eq 'ARRAY') {
                   9788:             $ownerlist = join(',',@{$owners});
                   9789:         } else {
                   9790:             $ownerlist = $owners;
                   9791:         }
                   9792:         if (ref($classesref) eq 'HASH') {
                   9793:             my $classes = &freeze_escape($classesref);
                   9794:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9795:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9796:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9797:                 my @items = split(/&/,$response);
                   9798:                 foreach my $item (@items) {
                   9799:                     my ($key,$value) = split('=',$item);
                   9800:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9801:                 }
                   9802:             }
                   9803:         }
                   9804:     }
                   9805:     return %validations;
                   9806: }
                   9807: 
1.1172.2.38  raeburn  9808: sub auto_crsreq_update {
                   9809:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9810:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9811:     my ($homeserver,%crsreqresponse);
                   9812:     if ($cdom =~ /^$match_domain$/) {
                   9813:         $homeserver = &domain($cdom,'primary');
                   9814:     }
                   9815:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9816:         my $info;
                   9817:         if (ref($inbound) eq 'HASH') {
                   9818:             $info = &freeze_escape($inbound);
                   9819:         }
                   9820:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9821:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9822:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9823:                             &escape($title).':'.&escape($code).':'.
                   9824:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9825:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9826:             my @items = split(/&/,$response);
                   9827:             foreach my $item (@items) {
                   9828:                 my ($key,$value) = split('=',$item);
                   9829:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9830:             }
                   9831:         }
                   9832:     }
                   9833:     return \%crsreqresponse;
                   9834: }
                   9835: 
1.1172.2.78  raeburn  9836: sub auto_export_grades {
                   9837:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9838:     my ($homeserver,%exportresponse);
                   9839:     if ($cdom =~ /^$match_domain$/) {
                   9840:         $homeserver = &domain($cdom,'primary');
                   9841:     }
                   9842:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9843:         my $info;
                   9844:         if (ref($inforef) eq 'HASH') {
                   9845:             $info = &freeze_escape($inforef);
                   9846:         }
                   9847:         if (ref($gradesref) eq 'HASH') {
                   9848:             my $grades = &freeze_escape($gradesref);
                   9849:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   9850:                                 $info.':'.$grades,$homeserver);
                   9851:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   9852:                 my @items = split(/&/,$response);
                   9853:                 foreach my $item (@items) {
                   9854:                     my ($key,$value) = split('=',$item);
                   9855:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   9856:                 }
                   9857:             }
                   9858:         }
                   9859:     }
                   9860:     return \%exportresponse;
                   9861: }
                   9862: 
1.1172.2.68  raeburn  9863: sub check_instcode_cloning {
                   9864:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   9865:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9866:         return;
                   9867:     }
                   9868:     my $canclone;
                   9869:     if (@{$code_order} > 0) {
                   9870:         my $instcoderegexp ='^';
                   9871:         my @clonecodes = split(/\&/,$cloner);
                   9872:         foreach my $item (@{$code_order}) {
                   9873:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9874:                 foreach my $pair (@clonecodes) {
                   9875:                     my ($key,$val) = split(/\=/,$pair,2);
                   9876:                     $val = &unescape($val);
                   9877:                     if ($key eq $item) {
                   9878:                         $instcoderegexp .= '('.$val.')';
                   9879:                         last;
                   9880:                     }
                   9881:                 }
                   9882:             } else {
                   9883:                 $instcoderegexp .= $codedefaults->{$item};
                   9884:             }
                   9885:         }
                   9886:         $instcoderegexp .= '$';
                   9887:         my (@from,@to);
                   9888:         eval {
                   9889:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9890:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9891:         };
                   9892:         if ((@from > 0) && (@to > 0)) {
                   9893:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9894:             if (!@diffs) {
                   9895:                 $canclone = 1;
                   9896:             }
                   9897:         }
                   9898:     }
                   9899:     return $canclone;
                   9900: }
                   9901: 
                   9902: sub default_instcode_cloning {
                   9903:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9904:     my (%codedefaults,@code_order,$canclone);
                   9905:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9906:         %codedefaults = %{$codedefaultsref};
                   9907:         @code_order = @{$codeorderref};
                   9908:     } elsif ($clonedom) {
                   9909:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9910:     }
                   9911:     if (($domdefclone) && (@code_order)) {
                   9912:         my @clonecodes = split(/\+/,$domdefclone);
                   9913:         my $instcoderegexp ='^';
                   9914:         foreach my $item (@code_order) {
                   9915:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9916:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9917:             } else {
                   9918:                 $instcoderegexp .= $codedefaults{$item};
                   9919:             }
                   9920:         }
                   9921:         $instcoderegexp .= '$';
                   9922:         my (@from,@to);
                   9923:         eval {
                   9924:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9925:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9926:         };
                   9927:         if ((@from > 0) && (@to > 0)) {
                   9928:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9929:             if (!@diffs) {
                   9930:                 $canclone = 1;
                   9931:             }
                   9932:         }
                   9933:     }
                   9934:     return $canclone;
                   9935: }
                   9936: 
1.679     raeburn  9937: # ------------------------------------------------------- Course Group routines
                   9938: 
                   9939: sub get_coursegroups {
1.809     raeburn  9940:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9941:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9942: }
                   9943: 
1.679     raeburn  9944: sub modify_coursegroup {
                   9945:     my ($cdom,$cnum,$groupsettings) = @_;
                   9946:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9947: }
                   9948: 
1.809     raeburn  9949: sub toggle_coursegroup_status {
                   9950:     my ($cdom,$cnum,$group,$action) = @_;
                   9951:     my ($from_namespace,$to_namespace);
                   9952:     if ($action eq 'delete') {
                   9953:         $from_namespace = 'coursegroups';
                   9954:         $to_namespace = 'deleted_groups';
                   9955:     } else {
                   9956:         $from_namespace = 'deleted_groups';
                   9957:         $to_namespace = 'coursegroups';
                   9958:     }
                   9959:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9960:     if (my $tmp = &error(%curr_group)) {
                   9961:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9962:         return ('read error',$tmp);
                   9963:     } else {
                   9964:         my %savedsettings = %curr_group; 
1.809     raeburn  9965:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9966:         my $deloutcome;
                   9967:         if ($result eq 'ok') {
1.809     raeburn  9968:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9969:         } else {
                   9970:             return ('write error',$result);
                   9971:         }
                   9972:         if ($deloutcome eq 'ok') {
                   9973:             return 'ok';
                   9974:         } else {
                   9975:             return ('delete error',$deloutcome);
                   9976:         }
                   9977:     }
                   9978: }
                   9979: 
1.679     raeburn  9980: sub modify_group_roles {
1.957     raeburn  9981:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9982:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9983:     my $role = 'gr/'.&escape($userprivs);
                   9984:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9985:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9986:     if ($result eq 'ok') {
                   9987:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9988:     }
1.679     raeburn  9989:     return $result;
                   9990: }
                   9991: 
                   9992: sub modify_coursegroup_membership {
                   9993:     my ($cdom,$cnum,$membership) = @_;
                   9994:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9995:     return $result;
                   9996: }
                   9997: 
1.682     raeburn  9998: sub get_active_groups {
                   9999:     my ($udom,$uname,$cdom,$cnum) = @_;
                   10000:     my $now = time;
                   10001:     my %groups = ();
                   10002:     foreach my $key (keys(%env)) {
1.811     albertel 10003:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  10004:             my ($start,$end) = split(/\./,$env{$key});
                   10005:             if (($end!=0) && ($end<$now)) { next; }
                   10006:             if (($start!=0) && ($start>$now)) { next; }
                   10007:             if ($1 eq $cdom && $2 eq $cnum) {
                   10008:                 $groups{$3} = $env{$key} ;
                   10009:             }
                   10010:         }
                   10011:     }
                   10012:     return %groups;
                   10013: }
                   10014: 
1.683     raeburn  10015: sub get_group_membership {
                   10016:     my ($cdom,$cnum,$group) = @_;
                   10017:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   10018: }
                   10019: 
                   10020: sub get_users_groups {
                   10021:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  10022:     my @usersgroups;
1.683     raeburn  10023:     my $cachetime=1800;
                   10024: 
                   10025:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  10026:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   10027:     if (defined($cached)) {
1.734     albertel 10028:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  10029:     } else {  
                   10030:         $grouplist = '';
1.816     raeburn  10031:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  10032:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  10033:         my $access_end = $env{'course.'.$courseid.
                   10034:                               '.default_enrollment_end_date'};
                   10035:         my $now = time;
                   10036:         foreach my $key (keys(%roleshash)) {
                   10037:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   10038:                 my $group = $1;
                   10039:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   10040:                     my $start = $2;
                   10041:                     my $end = $1;
                   10042:                     if ($start == -1) { next; } # deleted from group
                   10043:                     if (($start!=0) && ($start>$now)) { next; }
                   10044:                     if (($end!=0) && ($end<$now)) {
                   10045:                         if ($access_end && $access_end < $now) {
                   10046:                             if ($access_end - $end < 86400) {
                   10047:                                 push(@usersgroups,$group);
1.733     raeburn  10048:                             }
                   10049:                         }
1.817     raeburn  10050:                         next;
1.733     raeburn  10051:                     }
1.817     raeburn  10052:                     push(@usersgroups,$group);
1.683     raeburn  10053:                 }
                   10054:             }
                   10055:         }
1.817     raeburn  10056:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   10057:         $grouplist = join(':',@usersgroups);
                   10058:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  10059:     }
1.733     raeburn  10060:     return @usersgroups;
1.683     raeburn  10061: }
                   10062: 
                   10063: sub devalidate_getgroups_cache {
                   10064:     my ($udom,$uname,$cdom,$cnum)=@_;
                   10065:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 10066: 
1.683     raeburn  10067:     my $hashid="$udom:$uname:$courseid";
                   10068:     &devalidate_cache_new('getgroups',$hashid);
                   10069: }
                   10070: 
1.12      www      10071: # ------------------------------------------------------------------ Plain Text
                   10072: 
                   10073: sub plaintext {
1.988     raeburn  10074:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  10075:     if ($short =~ m{^cr/}) {
1.758     albertel 10076: 	return (split('/',$short))[-1];
                   10077:     }
1.742     raeburn  10078:     if (!defined($cid)) {
                   10079:         $cid = $env{'request.course.id'};
                   10080:     }
                   10081:     my %rolenames = (
1.1008    raeburn  10082:                       Course    => 'std',
                   10083:                       Community => 'alt1',
1.742     raeburn  10084:                     );
1.1037    raeburn  10085:     if ($cid ne '') {
                   10086:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   10087:             unless ($forcedefault) {
                   10088:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   10089:                 &Apache::lonlocal::mt_escape(\$roletext);
                   10090:                 return &Apache::lonlocal::mt($roletext);
                   10091:             }
                   10092:         }
                   10093:     }
                   10094:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   10095:         (defined($rolenames{$type})) && 
                   10096:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  10097:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  10098:     } elsif ($cid ne '') {
                   10099:         my $crstype = $env{'course.'.$cid.'.type'};
                   10100:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   10101:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   10102:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   10103:         }
1.742     raeburn  10104:     }
1.1037    raeburn  10105:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      10106: }
                   10107: 
                   10108: # ----------------------------------------------------------------- Assign Role
                   10109: 
                   10110: sub assignrole {
1.957     raeburn  10111:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   10112:         $context)=@_;
1.21      www      10113:     my $mrole;
                   10114:     if ($role =~ /^cr\//) {
1.393     www      10115:         my $cwosec=$url;
1.811     albertel 10116:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      10117: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  10118:            my $refused = 1;
                   10119:            if ($context eq 'requestcourses') {
                   10120:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   10121:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   10122:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   10123:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10124:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10125:                            if ($crsenv{'internal.courseowner'} eq
                   10126:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   10127:                                $refused = '';
                   10128:                            }
                   10129:                        }
                   10130:                    }
                   10131:                }
                   10132:            }
                   10133:            if ($refused) {
                   10134:                &logthis('Refused custom assignrole: '.
                   10135:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   10136:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   10137:                return 'refused';
                   10138:            }
1.104     www      10139:         }
1.21      www      10140:         $mrole='cr';
1.678     raeburn  10141:     } elsif ($role =~ /^gr\//) {
                   10142:         my $cwogrp=$url;
1.811     albertel 10143:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  10144:         unless (&allowed('mdg',$cwogrp)) {
                   10145:             &logthis('Refused group assignrole: '.
                   10146:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   10147:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   10148:             return 'refused';
                   10149:         }
                   10150:         $mrole='gr';
1.21      www      10151:     } else {
1.82      www      10152:         my $cwosec=$url;
1.811     albertel 10153:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  10154:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   10155:             my $refused;
                   10156:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   10157:                 if (!(&allowed('c'.$role,$url))) {
                   10158:                     $refused = 1;
                   10159:                 }
                   10160:             } else {
                   10161:                 $refused = 1;
                   10162:             }
1.947     raeburn  10163:             if ($refused) {
1.1045    raeburn  10164:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10165:                 if (!$selfenroll && $context eq 'course') {
                   10166:                     my %crsenv;
                   10167:                     if ($role eq 'cc' || $role eq 'co') {
                   10168:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10169:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   10170:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   10171:                                 if ($crsenv{'internal.courseowner'} eq 
                   10172:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10173:                                     $refused = '';
                   10174:                                 }
                   10175:                             }
                   10176:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   10177:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   10178:                                 if ($crsenv{'internal.courseowner'} eq 
                   10179:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10180:                                     $refused = '';
                   10181:                                 }
                   10182:                             }
                   10183:                         }
                   10184:                     }
                   10185:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  10186:                     $refused = '';
1.1017    raeburn  10187:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  10188:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  10189:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  10190:                         my $wrongcc;
                   10191:                         if ($cnum =~ /^$match_community$/) {
                   10192:                             $wrongcc = 1 if ($role eq 'cc');
                   10193:                         } else {
                   10194:                             $wrongcc = 1 if ($role eq 'co');
                   10195:                         }
                   10196:                         unless ($wrongcc) {
                   10197:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10198:                             if ($crsenv{'internal.courseowner'} eq 
                   10199:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   10200:                                 $refused = '';
                   10201:                             }
1.1017    raeburn  10202:                         }
                   10203:                     }
1.1172.2.9  raeburn  10204:                 } elsif ($context eq 'requestauthor') {
                   10205:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   10206:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   10207:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   10208:                             $refused = '';
                   10209:                         } else {
                   10210:                             my %domdefaults = &get_domain_defaults($udom);
                   10211:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   10212:                                 my $checkbystatus;
                   10213:                                 if ($env{'user.adv'}) {
                   10214:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   10215:                                     if ($disposition eq 'automatic') {
                   10216:                                         $refused = '';
                   10217:                                     } elsif ($disposition eq '') {
                   10218:                                         $checkbystatus = 1;
                   10219:                                     }
                   10220:                                 } else {
                   10221:                                     $checkbystatus = 1;
                   10222:                                 }
                   10223:                                 if ($checkbystatus) {
                   10224:                                     if ($env{'environment.inststatus'}) {
                   10225:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   10226:                                         foreach my $type (@inststatuses) {
                   10227:                                             if (($type ne '') &&
                   10228:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   10229:                                                 $refused = '';
                   10230:                                             }
                   10231:                                         }
                   10232:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   10233:                                         $refused = '';
                   10234:                                     }
                   10235:                                 }
                   10236:                             }
                   10237:                         }
                   10238:                     }
1.1017    raeburn  10239:                 }
                   10240:                 if ($refused) {
1.947     raeburn  10241:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   10242:                              ' '.$role.' '.$end.' '.$start.' by '.
                   10243: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   10244:                     return 'refused';
                   10245:                 }
1.932     raeburn  10246:             }
1.1131    raeburn  10247:         } elsif ($role eq 'au') {
                   10248:             if ($url ne '/'.$udom.'/') {
                   10249:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   10250:                          ' to assign author role for '.$uname.':'.$udom.
                   10251:                          ' in domain: '.$url.' refused (wrong domain).');
                   10252:                 return 'refused';
                   10253:             }
1.104     www      10254:         }
1.21      www      10255:         $mrole=$role;
                   10256:     }
1.620     albertel 10257:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      10258:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      10259:     if ($end) { $command.='_'.$end; }
1.21      www      10260:     if ($start) {
                   10261: 	if ($end) { 
1.81      www      10262:            $command.='_'.$start; 
1.21      www      10263:         } else {
1.81      www      10264:            $command.='_0_'.$start;
1.21      www      10265:         }
                   10266:     }
1.739     raeburn  10267:     my $origstart = $start;
                   10268:     my $origend = $end;
1.957     raeburn  10269:     my $delflag;
1.357     www      10270: # actually delete
                   10271:     if ($deleteflag) {
1.373     www      10272: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      10273: # modify command to delete the role
1.620     albertel 10274:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      10275:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 10276: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      10277: # set start and finish to negative values for userrolelog
                   10278:            $start=-1;
                   10279:            $end=-1;
1.957     raeburn  10280:            $delflag = 1;
1.357     www      10281:         }
                   10282:     }
                   10283: # send command
1.349     www      10284:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      10285: # log new user role if status is ok
1.349     www      10286:     if ($answer eq 'ok') {
1.663     raeburn  10287: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  10288:         if (($role eq 'cc') || ($role eq 'in') ||
                   10289:             ($role eq 'ep') || ($role eq 'ad') ||
                   10290:             ($role eq 'ta') || ($role eq 'st') ||
                   10291:             ($role=~/^cr/) || ($role eq 'gr') ||
                   10292:             ($role eq 'co')) {
1.1172.2.13  raeburn  10293: # for course roles, perform group memberships changes triggered by role change.
                   10294:             unless ($role =~ /^gr/) {
                   10295:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   10296:                                                  $origstart,$selfenroll,$context);
                   10297:             }
1.1172.2.9  raeburn  10298:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10299:                            $selfenroll,$context);
                   10300:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  10301:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   10302:                  ($role eq 'da')) {
1.1172.2.9  raeburn  10303:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10304:                            $context);
                   10305:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   10306:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10307:                              $context);
                   10308:         }
1.1053    raeburn  10309:         if ($role eq 'cc') {
                   10310:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   10311:         }
1.349     www      10312:     }
                   10313:     return $answer;
1.169     harris41 10314: }
                   10315: 
1.1053    raeburn  10316: sub autoupdate_coowners {
                   10317:     my ($url,$end,$start,$uname,$udom) = @_;
                   10318:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   10319:     if (($cdom ne '') && ($cnum ne '')) {
                   10320:         my $now = time;
                   10321:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   10322:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   10323:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   10324:             my $instcode = $coursehash{'internal.coursecode'};
1.1172.2.141  raeburn  10325:             my $xlists = $coursehash{'internal.crosslistings'};
1.1053    raeburn  10326:             if ($instcode ne '') {
1.1056    raeburn  10327:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   10328:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  10329:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  10330:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1172.2.141  raeburn  10331:                         unless ($result eq 'valid') {
                   10332:                             if ($xlists ne '') {
                   10333:                                 foreach my $xlist (split(',',$xlists)) {
                   10334:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
                   10335:                                     $result =
                   10336:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
                   10337:                                                                       $inst_crosslist,$uname.':'.$udom);
                   10338:                                     last if ($result eq 'valid');
                   10339:                                 }
                   10340:                             }
                   10341:                         }
1.1056    raeburn  10342:                         if ($result eq 'valid') {
                   10343:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  10344:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10345:                                     push(@newcoowners,$coowner);
                   10346:                                 }
                   10347:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   10348:                                     push(@newcoowners,$uname.':'.$udom);
                   10349:                                 }
                   10350:                                 @newcoowners = sort(@newcoowners);
                   10351:                             } else {
                   10352:                                 push(@newcoowners,$uname.':'.$udom);
                   10353:                             }
1.1172.2.141  raeburn  10354:                         } elsif ($coursehash{'internal.co-owners'}) {
                   10355:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10356:                                 unless ($coowner eq $uname.':'.$udom) {
                   10357:                                     push(@newcoowners,$coowner);
1.1053    raeburn  10358:                                 }
                   10359:                             }
1.1172.2.141  raeburn  10360:                             unless (@newcoowners > 0) {
                   10361:                                 $delcoowners = 1;
                   10362:                                 $coowners = '';
                   10363:                             }
1.1053    raeburn  10364:                         }
                   10365:                         if (@newcoowners || $delcoowners) {
                   10366:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   10367:                                             $delcoowners,@newcoowners);
                   10368:                         }
                   10369:                     }
                   10370:                 }
                   10371:             }
                   10372:         }
                   10373:     }
                   10374: }
                   10375: 
                   10376: sub store_coowners {
                   10377:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   10378:     my $cid = $cdom.'_'.$cnum;
                   10379:     my ($coowners,$delresult,$putresult);
                   10380:     if (@newcoowners) {
                   10381:         $coowners = join(',',@newcoowners);
                   10382:         my %coownershash = (
                   10383:                             'internal.co-owners' => $coowners,
                   10384:                            );
                   10385:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   10386:         if ($putresult eq 'ok') {
                   10387:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   10388:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   10389:             }
                   10390:         }
                   10391:     }
                   10392:     if ($delcoowners) {
                   10393:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   10394:         if ($delresult eq 'ok') {
                   10395:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   10396:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   10397:             }
                   10398:         }
                   10399:     }
                   10400:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   10401:         my %crsinfo =
                   10402:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   10403:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   10404:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   10405:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   10406:         }
                   10407:     }
                   10408: }
                   10409: 
1.169     harris41 10410: # -------------------------------------------------- Modify user authentication
1.197     www      10411: # Overrides without validation
                   10412: 
1.169     harris41 10413: sub modifyuserauth {
                   10414:     my ($udom,$uname,$umode,$upass)=@_;
                   10415:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  10416:     my $allowed;
                   10417:     if (&allowed('mau',$udom)) {
                   10418:         $allowed = 1;
                   10419:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   10420:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   10421:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   10422:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10423:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10424:         if (($cdom ne '') && ($cnum ne '')) {
                   10425:             my $is_owner = &is_course_owner($cdom,$cnum);
                   10426:             if ($is_owner) {
                   10427:                 $allowed = 1;
                   10428:             }
                   10429:         }
                   10430:     }
                   10431:     unless ($allowed) { return 'refused'; }
1.197     www      10432:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 10433:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10434:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 10435:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10436: 		     &escape($upass),$uhome);
1.1172.2.134  raeburn  10437:     my $ip = &get_requestor_ip();
1.620     albertel 10438:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10439:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.134  raeburn  10440:          '(Remote '.$ip.'): '.$reply);
1.197     www      10441:     &log($udom,,$uname,$uhome,
1.620     albertel 10442:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10443:                                      $env{'user.name'}.', '.$umode.
1.1172.2.134  raeburn  10444:          '(Remote '.$ip.'): '.$reply);
1.169     harris41 10445:     unless ($reply eq 'ok') {
1.197     www      10446:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10447: 	return 'error: '.$reply;
                   10448:     }   
1.170     harris41 10449:     return 'ok';
1.80      www      10450: }
                   10451: 
1.81      www      10452: # --------------------------------------------------------------- Modify a user
1.80      www      10453: 
1.81      www      10454: sub modifyuser {
1.206     matthew  10455:     my ($udom,    $uname, $uid,
                   10456:         $umode,   $upass, $first,
                   10457:         $middle,  $last,  $gene,
1.1058    raeburn  10458:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10459:     $udom= &LONCAPA::clean_domain($udom);
                   10460:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10461:     my $showcandelete = 'none';
                   10462:     if (ref($candelete) eq 'ARRAY') {
                   10463:         if (@{$candelete} > 0) {
                   10464:             $showcandelete = join(', ',@{$candelete});
                   10465:         }
                   10466:     }
1.81      www      10467:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10468:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10469: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10470:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10471:                                      ' desiredhome not specified'). 
1.620     albertel 10472:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10473:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10474:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10475:     my $newuser;
                   10476:     if ($uhome eq 'no_host') {
                   10477:         $newuser = 1;
                   10478:     }
1.80      www      10479: # ----------------------------------------------------------------- Create User
1.406     albertel 10480:     if (($uhome eq 'no_host') && 
                   10481: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      10482:         my $unhome='';
1.844     albertel 10483:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10484:             $unhome = $desiredhome;
1.620     albertel 10485: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10486: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10487:         } else { # load balancing routine for determining $unhome
1.81      www      10488:             my $loadm=10000000;
1.841     albertel 10489: 	    my %servers = &get_servers($udom,'library');
                   10490: 	    foreach my $tryserver (keys(%servers)) {
                   10491: 		my $answer=reply('load',$tryserver);
                   10492: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10493: 		    $loadm=$answer;
                   10494: 		    $unhome=$tryserver;
                   10495: 		}
1.80      www      10496: 	    }
                   10497:         }
                   10498:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10499: 	    return 'error: unable to find a home server for '.$uname.
                   10500:                    ' in domain '.$udom;
1.80      www      10501:         }
                   10502:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10503:                          &escape($upass),$unhome);
                   10504: 	unless ($reply eq 'ok') {
                   10505:             return 'error: '.$reply;
                   10506:         }   
1.230     stredwic 10507:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10508:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10509: 	    return 'error: unable verify users home machine.';
1.80      www      10510:         }
1.209     matthew  10511:     }   # End of creation of new user
1.80      www      10512: # ---------------------------------------------------------------------- Add ID
                   10513:     if ($uid) {
                   10514:        $uid=~tr/A-Z/a-z/;
                   10515:        my %uidhash=&idrget($udom,$uname);
1.196     www      10516:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10517:          && (!$forceid)) {
1.80      www      10518: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10519: 	      return 'error: user id "'.$uid.'" does not match '.
                   10520:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10521:           }
                   10522:        } else {
                   10523: 	  &idput($udom,($uname => $uid));
                   10524:        }
                   10525:     }
                   10526: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10527:     my @tmp=&get('environment',
1.899     raeburn  10528: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10529:                     'permanentemail','inststatus'],
1.134     albertel 10530: 		   $udom,$uname);
1.1075    raeburn  10531:     my (%names,%oldnames);
1.313     matthew  10532:     if ($tmp[0] =~ m/^error:.*/) { 
                   10533:         %names=(); 
                   10534:     } else {
                   10535:         %names = @tmp;
1.1075    raeburn  10536:         %oldnames = %names;
1.313     matthew  10537:     }
1.388     www      10538: #
1.1058    raeburn  10539: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10540: # of users did not contain them), do not overwrite existing values
                   10541: # unless field is in $candelete array ref.  
                   10542: #
                   10543: 
                   10544:     my @fields = ('firstname','middlename','lastname','generation',
                   10545:                   'permanentemail','id');
                   10546:     my %newvalues;
                   10547:     if (ref($candelete) eq 'ARRAY') {
                   10548:         foreach my $field (@fields) {
                   10549:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10550:                 if ($field eq 'firstname') {
                   10551:                     $names{$field} = $first;
                   10552:                 } elsif ($field eq 'middlename') {
                   10553:                     $names{$field} = $middle;
                   10554:                 } elsif ($field eq 'lastname') {
                   10555:                     $names{$field} = $last;
                   10556:                 } elsif ($field eq 'generation') { 
                   10557:                     $names{$field} = $gene;
                   10558:                 } elsif ($field eq 'permanentemail') {
                   10559:                     $names{$field} = $email;
                   10560:                 } elsif ($field eq 'id') {
                   10561:                     $names{$field}  = $uid;
                   10562:                 }
                   10563:             }
                   10564:         }
                   10565:     }
1.388     www      10566:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10567:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10568:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10569:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10570:     if ($email) {
                   10571:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10572:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10573:     }
1.899     raeburn  10574:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10575:     if (defined($inststatus)) {
                   10576:         $names{'inststatus'} = '';
                   10577:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10578:         if (ref($usertypes) eq 'HASH') {
                   10579:             my @okstatuses; 
                   10580:             foreach my $item (split(/:/,$inststatus)) {
                   10581:                 if (defined($usertypes->{$item})) {
                   10582:                     push(@okstatuses,$item);  
                   10583:                 }
                   10584:             }
                   10585:             if (@okstatuses) {
                   10586:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10587:             }
                   10588:         }
                   10589:     }
1.1075    raeburn  10590:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10591:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10592:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10593:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10594:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10595:     } else {
                   10596:         $logmsg .= ' during self creation';
                   10597:     }
1.1075    raeburn  10598:     my $changed;
                   10599:     if ($newuser) {
                   10600:         $changed = 1;
                   10601:     } else {
                   10602:         foreach my $field (@fields) {
                   10603:             if ($names{$field} ne $oldnames{$field}) {
                   10604:                 $changed = 1;
                   10605:                 last;
                   10606:             }
                   10607:         }
                   10608:     }
                   10609:     unless ($changed) {
                   10610:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10611:         &logthis($logmsg);
                   10612:         return 'ok';
                   10613:     }
                   10614:     my $reply = &put('environment', \%names, $udom,$uname);
                   10615:     if ($reply ne 'ok') { 
                   10616:         return 'error: '.$reply;
                   10617:     }
1.1087    raeburn  10618:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10619:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10620:     }
1.1075    raeburn  10621:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10622:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10623:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10624:     &logthis($logmsg);
1.134     albertel 10625:     return 'ok';
1.80      www      10626: }
                   10627: 
1.81      www      10628: # -------------------------------------------------------------- Modify student
1.80      www      10629: 
1.81      www      10630: sub modifystudent {
                   10631:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10632:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10633:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10634:     if (!$cid) {
1.620     albertel 10635: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10636: 	    return 'not_in_class';
                   10637: 	}
1.80      www      10638:     }
                   10639: # --------------------------------------------------------------- Make the user
1.81      www      10640:     my $reply=&modifyuser
1.209     matthew  10641: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10642:          $desiredhome,$email,$inststatus);
1.80      www      10643:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10644:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10645:     # student's environment
1.297     matthew  10646:     $uid = undef if (!$forceid);
1.455     albertel 10647:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10648: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10649:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10650:     return $reply;
                   10651: }
                   10652: 
                   10653: sub modify_student_enrollment {
1.1172.2.23  raeburn  10654:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10655:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10656:     my ($cdom,$cnum,$chome);
                   10657:     if (!$cid) {
1.620     albertel 10658: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10659: 	    return 'not_in_class';
                   10660: 	}
1.620     albertel 10661: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10662: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10663:     } else {
                   10664: 	($cdom,$cnum)=split(/_/,$cid);
                   10665:     }
1.620     albertel 10666:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10667:     if (!$chome) {
1.457     raeburn  10668: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10669:     }
1.455     albertel 10670:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10671:     # Make sure the user exists
1.81      www      10672:     my $uhome=&homeserver($uname,$udom);
                   10673:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10674: 	return 'error: no such user';
                   10675:     }
1.297     matthew  10676:     # Get student data if we were not given enough information
                   10677:     if (!defined($first)  || $first  eq '' || 
                   10678:         !defined($last)   || $last   eq '' || 
                   10679:         !defined($uid)    || $uid    eq '' || 
                   10680:         !defined($middle) || $middle eq '' || 
                   10681:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10682:         # They did not supply us with enough data to enroll the student, so
                   10683:         # we need to pick up more information.
1.297     matthew  10684:         my %tmp = &get('environment',
1.294     matthew  10685:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10686:                        ,$udom,$uname);
                   10687: 
1.800     albertel 10688:         #foreach my $key (keys(%tmp)) {
                   10689:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10690:         #}
1.294     matthew  10691:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10692:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10693:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10694:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10695:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10696:     }
1.556     albertel 10697:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10698:     my $user = "$uname:$udom";
                   10699:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10700:     my $reply=cput('classlist',
1.1148    raeburn  10701: 		   {$user => 
1.1172.2.76  raeburn  10702: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10703: 		   $cdom,$cnum);
1.1148    raeburn  10704:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10705:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10706:     } else { 
1.81      www      10707: 	return 'error: '.$reply;
                   10708:     }
1.297     matthew  10709:     # Add student role to user
1.83      www      10710:     my $uurl='/'.$cid;
1.81      www      10711:     $uurl=~s/\_/\//g;
                   10712:     if ($usec) {
                   10713: 	$uurl.='/'.$usec;
                   10714:     }
1.1148    raeburn  10715:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10716:                              $selfenroll,$context);
                   10717:     if ($result ne 'ok') {
                   10718:         if ($old_entry{$user} ne '') {
                   10719:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10720:         } else {
                   10721:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10722:         }
                   10723:     }
                   10724:     return $result; 
1.21      www      10725: }
                   10726: 
1.556     albertel 10727: sub format_name {
                   10728:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10729:     my $name;
                   10730:     if ($first ne 'lastname') {
                   10731: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10732:     } else {
                   10733: 	if ($lastname=~/\S/) {
                   10734: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10735: 	    $name=~s/\s+,/,/;
                   10736: 	} else {
                   10737: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10738: 	}
                   10739:     }
                   10740:     $name=~s/^\s+//;
                   10741:     $name=~s/\s+$//;
                   10742:     $name=~s/\s+/ /g;
                   10743:     return $name;
                   10744: }
                   10745: 
1.84      www      10746: # ------------------------------------------------- Write to course preferences
                   10747: 
                   10748: sub writecoursepref {
                   10749:     my ($courseid,%prefs)=@_;
                   10750:     $courseid=~s/^\///;
                   10751:     $courseid=~s/\_/\//g;
                   10752:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10753:     my $chome=homeserver($cnum,$cdomain);
                   10754:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10755: 	return 'error: no such course';
                   10756:     }
                   10757:     my $cstring='';
1.800     albertel 10758:     foreach my $pref (keys(%prefs)) {
                   10759: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10760:     }
1.84      www      10761:     $cstring=~s/\&$//;
                   10762:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10763: }
                   10764: 
                   10765: # ---------------------------------------------------------- Make/modify course
                   10766: 
                   10767: sub createcourse {
1.741     raeburn  10768:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1172.2.146.  .1(raebu 10769:22):         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      10770:     $url=&declutter($url);
                   10771:     my $cid='';
1.1028    raeburn  10772:     if ($context eq 'requestcourses') {
                   10773:         my $can_create = 0;
                   10774:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10775:         if ($udom eq $ownerdom) {
1.1172.2.146.  .1(raebu 10776:22):             my $reload;
                   10777:22):             if (($callercontext eq 'auto') &&
                   10778:22):                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   10779:22):                 $reload = 'reload';
                   10780:22):             }
                   10781:22):             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  10782:                                   $context)) {
                   10783:                 $can_create = 1;
                   10784:             }
                   10785:         } else {
                   10786:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10787:                                            $category);
                   10788:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10789:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10790:                 if (@curr > 0) {
                   10791:                     my @options = qw(approval validate autolimit);
                   10792:                     my $optregex = join('|',@options);
                   10793:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10794:                         $can_create = 1;
                   10795:                     }
                   10796:                 }
                   10797:             }
                   10798:         }
                   10799:         if ($can_create) {
                   10800:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10801:                 unless (&allowed('ccc',$udom)) {
                   10802:                     return 'refused'; 
                   10803:                 }
1.1017    raeburn  10804:             }
                   10805:         } else {
                   10806:             return 'refused';
                   10807:         }
1.1028    raeburn  10808:     } elsif (!&allowed('ccc',$udom)) {
                   10809:         return 'refused';
1.84      www      10810:     }
1.1011    raeburn  10811: # --------------------------------------------------------------- Get Unique ID
                   10812:     my $uname;
                   10813:     if ($cnum =~ /^$match_courseid$/) {
                   10814:         my $chome=&homeserver($cnum,$udom,'true');
                   10815:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10816:             $uname = $cnum;
                   10817:         } else {
1.1038    raeburn  10818:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10819:         }
                   10820:     } else {
1.1038    raeburn  10821:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10822:     }
                   10823:     return $uname if ($uname =~ /^error/);
                   10824: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10825:     if (!defined($course_server)) {
                   10826:         if (defined(&domain($udom,'primary'))) {
                   10827:             $course_server = &domain($udom,'primary');
                   10828:         } else {
                   10829:             $course_server = $env{'user.home'}; 
                   10830:         }
                   10831:     }
                   10832:     my %host_servers =
                   10833:         &Apache::lonnet::get_servers($udom,'library');
                   10834:     unless ($host_servers{$course_server}) {
                   10835:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  10836:     }
1.84      www      10837: # ------------------------------------------------------------- Make the course
                   10838:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  10839:                       $course_server);
1.84      www      10840:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  10841:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      10842:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10843: 	return 'error: no such course';
                   10844:     }
1.271     www      10845: # ----------------------------------------------------------------- Course made
1.516     raeburn  10846: # log existence
1.1029    raeburn  10847:     my $now = time;
1.918     raeburn  10848:     my $newcourse = {
                   10849:                     $udom.'_'.$uname => {
1.921     raeburn  10850:                                      description => $description,
                   10851:                                      inst_code   => $inst_code,
                   10852:                                      owner       => $course_owner,
                   10853:                                      type        => $crstype,
1.1029    raeburn  10854:                                      creator     => $env{'user.name'}.':'.
                   10855:                                                     $env{'user.domain'},
                   10856:                                      created     => $now,
                   10857:                                      context     => $context,
1.918     raeburn  10858:                                                 },
                   10859:                     };
1.921     raeburn  10860:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      10861: # set toplevel url
1.271     www      10862:     my $topurl=$url;
                   10863:     unless ($nonstandard) {
                   10864: # ------------------------------------------ For standard courses, make top url
                   10865:         my $mapurl=&clutter($url);
1.278     www      10866:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 10867:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      10868: <map>
                   10869: <resource id="1" type="start"></resource>
                   10870: <resource id="2" src="$mapurl"></resource>
                   10871: <resource id="3" type="finish"></resource>
                   10872: <link index="1" from="1" to="2"></link>
                   10873: <link index="2" from="2" to="3"></link>
                   10874: </map>
                   10875: ENDINITMAP
                   10876:         $topurl=&declutter(
1.638     albertel 10877:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      10878:                           );
                   10879:     }
                   10880: # ----------------------------------------------------------- Write preferences
1.84      www      10881:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  10882:                      ('description'              => $description,
                   10883:                       'url'                      => $topurl,
                   10884:                       'internal.creator'         => $env{'user.name'}.':'.
                   10885:                                                     $env{'user.domain'},
                   10886:                       'internal.created'         => $now,
                   10887:                       'internal.creationcontext' => $context)
                   10888:                     );
1.84      www      10889:     return '/'.$udom.'/'.$uname;
                   10890: }
                   10891: 
1.1011    raeburn  10892: # ------------------------------------------------------------------- Create ID
                   10893: sub generate_coursenum {
1.1038    raeburn  10894:     my ($udom,$crstype) = @_;
1.1011    raeburn  10895:     my $domdesc = &domain($udom);
                   10896:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10897:     my $first;
                   10898:     if ($crstype eq 'Community') {
                   10899:         $first = '0';
                   10900:     } else {
                   10901:         $first = int(1+rand(9)); 
                   10902:     } 
                   10903:     my $uname=$first.
1.1011    raeburn  10904:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10905:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10906:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10907: # ----------------------------------------------- Make sure that does not exist
                   10908:     my $uhome=&homeserver($uname,$udom,'true');
                   10909:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10910:         if ($crstype eq 'Community') {
                   10911:             $first = '0';
                   10912:         } else {
                   10913:             $first = int(1+rand(9));
                   10914:         }
                   10915:         $uname=$first.
1.1011    raeburn  10916:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10917:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10918:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10919:         $uhome=&homeserver($uname,$udom,'true');
                   10920:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10921:             return 'error: unable to generate unique course-ID';
                   10922:         }
                   10923:     }
                   10924:     return $uname;
                   10925: }
                   10926: 
1.813     albertel 10927: sub is_course {
1.1167    droeschl 10928:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10929:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  10930:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   10931:     my $uhome=&homeserver($cnum,$cdom);
                   10932:     my $iscourse;
                   10933:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   10934:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   10935:     } else {
                   10936:         my $hashid = $cdom.':'.$cnum;
                   10937:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   10938:         unless (defined($cached)) {
                   10939:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   10940:                                         $cnum,undef,undef,'.');
                   10941:             $iscourse = 0;
                   10942:             if (exists($courses{$cdom.'_'.$cnum})) {
                   10943:                 $iscourse = 1;
                   10944:             }
                   10945:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   10946:         }
                   10947:     }
                   10948:     return unless($iscourse);
1.1167    droeschl 10949:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10950: }
                   10951: 
1.1015    raeburn  10952: sub store_userdata {
                   10953:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10954:     my $result;
1.1016    raeburn  10955:     if ($datakey ne '') {
1.1013    raeburn  10956:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10957:             if ($udom eq '' || $uname eq '') {
                   10958:                 $udom = $env{'user.domain'};
                   10959:                 $uname = $env{'user.name'};
                   10960:             }
                   10961:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10962:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10963:                 $result = 'error: no_host';
                   10964:             } else {
1.1172.2.138  raeburn  10965:                 $storehash->{'ip'} = &get_requestor_ip();
1.1013    raeburn  10966:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10967: 
                   10968:                 my $namevalue='';
                   10969:                 foreach my $key (keys(%{$storehash})) {
                   10970:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10971:                 }
                   10972:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  10973:                 unless ($namespace eq 'courserequests') {
                   10974:                     $datakey = &escape($datakey);
                   10975:                 }
1.1105    raeburn  10976:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10977:                                   $namevalue,$uhome);
1.1013    raeburn  10978:             }
                   10979:         } else {
                   10980:             $result = 'error: data to store was not a hash reference'; 
                   10981:         }
                   10982:     } else {
                   10983:         $result= 'error: invalid requestkey'; 
                   10984:     }
                   10985:     return $result;
                   10986: }
                   10987: 
1.21      www      10988: # ---------------------------------------------------------- Assign Custom Role
                   10989: 
                   10990: sub assigncustomrole {
1.957     raeburn  10991:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10992:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10993:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10994: }
                   10995: 
                   10996: # ----------------------------------------------------------------- Revoke Role
                   10997: 
                   10998: sub revokerole {
1.957     raeburn  10999:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11000:     my $now=time;
1.965     raeburn  11001:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      11002: }
                   11003: 
                   11004: # ---------------------------------------------------------- Revoke Custom Role
                   11005: 
                   11006: sub revokecustomrole {
1.957     raeburn  11007:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11008:     my $now=time;
1.357     www      11009:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  11010:            $deleteflag,$selfenroll,$context);
1.17      www      11011: }
                   11012: 
1.533     banghart 11013: # ------------------------------------------------------------ Disk usage
1.535     albertel 11014: sub diskusage {
1.955     raeburn  11015:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   11016:     $directorypath =~ s/\/$//;
                   11017:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   11018:                        .&escape($getpropath).':'.&escape($uname).':'
                   11019:                        .&escape($udom),homeserver($uname,$udom));
                   11020:     if ($listing eq 'unknown_cmd') {
                   11021:         if ($getpropath) {
                   11022:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   11023:         }
                   11024:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   11025:     }
1.514     albertel 11026:     return $listing;
1.512     banghart 11027: }
                   11028: 
1.566     banghart 11029: sub is_locked {
1.1096    raeburn  11030:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 11031:     my @check;
                   11032:     my $is_locked;
1.1093    raeburn  11033:     push (@check,$file_name);
1.613     albertel 11034:     my %locked = &get('file_permissions',\@check,
1.620     albertel 11035: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 11036:     my ($tmp)=keys(%locked);
                   11037:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  11038:     
1.566     banghart 11039:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  11040:         $is_locked = 'false';
                   11041:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  11042:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  11043:                $is_locked = 'true';
1.1096    raeburn  11044:                if (ref($which) eq 'ARRAY') {
                   11045:                    push(@{$which},$entry);
                   11046:                } else {
                   11047:                    last;
                   11048:                }
1.745     raeburn  11049:            }
                   11050:        }
1.566     banghart 11051:     } else {
                   11052:         $is_locked = 'false';
                   11053:     }
1.1093    raeburn  11054:     return $is_locked;
1.566     banghart 11055: }
                   11056: 
1.759     albertel 11057: sub declutter_portfile {
                   11058:     my ($file) = @_;
1.833     albertel 11059:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 11060:     return $file;
                   11061: }
                   11062: 
1.559     banghart 11063: # ------------------------------------------------------------- Mark as Read Only
                   11064: 
                   11065: sub mark_as_readonly {
                   11066:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 11067:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11068:     my ($tmp)=keys(%current_permissions);
                   11069:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 11070:     foreach my $file (@{$files}) {
1.759     albertel 11071: 	$file = &declutter_portfile($file);
1.561     banghart 11072:         push(@{$current_permissions{$file}},$what);
1.559     banghart 11073:     }
1.613     albertel 11074:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11075:     return;
                   11076: }
                   11077: 
1.572     banghart 11078: # ------------------------------------------------------------Save Selected Files
                   11079: 
                   11080: sub save_selected_files {
                   11081:     my ($user, $path, @files) = @_;
                   11082:     my $filename = $user."savedfiles";
1.573     banghart 11083:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  11084:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 11085:     foreach my $file (@files) {
1.620     albertel 11086:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 11087:     }
                   11088:     foreach my $file (@other_files) {
1.574     banghart 11089:         print (OUT $file."\n");
1.572     banghart 11090:     }
1.574     banghart 11091:     close (OUT);
1.572     banghart 11092:     return 'ok';
                   11093: }
                   11094: 
1.574     banghart 11095: sub clear_selected_files {
                   11096:     my ($user) = @_;
                   11097:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  11098:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 11099:     print (OUT undef);
                   11100:     close (OUT);
                   11101:     return ("ok");    
                   11102: }
                   11103: 
1.572     banghart 11104: sub files_in_path {
                   11105:     my ($user, $path) = @_;
                   11106:     my $filename = $user."savedfiles";
                   11107:     my %return_files;
1.1172.2.96  raeburn  11108:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 11109:     while (my $line_in = <IN>) {
1.574     banghart 11110:         chomp ($line_in);
                   11111:         my @paths_and_file = split (m!/!, $line_in);
                   11112:         my $file_part = pop (@paths_and_file);
                   11113:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 11114:         $path_part.='/';
                   11115:         my $path_and_file = $path_part.$file_part;
                   11116:         if ($path_part eq $path) {
                   11117:             $return_files{$file_part}= 'selected';
                   11118:         }
                   11119:     }
1.574     banghart 11120:     close (IN);
                   11121:     return (\%return_files);
1.572     banghart 11122: }
                   11123: 
                   11124: # called in portfolio select mode, to show files selected NOT in current directory
                   11125: sub files_not_in_path {
                   11126:     my ($user, $path) = @_;
                   11127:     my $filename = $user."savedfiles";
                   11128:     my @return_files;
                   11129:     my $path_part;
1.1172.2.96  raeburn  11130:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 11131:     while (my $line = <IN>) {
1.572     banghart 11132:         #ok, I know it's clunky, but I want it to work
1.800     albertel 11133:         my @paths_and_file = split(m|/|, $line);
                   11134:         my $file_part = pop(@paths_and_file);
                   11135:         chomp($file_part);
                   11136:         my $path_part = join('/', @paths_and_file);
1.572     banghart 11137:         $path_part .= '/';
                   11138:         my $path_and_file = $path_part.$file_part;
                   11139:         if ($path_part ne $path) {
1.800     albertel 11140:             push(@return_files, ($path_and_file));
1.572     banghart 11141:         }
                   11142:     }
1.800     albertel 11143:     close(OUT);
1.574     banghart 11144:     return (@return_files);
1.572     banghart 11145: }
                   11146: 
1.745     raeburn  11147: #----------------------------------------------Get portfolio file permissions
1.629     banghart 11148: 
1.745     raeburn  11149: sub get_portfile_permissions {
                   11150:     my ($domain,$user) = @_;
1.613     albertel 11151:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11152:     my ($tmp)=keys(%current_permissions);
                   11153:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11154:     return \%current_permissions;
                   11155: }
                   11156: 
                   11157: #---------------------------------------------Get portfolio file access controls
                   11158: 
1.749     raeburn  11159: sub get_access_controls {
1.745     raeburn  11160:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 11161:     my %access;
                   11162:     my $real_file = $file;
                   11163:     $file =~ s/\.meta$//;
1.745     raeburn  11164:     if (defined($file)) {
1.749     raeburn  11165:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   11166:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 11167:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  11168:             }
                   11169:         }
1.745     raeburn  11170:     } else {
1.749     raeburn  11171:         foreach my $key (keys(%{$current_permissions})) {
                   11172:             if ($key =~ /\0accesscontrol$/) {
                   11173:                 if (defined($group)) {
                   11174:                     if ($key !~ m-^\Q$group\E/-) {
                   11175:                         next;
                   11176:                     }
                   11177:                 }
                   11178:                 my ($fullpath) = split(/\0/,$key);
                   11179:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   11180:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   11181:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   11182:                     }
                   11183:                 }
                   11184:             }
                   11185:         }
                   11186:     }
                   11187:     return %access;
                   11188: }
                   11189: 
                   11190: sub modify_access_controls {
                   11191:     my ($file_name,$changes,$domain,$user)=@_;
                   11192:     my ($outcome,$deloutcome);
                   11193:     my %store_permissions;
                   11194:     my %new_values;
                   11195:     my %new_control;
                   11196:     my %translation;
                   11197:     my @deletions = ();
                   11198:     my $now = time;
                   11199:     if (exists($$changes{'activate'})) {
                   11200:         if (ref($$changes{'activate'}) eq 'HASH') {
                   11201:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   11202:             my $numnew = scalar(@newitems);
                   11203:             for (my $i=0; $i<$numnew; $i++) {
                   11204:                 my $newkey = $newitems[$i];
                   11205:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  11206:                 if ($newkey =~ /^\d+:/) { 
                   11207:                     $newkey =~ s/^(\d+)/$newid/;
                   11208:                     $translation{$1} = $newid;
                   11209:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   11210:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   11211:                     $translation{$1} = $newid;
                   11212:                 }
1.749     raeburn  11213:                 $new_values{$file_name."\0".$newkey} = 
                   11214:                                           $$changes{'activate'}{$newitems[$i]};
                   11215:                 $new_control{$newkey} = $now;
                   11216:             }
                   11217:         }
                   11218:     }
                   11219:     my %todelete;
                   11220:     my %changed_items;
                   11221:     foreach my $action ('delete','update') {
                   11222:         if (exists($$changes{$action})) {
                   11223:             if (ref($$changes{$action}) eq 'HASH') {
                   11224:                 foreach my $key (keys(%{$$changes{$action}})) {
                   11225:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   11226:                     if ($action eq 'delete') { 
                   11227:                         $todelete{$itemnum} = 1;
                   11228:                     } else {
                   11229:                         $changed_items{$itemnum} = $key;
                   11230:                     }
                   11231:                 }
1.745     raeburn  11232:             }
                   11233:         }
1.749     raeburn  11234:     }
                   11235:     # get lock on access controls for file.
                   11236:     my $lockhash = {
                   11237:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   11238:                                                        ':'.$env{'user.domain'},
                   11239:                    }; 
                   11240:     my $tries = 0;
                   11241:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11242:    
1.1172.2.79  raeburn  11243:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  11244:         $tries ++;
1.1172.2.79  raeburn  11245:         sleep(0.1);
1.749     raeburn  11246:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11247:     }
                   11248:     if ($gotlock eq 'ok') {
                   11249:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   11250:         my ($tmp)=keys(%curr_permissions);
                   11251:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   11252:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   11253:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   11254:             if (ref($curr_controls) eq 'HASH') {
                   11255:                 foreach my $control_item (keys(%{$curr_controls})) {
                   11256:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   11257:                     if (defined($todelete{$itemnum})) {
                   11258:                         push(@deletions,$file_name."\0".$control_item);
                   11259:                     } else {
                   11260:                         if (defined($changed_items{$itemnum})) {
                   11261:                             $new_control{$changed_items{$itemnum}} = $now;
                   11262:                             push(@deletions,$file_name."\0".$control_item);
                   11263:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   11264:                         } else {
                   11265:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   11266:                         }
                   11267:                     }
1.745     raeburn  11268:                 }
                   11269:             }
                   11270:         }
1.970     raeburn  11271:         my ($group);
                   11272:         if (&is_course($domain,$user)) {
                   11273:             ($group,my $file) = split(/\//,$file_name,2);
                   11274:         }
1.749     raeburn  11275:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   11276:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   11277:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   11278:         #  remove lock
                   11279:         my @del_lock = ($file_name."\0".'locked_access_records');
                   11280:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  11281:         my $sqlresult =
1.970     raeburn  11282:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  11283:                                     $group);
1.749     raeburn  11284:     } else {
                   11285:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  11286:     }
1.749     raeburn  11287:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  11288: }
                   11289: 
1.827     raeburn  11290: sub make_public_indefinitely {
                   11291:     my ($requrl) = @_;
                   11292:     my $now = time;
                   11293:     my $action = 'activate';
                   11294:     my $aclnum = 0;
                   11295:     if (&is_portfolio_url($requrl)) {
                   11296:         my (undef,$udom,$unum,$file_name,$group) =
                   11297:             &parse_portfolio_url($requrl);
                   11298:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   11299:         my %access_controls = &get_access_controls($current_perms,
                   11300:                                                    $group,$file_name);
                   11301:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   11302:             my ($num,$scope,$end,$start) = 
                   11303:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   11304:             if ($scope eq 'public') {
                   11305:                 if ($start <= $now && $end == 0) {
                   11306:                     $action = 'none';
                   11307:                 } else {
                   11308:                     $action = 'update';
                   11309:                     $aclnum = $num;
                   11310:                 }
                   11311:                 last;
                   11312:             }
                   11313:         }
                   11314:         if ($action eq 'none') {
                   11315:              return 'ok';
                   11316:         } else {
                   11317:             my %changes;
                   11318:             my $newend = 0;
                   11319:             my $newstart = $now;
                   11320:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   11321:             $changes{$action}{$newkey} = {
                   11322:                 type => 'public',
                   11323:                 time => {
                   11324:                     start => $newstart,
                   11325:                     end   => $newend,
                   11326:                 },
                   11327:             };
                   11328:             my ($outcome,$deloutcome,$new_values,$translation) =
                   11329:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   11330:             return $outcome;
                   11331:         }
                   11332:     } else {
                   11333:         return 'invalid';
                   11334:     }
                   11335: }
                   11336: 
1.745     raeburn  11337: #------------------------------------------------------Get Marked as Read Only
                   11338: 
                   11339: sub get_marked_as_readonly {
                   11340:     my ($domain,$user,$what,$group) = @_;
                   11341:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 11342:     my @readonly_files;
1.629     banghart 11343:     my $cmp1=$what;
                   11344:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  11345:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11346:         if (defined($group)) {
                   11347:             if ($file_name !~ m-^\Q$group\E/-) {
                   11348:                 next;
                   11349:             }
                   11350:         }
1.561     banghart 11351:         if (ref($value) eq "ARRAY"){
                   11352:             foreach my $stored_what (@{$value}) {
1.629     banghart 11353:                 my $cmp2=$stored_what;
1.759     albertel 11354:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  11355:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  11356:                 }
1.629     banghart 11357:                 if ($cmp1 eq $cmp2) {
1.561     banghart 11358:                     push(@readonly_files, $file_name);
1.745     raeburn  11359:                     last;
1.563     banghart 11360:                 } elsif (!defined($what)) {
                   11361:                     push(@readonly_files, $file_name);
1.745     raeburn  11362:                     last;
1.561     banghart 11363:                 }
                   11364:             }
1.745     raeburn  11365:         }
1.561     banghart 11366:     }
                   11367:     return @readonly_files;
                   11368: }
1.577     banghart 11369: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 11370: 
1.577     banghart 11371: sub get_marked_as_readonly_hash {
1.745     raeburn  11372:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 11373:     my %readonly_files;
1.745     raeburn  11374:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11375:         if (defined($group)) {
                   11376:             if ($file_name !~ m-^\Q$group\E/-) {
                   11377:                 next;
                   11378:             }
                   11379:         }
1.577     banghart 11380:         if (ref($value) eq "ARRAY"){
                   11381:             foreach my $stored_what (@{$value}) {
1.745     raeburn  11382:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 11383:                     foreach my $lock_descriptor(@{$stored_what}) {
                   11384:                         if ($lock_descriptor eq 'graded') {
                   11385:                             $readonly_files{$file_name} = 'graded';
                   11386:                         } elsif ($lock_descriptor eq 'handback') {
                   11387:                             $readonly_files{$file_name} = 'handback';
                   11388:                         } else {
                   11389:                             if (!exists($readonly_files{$file_name})) {
                   11390:                                 $readonly_files{$file_name} = 'locked';
                   11391:                             }
                   11392:                         }
1.745     raeburn  11393:                     }
1.750     banghart 11394:                 } 
1.577     banghart 11395:             }
                   11396:         } 
                   11397:     }
                   11398:     return %readonly_files;
                   11399: }
1.559     banghart 11400: # ------------------------------------------------------------ Unmark as Read Only
                   11401: 
                   11402: sub unmark_as_readonly {
1.629     banghart 11403:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   11404:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  11405:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 11406:     $file_name = &declutter_portfile($file_name);
1.634     albertel 11407:     my $symb_crs = $what;
                   11408:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  11409:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 11410:     my ($tmp)=keys(%current_permissions);
                   11411:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11412:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 11413:     foreach my $file (@readonly_files) {
1.759     albertel 11414: 	my $clean_file = &declutter_portfile($file);
                   11415: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 11416: 	my $current_locks = $current_permissions{$file};
1.563     banghart 11417:         my @new_locks;
                   11418:         my @del_keys;
                   11419:         if (ref($current_locks) eq "ARRAY"){
                   11420:             foreach my $locker (@{$current_locks}) {
1.632     albertel 11421:                 my $compare=$locker;
1.749     raeburn  11422:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  11423:                     $compare=join('',@{$locker});
1.746     raeburn  11424:                     if ($compare ne $symb_crs) {
                   11425:                         push(@new_locks, $locker);
                   11426:                     }
1.563     banghart 11427:                 }
                   11428:             }
1.650     albertel 11429:             if (scalar(@new_locks) > 0) {
1.563     banghart 11430:                 $current_permissions{$file} = \@new_locks;
                   11431:             } else {
                   11432:                 push(@del_keys, $file);
1.613     albertel 11433:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11434:                 delete($current_permissions{$file});
1.563     banghart 11435:             }
                   11436:         }
1.561     banghart 11437:     }
1.613     albertel 11438:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11439:     return;
                   11440: }
1.512     banghart 11441: 
1.17      www      11442: # ------------------------------------------------------------ Directory lister
                   11443: 
                   11444: sub dirlist {
1.955     raeburn  11445:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11446:     $uri=~s/^\///;
                   11447:     $uri=~s/\/$//;
1.253     stredwic 11448:     my ($udom, $uname);
1.955     raeburn  11449:     if ($getuserdir) {
1.253     stredwic 11450:         $udom = $userdomain;
                   11451:         $uname = $username;
1.955     raeburn  11452:     } else {
                   11453:         (undef,$udom,$uname)=split(/\//,$uri);
                   11454:         if(defined($userdomain)) {
                   11455:             $udom = $userdomain;
                   11456:         }
                   11457:         if(defined($username)) {
                   11458:             $uname = $username;
                   11459:         }
1.253     stredwic 11460:     }
1.955     raeburn  11461:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11462: 
1.955     raeburn  11463:     $dirRoot = $perlvar{'lonDocRoot'};
                   11464:     if (defined($getpropath)) {
                   11465:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11466:         $dirRoot =~ s/\/$//;
1.955     raeburn  11467:     } elsif (defined($getuserdir)) {
                   11468:         my $subdir=$uname.'__';
                   11469:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11470:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11471:                    ."/$udom/$subdir/$uname";
                   11472:     } elsif (defined($alternateRoot)) {
                   11473:         $dirRoot = $alternateRoot;
1.751     banghart 11474:     }
1.253     stredwic 11475: 
                   11476:     if($udom) {
                   11477:         if($uname) {
1.1135    raeburn  11478:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11479:             if ($uhome eq 'no_host') {
                   11480:                 return ([],'no_host');
                   11481:             }
1.955     raeburn  11482:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11483:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11484:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11485:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11486:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11487:             } else {
                   11488:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11489:             }
1.605     matthew  11490:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11491:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11492:                 @listing_results = split(/:/,$listing);
                   11493:             } else {
                   11494:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11495:             }
1.1135    raeburn  11496:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11497:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11498:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11499:                 return ([],$listing);
                   11500:             } else {
                   11501:                 return (\@listing_results);
1.1135    raeburn  11502:             }
1.955     raeburn  11503:         } elsif(!$alternateRoot) {
1.1136    raeburn  11504:             my (%allusers,%listerror);
1.841     albertel 11505: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11506:  	    foreach my $tryserver (keys(%servers)) {
                   11507:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11508:                                   &escape($udom),$tryserver);
                   11509:                 if ($listing eq 'unknown_cmd') {
                   11510: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11511: 				      $udom, $tryserver);
                   11512:                 } else {
                   11513:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11514:                 }
1.841     albertel 11515: 		if ($listing eq 'unknown_cmd') {
                   11516: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11517: 				      $udom, $tryserver);
                   11518: 		    @listing_results = split(/:/,$listing);
                   11519: 		} else {
                   11520: 		    @listing_results =
                   11521: 			map { &unescape($_); } split(/:/,$listing);
                   11522: 		}
1.1136    raeburn  11523:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11524:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11525:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11526:                     $listerror{$tryserver} = $listing;
                   11527:                 } else {
1.841     albertel 11528: 		    foreach my $line (@listing_results) {
                   11529: 			my ($entry) = split(/&/,$line,2);
                   11530: 			$allusers{$entry} = 1;
                   11531: 		    }
                   11532: 		}
1.253     stredwic 11533:             }
1.1136    raeburn  11534:             my @alluserslist=();
1.800     albertel 11535:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11536:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11537:             }
1.1172.2.80  raeburn  11538:             if (!%listerror) {
                   11539:                 # no errors
                   11540:                 return (\@alluserslist);
                   11541:             } elsif (scalar(keys(%servers)) == 1) {
                   11542:                 # one library server, one error
                   11543:                 my ($key) = keys(%listerror);
                   11544:                 return (\@alluserslist, $listerror{$key});
                   11545:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11546:                 # con_lost indicates that we might miss data from at least one
                   11547:                 # library server
                   11548:                 return (\@alluserslist, 'con_lost');
                   11549:             } else {
                   11550:                 # multiple library servers and no con_lost -> data should be
                   11551:                 # complete.
                   11552:                 return (\@alluserslist);
                   11553:             }
                   11554: 
1.253     stredwic 11555:         } else {
1.1136    raeburn  11556:             return ([],'missing username');
1.253     stredwic 11557:         }
1.955     raeburn  11558:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11559:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11560:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11561:         return (\@all_domains);
1.955     raeburn  11562:     } else {
1.1136    raeburn  11563:         return ([],'missing domain');
1.275     stredwic 11564:     }
                   11565: }
                   11566: 
                   11567: # --------------------------------------------- GetFileTimestamp
                   11568: # This function utilizes dirlist and returns the date stamp for
                   11569: # when it was last modified.  It will also return an error of -1
                   11570: # if an error occurs
                   11571: 
                   11572: sub GetFileTimestamp {
1.955     raeburn  11573:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11574:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11575:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11576:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11577:                                     undef,$getuserdir);
                   11578:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11579:         return -1;
                   11580:     }
                   11581:     if (ref($fileref) eq 'ARRAY') {
                   11582:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11583:         # @stats contains first the filename, then the stat output
                   11584:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11585:     } else {
                   11586:         return -1;
1.253     stredwic 11587:     }
1.26      www      11588: }
                   11589: 
1.712     albertel 11590: sub stat_file {
                   11591:     my ($uri) = @_;
1.787     albertel 11592:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11593: 
1.955     raeburn  11594:     my ($udom,$uname,$file);
1.712     albertel 11595:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11596: 	($udom,$uname,$file) =
1.811     albertel 11597: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11598: 	$file = 'userfiles/'.$file;
                   11599:     }
                   11600:     if ($uri =~ m-^/res/-) {
                   11601: 	($udom,$uname) = 
1.807     albertel 11602: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11603: 	$file = $uri;
                   11604:     }
                   11605: 
                   11606:     if (!$udom || !$uname || !$file) {
                   11607: 	# unable to handle the uri
                   11608: 	return ();
                   11609:     }
1.956     raeburn  11610:     my $getpropath;
                   11611:     if ($file =~ /^userfiles\//) {
                   11612:         $getpropath = 1;
                   11613:     }
1.1136    raeburn  11614:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11615:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11616:         return ();
                   11617:     } else {
                   11618:         if (ref($listref) eq 'ARRAY') {
                   11619:             my @stats = split('&',$listref->[0]);
                   11620: 	    shift(@stats); #filename is first
                   11621: 	    return @stats;
                   11622:         }
1.712     albertel 11623:     }
                   11624:     return ();
                   11625: }
                   11626: 
1.26      www      11627: # -------------------------------------------------------- Value of a Condition
                   11628: 
1.713     albertel 11629: # gets the value of a specific preevaluated condition
                   11630: #    stored in the string  $env{user.state.<cid>}
                   11631: # or looks up a condition reference in the bighash and if if hasn't
                   11632: # already been evaluated recurses into docondval to get the value of
                   11633: # the condition, then memoizing it to 
                   11634: #   $env{user.state.<cid>.<condition>}
1.40      www      11635: sub directcondval {
                   11636:     my $number=shift;
1.620     albertel 11637:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11638: 	&Apache::lonuserstate::evalstate();
                   11639:     }
1.713     albertel 11640:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11641: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11642:     } elsif ($number =~ /^_/) {
                   11643: 	my $sub_condition;
                   11644: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11645: 		&GDBM_READER(),0640)) {
                   11646: 	    $sub_condition=$bighash{'conditions'.$number};
                   11647: 	    untie(%bighash);
                   11648: 	}
                   11649: 	my $value = &docondval($sub_condition);
1.949     raeburn  11650: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11651: 	return $value;
                   11652:     }
1.620     albertel 11653:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11654:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11655:     } else {
                   11656:        return 2;
                   11657:     }
                   11658: }
                   11659: 
1.713     albertel 11660: # get the collection of conditions for this resource
1.26      www      11661: sub condval {
                   11662:     my $condidx=shift;
1.54      www      11663:     my $allpathcond='';
1.713     albertel 11664:     foreach my $cond (split(/\|/,$condidx)) {
                   11665: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11666: 	    $allpathcond.=
                   11667: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11668: 	}
1.191     harris41 11669:     }
1.54      www      11670:     $allpathcond=~s/\|$//;
1.713     albertel 11671:     return &docondval($allpathcond);
                   11672: }
                   11673: 
                   11674: #evaluates an expression of conditions
                   11675: sub docondval {
                   11676:     my ($allpathcond) = @_;
                   11677:     my $result=0;
                   11678:     if ($env{'request.course.id'}
                   11679: 	&& defined($allpathcond)) {
                   11680: 	my $operand='|';
                   11681: 	my @stack;
                   11682: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11683: 	    if ($chunk eq '(') {
                   11684: 		push @stack,($operand,$result);
                   11685: 	    } elsif ($chunk eq ')') {
                   11686: 		my $before=pop @stack;
                   11687: 		if (pop @stack eq '&') {
                   11688: 		    $result=$result>$before?$before:$result;
                   11689: 		} else {
                   11690: 		    $result=$result>$before?$result:$before;
                   11691: 		}
                   11692: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11693: 		$operand=$chunk;
                   11694: 	    } else {
                   11695: 		my $new=directcondval($chunk);
                   11696: 		if ($operand eq '&') {
                   11697: 		    $result=$result>$new?$new:$result;
                   11698: 		} else {
                   11699: 		    $result=$result>$new?$result:$new;
                   11700: 		}
                   11701: 	    }
                   11702: 	}
1.26      www      11703:     }
                   11704:     return $result;
1.421     albertel 11705: }
                   11706: 
                   11707: # ---------------------------------------------------- Devalidate courseresdata
                   11708: 
                   11709: sub devalidatecourseresdata {
                   11710:     my ($coursenum,$coursedomain)=@_;
                   11711:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11712:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11713: }
                   11714: 
1.763     www      11715: 
1.200     www      11716: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11717: #
                   11718: #  Parameters:
                   11719: #      $coursenum    - Number of the course.
                   11720: #      $coursedomain - Domain at which the course was created.
                   11721: #  Returns:
                   11722: #     A hash of the course parameters along (I think) with timestamps
                   11723: #     and version info.
1.877     foxr     11724: 
1.624     albertel 11725: sub get_courseresdata {
                   11726:     my ($coursenum,$coursedomain)=@_;
1.200     www      11727:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11728:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11729:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11730:     my %dumpreply;
1.417     albertel 11731:     unless (defined($cached)) {
1.624     albertel 11732: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11733: 	$result=\%dumpreply;
1.251     albertel 11734: 	my ($tmp) = keys(%dumpreply);
                   11735: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11736: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11737: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11738: 	    return $tmp;
1.416     albertel 11739: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11740: 	    $result=undef;
1.599     albertel 11741: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11742: 	}
                   11743:     }
1.624     albertel 11744:     return $result;
                   11745: }
                   11746: 
1.633     albertel 11747: sub devalidateuserresdata {
                   11748:     my ($uname,$udom)=@_;
                   11749:     my $hashid="$udom:$uname";
                   11750:     &devalidate_cache_new('userres',$hashid);
                   11751: }
                   11752: 
1.624     albertel 11753: sub get_userresdata {
                   11754:     my ($uname,$udom)=@_;
                   11755:     #most student don\'t have any data set, check if there is some data
                   11756:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11757: 
                   11758:     my $hashid="$udom:$uname";
                   11759:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11760:     if (!defined($cached)) {
                   11761: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11762: 	$result=\%resourcedata;
                   11763: 	&do_cache_new('userres',$hashid,$result,600);
                   11764:     }
                   11765:     my ($tmp)=keys(%$result);
                   11766:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11767: 	return $result;
                   11768:     }
                   11769:     #error 2 occurs when the .db doesn't exist
                   11770:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11771:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11772: 	    &logthis("<font color=\"blue\">WARNING:".
                   11773: 		     " Trying to get resource data for ".
                   11774: 		     $uname." at ".$udom.": ".
                   11775: 		     $tmp."</font>");
                   11776:         }
1.624     albertel 11777:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11778: 	#&EXT_cache_set($udom,$uname);
                   11779: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11780: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11781:     }
                   11782:     return $tmp;
                   11783: }
1.879     foxr     11784: #----------------------------------------------- resdata - return resource data
                   11785: #  Purpose:
                   11786: #    Return resource data for either users or for a course.
                   11787: #  Parameters:
                   11788: #     $name      - Course/user name.
                   11789: #     $domain    - Name of the domain the user/course is registered on.
                   11790: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   11791: #     @which     - Array of names of resources desired.
                   11792: #  Returns:
                   11793: #     The value of the first reasource in @which that is found in the
                   11794: #     resource hash.
                   11795: #  Exceptional Conditions:
                   11796: #     If the $type passed in is not valid (not the string 'course' or 
                   11797: #     'user', an undefined  reference is returned.
                   11798: #     If none of the resources are found, an undef is returned
1.624     albertel 11799: sub resdata {
                   11800:     my ($name,$domain,$type,@which)=@_;
                   11801:     my $result;
                   11802:     if ($type eq 'course') {
                   11803: 	$result=&get_courseresdata($name,$domain);
                   11804:     } elsif ($type eq 'user') {
                   11805: 	$result=&get_userresdata($name,$domain);
                   11806:     }
                   11807:     if (!ref($result)) { return $result; }    
1.251     albertel 11808:     foreach my $item (@which) {
1.927     albertel 11809: 	if (defined($result->{$item->[0]})) {
                   11810: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11811: 	}
1.250     albertel 11812:     }
1.291     albertel 11813:     return undef;
1.200     www      11814: }
                   11815: 
1.1172.2.146.  .1(raebu 11816:22): sub get_domain_lti {
                   11817:22):     my ($cdom,$context) = @_;
          .4(raebu 11818:22):     my ($name,$cachename,%lti);
          .1(raebu 11819:22):     if ($context eq 'consumer') {
                   11820:22):         $name = 'ltitools';
                   11821:22):     } elsif ($context eq 'provider') {
                   11822:22):         $name = 'lti';
          .4(raebu 11823:22):     } elsif ($context eq 'linkprot') {
                   11824:22):         $name = 'ltisec';
          .1(raebu 11825:22):     } else {
                   11826:22):         return %lti;
                   11827:22):     }
          .4(raebu 11828:22): 
                   11829:22):     if ($context eq 'linkprot') {
                   11830:22):         $cachename = $context;
                   11831:22):     } else {
                   11832:22):         $cachename = $name;
                   11833:22):     }
                   11834:22): 
                   11835:22):     my ($result,$cached)=&is_cached_new($cachename,$cdom);
          .1(raebu 11836:22):     if (defined($cached)) {
                   11837:22):         if (ref($result) eq 'HASH') {
                   11838:22):             %lti = %{$result};
                   11839:22):         }
                   11840:22):     } else {
                   11841:22):         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   11842:22):         if (ref($domconfig{$name}) eq 'HASH') {
          .4(raebu 11843:22):             if ($context eq 'linkprot') {
                   11844:22):                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
                   11845:22):                     %lti = %{$domconfig{$name}{'linkprot'}};
                   11846:22):                 }
                   11847:22):             } else {
                   11848:22):                 %lti = %{$domconfig{$name}};
                   11849:22):             }
                   11850:22):             if (($context eq 'consumer') && (keys(%lti))) {
                   11851:22):                 my %encdomconfig = &get_dom('encconfig',[$name],$cdom,undef,1);
                   11852:22):                 if (ref($encdomconfig{$name}) eq 'HASH') {
                   11853:22):                     foreach my $id (keys(%lti)) {
                   11854:22):                         if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
                   11855:22):                             foreach my $item ('key','secret') {
                   11856:22):                                 $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
                   11857:22):                             }
          .1(raebu 11858:22):                         }
                   11859:22):                     }
                   11860:22):                 }
                   11861:22):             }
                   11862:22):         }
                   11863:22):         my $cachetime = 24*60*60;
          .4(raebu 11864:22):         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
          .1(raebu 11865:22):     }
                   11866:22):     return %lti;
                   11867:22): }
                   11868:22): 
                   11869:22): sub get_course_lti {
                   11870:22):     my ($cnum,$cdom) = @_;
                   11871:22):     my $hashid=$cdom.'_'.$cnum;
                   11872:22):     my %courselti;
                   11873:22):     my ($result,$cached)=&is_cached_new('courselti',$hashid);
                   11874:22):     if (defined($cached)) {
                   11875:22):         if (ref($result) eq 'HASH') {
                   11876:22):             %courselti = %{$result};
                   11877:22):         }
                   11878:22):     } else {
                   11879:22):         %courselti = &dump('lti',$cdom,$cnum,undef,undef,undef,1);
                   11880:22):         my $cachetime = 24*60*60;
                   11881:22):         &do_cache_new('courselti',$hashid,\%courselti,$cachetime);
                   11882:22):     }
                   11883:22):     return %courselti;
                   11884:22): }
                   11885:22): 
          .3(raebu 11886:22): sub courselti_itemid {
                   11887:22):     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
                   11888:22):     my ($chome,$itemid);
                   11889:22):     $chome = &homeserver($cnum,$cdom);
                   11890:22):     return if ($chome eq 'no_host');
                   11891:22):     if (ref($params) eq 'HASH') {
                   11892:22):         my $rep;
                   11893:22):         if (grep { $_ eq $chome } current_machine_ids()) {
                   11894:22):             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
                   11895:22):         } else {
                   11896:22):             my $escurl = &escape($url);
                   11897:22):             my $escmethod = &escape($method);
                   11898:22):             my $items = &freeze_escape($params);
                   11899:22):             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
                   11900:22):         }
                   11901:22):         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   11902:22):                 ($rep eq 'unknown_cmd')) {
                   11903:22):             $itemid = $rep;
                   11904:22):         }
                   11905:22):     }
                   11906:22):     return $itemid;
                   11907:22): }
                   11908:22): 
                   11909:22): sub domainlti_itemid {
                   11910:22):     my ($cdom,$url,$method,$params,$context) = @_;
                   11911:22):     my ($primary_id,$itemid);
                   11912:22):     $primary_id = &domain($cdom,'primary');
                   11913:22):     return if ($primary_id eq '');
                   11914:22):     if (ref($params) eq 'HASH') {
                   11915:22):         my $rep;
                   11916:22):         if (grep { $_ eq $primary_id } current_machine_ids()) {
                   11917:22):             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
                   11918:22):         } else {
                   11919:22):             my $cnum = '';
                   11920:22):             my $escurl = &escape($url);
                   11921:22):             my $escmethod = &escape($method);
                   11922:22):             my $items = &freeze_escape($params);
                   11923:22):             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
                   11924:22):         }
                   11925:22):         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   11926:22):                 ($rep eq 'unknown_cmd')) {
                   11927:22):             $itemid = $rep;
                   11928:22):         }
                   11929:22):     }
                   11930:22):     return $itemid;
                   11931:22): }
                   11932:22): 
          .9(raebu 11933:23): sub count_supptools {
                   11934:23):     my ($cnum,$cdom,$ignorecache,$reload)=@_;
1.1172.2.31  raeburn  11935:     my $hashid=$cnum.':'.$cdom;
1.1172.2.146.  .9(raebu 11936:23):     my ($numexttools,$cached);
1.1172.2.31  raeburn  11937:     unless ($ignorecache) {
1.1172.2.146.  .9(raebu 11938:23):         ($numexttools,$cached) = &is_cached_new('supptools',$hashid);
1.1172.2.31  raeburn  11939:     }
                   11940:     unless (defined($cached)) {
                   11941:         my $chome=&homeserver($cnum,$cdom);
1.1172.2.146.  .9(raebu 11942:23):         $numexttools = 0;
1.1172.2.31  raeburn  11943:         unless ($chome eq 'no_host') {
1.1172.2.146.  .9(raebu 11944:23):             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$reload);
                   11945:23):             if (ref($supplemental) eq 'HASH') {
                   11946:23):                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   11947:23):                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
                   11948:23):                         if ($key =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   11949:23):                             $numexttools ++;
                   11950:23):                         }
                   11951:23):                     }
                   11952:23):                 }
                   11953:23):             }
1.1172.2.31  raeburn  11954:         }
1.1172.2.146.  .9(raebu 11955:23):         &do_cache_new('supptools',$hashid,$numexttools,600);
1.1172.2.31  raeburn  11956:     }
1.1172.2.146.  .9(raebu 11957:23):     return $numexttools;
                   11958:23): }
                   11959:23): 
                   11960:23): sub has_unhidden_suppfiles {
                   11961:23):     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
                   11962:23):     my $hashid=$cnum.':'.$cdom;
                   11963:23):     my ($showsupp,$cached);
                   11964:23):     unless ($ignorecache) {
                   11965:23):         ($showsupp,$cached) = &is_cached_new('showsupp',$hashid);
                   11966:23):     }
                   11967:23):     unless (defined($cached)) {
                   11968:23):         my $chome=&homeserver($cnum,$cdom);
                   11969:23):         unless ($chome eq 'no_host') {
                   11970:23):             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$ignorecache,$possdel);
                   11971:23):             if (ref($supplemental) eq 'HASH') {
                   11972:23):                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   11973:23):                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
                   11974:23):                         next if ($key =~ /\.sequence$/);
                   11975:23):                         if (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
                   11976:23):                             foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
                   11977:23):                                 unless ($supplemental->{'hidden'}->{$id}) {
                   11978:23):                                     $showsupp = 1;
                   11979:23):                                     last;
                   11980:23):                                 }
                   11981:23):                             }
                   11982:23):                         }
                   11983:23):                         last if ($showsupp);
                   11984:23):                     }
                   11985:23):                 }
                   11986:23):             }
                   11987:23):         }
                   11988:23):         &do_cache_new('showsupp',$hashid,$showsupp,600);
                   11989:23):     }
                   11990:23):     return $showsupp;
1.1172.2.31  raeburn  11991: }
                   11992: 
1.379     matthew  11993: #
                   11994: # EXT resource caching routines
                   11995: #
                   11996: 
1.1172.2.146.  .1(raebu 11997:22): {
                   11998:22): # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   11999:22): #
                   12000:22): # The course for which we cache
                   12001:22): my $cachedmapkey='';
                   12002:22): # The cached recursive maps for this course
                   12003:22): my %cachedmaps=();
                   12004:22): # When this was last done
                   12005:22): my $cachedmaptime='';
                   12006:22): 
1.379     matthew  12007: sub clear_EXT_cache_status {
1.383     albertel 12008:     &delenv('cache.EXT.');
1.379     matthew  12009: }
                   12010: 
                   12011: sub EXT_cache_status {
                   12012:     my ($target_domain,$target_user) = @_;
1.383     albertel 12013:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 12014:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  12015:         # We know already the user has no data
                   12016:         return 1;
                   12017:     } else {
                   12018:         return 0;
                   12019:     }
                   12020: }
                   12021: 
                   12022: sub EXT_cache_set {
                   12023:     my ($target_domain,$target_user) = @_;
1.383     albertel 12024:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  12025:     #&appenv({$cachename => time});
1.379     matthew  12026: }
                   12027: 
1.28      www      12028: # --------------------------------------------------------- Value of a Variable
1.58      www      12029: sub EXT {
1.715     albertel 12030: 
1.1172.2.28  raeburn  12031:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      12032:     unless ($varname) { return ''; }
1.218     albertel 12033:     #get real user name/domain, courseid and symb
                   12034:     my $courseid;
1.359     albertel 12035:     my $publicuser;
1.427     www      12036:     if ($symbparm) {
                   12037: 	$symbparm=&get_symb_from_alias($symbparm);
                   12038:     }
1.218     albertel 12039:     if (!($uname && $udom)) {
1.790     albertel 12040:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 12041:       if (!$symbparm) {	$symbparm=$cursymb; }
                   12042:     } else {
1.620     albertel 12043: 	$courseid=$env{'request.course.id'};
1.218     albertel 12044:     }
1.48      www      12045:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   12046:     my $rest;
1.320     albertel 12047:     if (defined($therest[0])) {
1.48      www      12048:        $rest=join('.',@therest);
                   12049:     } else {
                   12050:        $rest='';
                   12051:     }
1.320     albertel 12052: 
1.57      www      12053:     my $qualifierrest=$qualifier;
                   12054:     if ($rest) { $qualifierrest.='.'.$rest; }
                   12055:     my $spacequalifierrest=$space;
                   12056:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      12057:     if ($realm eq 'user') {
1.48      www      12058: # --------------------------------------------------------------- user.resource
                   12059: 	if ($space eq 'resource') {
1.651     albertel 12060: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   12061: 		  || defined($Apache::lonhomework::parsing_a_task))
                   12062: 		 &&
1.1172.2.142  raeburn  12063: 		 ($symbparm eq &symbread()) ) {
1.744     albertel 12064: 		# if we are in the middle of processing the resource the
                   12065: 		# get the value we are planning on committing
                   12066:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   12067:                     return $Apache::lonhomework::results{$qualifierrest};
                   12068:                 } else {
                   12069:                     return $Apache::lonhomework::history{$qualifierrest};
                   12070:                 }
1.335     albertel 12071: 	    } else {
1.359     albertel 12072: 		my %restored;
1.620     albertel 12073: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 12074: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   12075: 		} else {
                   12076: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   12077: 		}
1.335     albertel 12078: 		return $restored{$qualifierrest};
                   12079: 	    }
1.48      www      12080: # ----------------------------------------------------------------- user.access
                   12081:         } elsif ($space eq 'access') {
1.218     albertel 12082: 	    # FIXME - not supporting calls for a specific user
1.48      www      12083:             return &allowed($qualifier,$rest);
                   12084: # ------------------------------------------ user.preferences, user.environment
                   12085:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 12086: 	    if (($uname eq $env{'user.name'}) &&
                   12087: 		($udom eq $env{'user.domain'})) {
                   12088: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 12089: 	    } else {
1.359     albertel 12090: 		my %returnhash;
                   12091: 		if (!$publicuser) {
                   12092: 		    %returnhash=&userenvironment($udom,$uname,
                   12093: 						 $qualifierrest);
                   12094: 		}
1.218     albertel 12095: 		return $returnhash{$qualifierrest};
                   12096: 	    }
1.48      www      12097: # ----------------------------------------------------------------- user.course
                   12098:         } elsif ($space eq 'course') {
1.218     albertel 12099: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12100:             return $env{join('.',('request.course',$qualifier))};
1.48      www      12101: # ------------------------------------------------------------------- user.role
                   12102:         } elsif ($space eq 'role') {
1.218     albertel 12103: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12104:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      12105:             if ($qualifier eq 'value') {
                   12106: 		return $role;
                   12107:             } elsif ($qualifier eq 'extent') {
                   12108:                 return $where;
                   12109:             }
                   12110: # ----------------------------------------------------------------- user.domain
                   12111:         } elsif ($space eq 'domain') {
1.218     albertel 12112:             return $udom;
1.48      www      12113: # ------------------------------------------------------------------- user.name
                   12114:         } elsif ($space eq 'name') {
1.218     albertel 12115:             return $uname;
1.48      www      12116: # ---------------------------------------------------- Any other user namespace
1.29      www      12117:         } else {
1.359     albertel 12118: 	    my %reply;
                   12119: 	    if (!$publicuser) {
                   12120: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   12121: 	    }
                   12122: 	    return $reply{$qualifierrest};
1.48      www      12123:         }
1.236     www      12124:     } elsif ($realm eq 'query') {
                   12125: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 12126:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   12127: 						[$spacequalifierrest]);
1.620     albertel 12128: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      12129:    } elsif ($realm eq 'request') {
1.48      www      12130: # ------------------------------------------------------------- request.browser
                   12131:         if ($space eq 'browser') {
1.1145    bisitz   12132:             return $env{'browser.'.$qualifier};
1.57      www      12133: # ------------------------------------------------------------ request.filename
                   12134:         } else {
1.620     albertel 12135:             return $env{'request.'.$spacequalifierrest};
1.29      www      12136:         }
1.28      www      12137:     } elsif ($realm eq 'course') {
1.48      www      12138: # ---------------------------------------------------------- course.description
1.620     albertel 12139:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      12140:     } elsif ($realm eq 'resource') {
1.165     www      12141: 
1.620     albertel 12142: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 12143: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   12144: 	}
1.693     albertel 12145: 
1.1172.2.30  raeburn  12146:         if ($qualifier eq '') {
                   12147: 	    if ($space eq 'title') {
                   12148: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   12149: 	        return &gettitle($symbparm);
                   12150: 	    }
1.693     albertel 12151: 	
1.1172.2.30  raeburn  12152: 	    if ($space eq 'map') {
                   12153: 	        my ($map) = &decode_symb($symbparm);
                   12154: 	        return &symbread($map);
                   12155: 	    }
                   12156:             if ($space eq 'maptitle') {
                   12157:                 my ($map) = &decode_symb($symbparm);
                   12158:                 return &gettitle($map);
                   12159:             }
                   12160: 	    if ($space eq 'filename') {
                   12161: 	        if ($symbparm) {
                   12162: 		    return &clutter((&decode_symb($symbparm))[2]);
                   12163: 	        }
                   12164: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 12165: 	    }
1.1172.2.30  raeburn  12166: 
                   12167:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   12168:                 if ($space eq 'visibleparts') {
                   12169:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   12170:                     my $item;
                   12171:                     if (ref($navmap)) {
                   12172:                         my $res = $navmap->getBySymb($symbparm);
                   12173:                         my $parts = $res->parts();
                   12174:                         if (ref($parts) eq 'ARRAY') {
                   12175:                             $item = join(',',@{$parts});
                   12176:                         }
                   12177:                         undef($navmap);
                   12178:                     }
                   12179:                     return $item;
                   12180:                 }
                   12181:             }
                   12182:         }
1.693     albertel 12183: 
                   12184: 	my ($section, $group, @groups);
1.593     albertel 12185: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  12186:         if (($courseid eq '') && ($cid)) {
                   12187:             $courseid = $cid;
                   12188:         }
                   12189: 	if (($symbparm && $courseid) && 
                   12190: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      12191: 
1.218     albertel 12192: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      12193: 
1.60      www      12194: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 12195: 	    my $symbp=$symbparm;
1.735     albertel 12196: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 12197: 
                   12198: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   12199: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   12200: 
1.620     albertel 12201: 	    if (($env{'user.name'} eq $uname) &&
                   12202: 		($env{'user.domain'} eq $udom)) {
                   12203: 		$section=$env{'request.course.sec'};
1.733     raeburn  12204:                 @groups = split(/:/,$env{'request.course.groups'});  
                   12205:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 12206: 	    } else {
1.539     albertel 12207: 		if (! defined($usection)) {
1.551     albertel 12208: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 12209: 		} else {
                   12210: 		    $section = $usection;
                   12211: 		}
1.733     raeburn  12212:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 12213: 	    }
                   12214: 
                   12215: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   12216: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   12217: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   12218: 
1.593     albertel 12219: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 12220: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 12221: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      12222: 
1.60      www      12223: # ----------------------------------------------------------- first, check user
1.624     albertel 12224: 
                   12225: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 12226: 				       ([$courselevelr,'resource'],
                   12227: 					[$courselevelm,'map'     ],
                   12228: 					[$courselevel, 'course'  ]));
1.931     albertel 12229: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      12230: 
1.594     albertel 12231: # ------------------------------------------------ second, check some of course
1.684     raeburn  12232:             my $coursereply;
1.691     raeburn  12233:             if (@groups > 0) {
                   12234:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   12235:                                        $mapparm,$spacequalifierrest);
1.927     albertel 12236:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  12237:             }
1.96      www      12238: 
1.684     raeburn  12239: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 12240: 				  $env{'course.'.$courseid.'.domain'},
                   12241: 				  'course',
                   12242: 				  ([$seclevelr,   'resource'],
                   12243: 				   [$seclevelm,   'map'     ],
                   12244: 				   [$seclevel,    'course'  ],
                   12245: 				   [$courselevelr,'resource']));
                   12246: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      12247: 
1.60      www      12248: # ------------------------------------------------------ third, check map parms
1.218     albertel 12249: 	    my %parmhash=();
                   12250: 	    my $thisparm='';
                   12251: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 12252: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 12253: 		    &GDBM_READER(),0640)) {
1.218     albertel 12254: 		$thisparm=$parmhash{$symbparm};
                   12255: 		untie(%parmhash);
                   12256: 	    }
1.927     albertel 12257: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 12258: 	}
1.594     albertel 12259: # ------------------------------------------ fourth, look in resource metadata
1.71      www      12260: 
1.218     albertel 12261: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 12262: 	my $filename;
                   12263: 	if (!$symbparm) { $symbparm=&symbread(); }
                   12264: 	if ($symbparm) {
1.409     www      12265: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 12266: 	} else {
1.620     albertel 12267: 	    $filename=$env{'request.filename'};
1.282     albertel 12268: 	}
                   12269: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 12270: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 12271: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 12272: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      12273: 
1.927     albertel 12274: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 12275: 	if ($symbparm && defined($courseid) && 
1.620     albertel 12276: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 12277: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   12278: 				     $env{'course.'.$courseid.'.domain'},
                   12279: 				     'course',
1.927     albertel 12280: 				     ([$courselevelm,'map'   ],
                   12281: 				      [$courselevel, 'course']));
                   12282: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 12283: 	}
1.145     www      12284: # ------------------------------------------------------------------ Cascade up
1.218     albertel 12285: 	unless ($space eq '0') {
1.336     albertel 12286: 	    my @parts=split(/_/,$space);
                   12287: 	    my $id=pop(@parts);
                   12288: 	    my $part=join('_',@parts);
                   12289: 	    if ($part eq '') { $part='0'; }
1.927     albertel 12290: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 12291: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  12292: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 12293: 	}
1.395     albertel 12294: 	if ($recurse) { return undef; }
                   12295: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 12296: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      12297: # ---------------------------------------------------- Any other user namespace
                   12298:     } elsif ($realm eq 'environment') {
                   12299: # ----------------------------------------------------------------- environment
1.620     albertel 12300: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   12301: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 12302: 	} else {
1.770     albertel 12303: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   12304: 		return '';
                   12305: 	    }
1.219     albertel 12306: 	    my %returnhash=&userenvironment($udom,$uname,
                   12307: 					    $spacequalifierrest);
                   12308: 	    return $returnhash{$spacequalifierrest};
                   12309: 	}
1.28      www      12310:     } elsif ($realm eq 'system') {
1.48      www      12311: # ----------------------------------------------------------------- system.time
                   12312: 	if ($space eq 'time') {
                   12313: 	    return time;
                   12314:         }
1.696     albertel 12315:     } elsif ($realm eq 'server') {
                   12316: # ----------------------------------------------------------------- system.time
                   12317: 	if ($space eq 'name') {
                   12318: 	    return $ENV{'SERVER_NAME'};
                   12319:         }
1.1172.2.146.  .1(raebu 12320:22):     } elsif ($realm eq 'client') {
                   12321:22):         if ($space eq 'remote_addr') {
                   12322:22):             return &get_requestor_ip();
                   12323:22):         }
1.28      www      12324:     }
1.48      www      12325:     return '';
1.61      www      12326: }
                   12327: 
1.927     albertel 12328: sub get_reply {
                   12329:     my ($reply_value) = @_;
1.940     raeburn  12330:     if (ref($reply_value) eq 'ARRAY') {
                   12331:         if (wantarray) {
                   12332: 	    return @$reply_value;
                   12333:         }
                   12334:         return $reply_value->[0];
                   12335:     } else {
                   12336:         return $reply_value;
1.927     albertel 12337:     }
                   12338: }
                   12339: 
1.691     raeburn  12340: sub check_group_parms {
                   12341:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   12342:     my @groupitems = ();
                   12343:     my $resultitem;
1.927     albertel 12344:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  12345:     foreach my $group (@{$groups}) {
                   12346:         foreach my $level (@levels) {
1.927     albertel 12347:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   12348:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  12349:         }
                   12350:     }
                   12351:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   12352:                             $env{'course.'.$courseid.'.domain'},
                   12353:                                      'course',@groupitems);
                   12354:     return $coursereply;
                   12355: }
                   12356: 
1.1172.2.146.  .1(raebu 12357:22): sub get_map_hierarchy {
                   12358:22):     my ($mapname,$courseid) = @_;
                   12359:22):     my @recurseup = ();
                   12360:22):     if ($mapname) {
                   12361:22):         if (($cachedmapkey eq $courseid) &&
                   12362:22):             (abs($cachedmaptime-time)<5)) {
                   12363:22):             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   12364:22):                 return @{$cachedmaps{$mapname}};
                   12365:22):             }
                   12366:22):         }
                   12367:22):         my $navmap = Apache::lonnavmaps::navmap->new();
                   12368:22):         if (ref($navmap)) {
                   12369:22):             @recurseup = $navmap->recurseup_maps($mapname);
                   12370:22):             undef($navmap);
                   12371:22):             $cachedmaps{$mapname} = \@recurseup;
                   12372:22):             $cachedmaptime=time;
                   12373:22):             $cachedmapkey=$courseid;
                   12374:22):         }
                   12375:22):     }
                   12376:22):     return @recurseup;
                   12377:22): }
                   12378:22): 
          .2(raebu 12379:22): }
          .1(raebu 12380:22): 
1.691     raeburn  12381: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  12382:     my ($courseid,@groups) = @_;
                   12383:     @groups = sort(@groups);
1.691     raeburn  12384:     return @groups;
                   12385: }
                   12386: 
1.395     albertel 12387: sub packages_tab_default {
                   12388:     my ($uri,$varname)=@_;
                   12389:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 12390: 
                   12391:     my (@extension,@specifics,$do_default);
                   12392:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 12393: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 12394: 	if ($pack_type eq 'default') {
                   12395: 	    $do_default=1;
                   12396: 	} elsif ($pack_type eq 'extension') {
                   12397: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 12398: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 12399: 	    # only look at packages defaults for packages that this id is
1.738     albertel 12400: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   12401: 	}
                   12402:     }
                   12403:     # first look for a package that matches the requested part id
                   12404:     foreach my $package (@specifics) {
                   12405: 	my (undef,$pack_type,$pack_part)=@{$package};
                   12406: 	next if ($pack_part ne $part);
                   12407: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12408: 	    return $packagetab{"$pack_type&$name&default"};
                   12409: 	}
                   12410:     }
                   12411:     # look for any possible matching non extension_ package
                   12412:     foreach my $package (@specifics) {
                   12413: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 12414: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12415: 	    return $packagetab{"$pack_type&$name&default"};
                   12416: 	}
1.585     albertel 12417: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 12418: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   12419: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 12420: 	}
                   12421:     }
1.738     albertel 12422:     # look for any posible extension_ match
                   12423:     foreach my $package (@extension) {
                   12424: 	my ($package,$pack_type)=@{$package};
                   12425: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12426: 	    return $packagetab{"$pack_type&$name&default"};
                   12427: 	}
                   12428: 	if (defined($packagetab{$package."&$name&default"})) {
                   12429: 	    return $packagetab{$package."&$name&default"};
                   12430: 	}
                   12431:     }
                   12432:     # look for a global default setting
                   12433:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   12434: 	return $packagetab{"default&$name&default"};
                   12435:     }
1.395     albertel 12436:     return undef;
                   12437: }
                   12438: 
1.334     albertel 12439: sub add_prefix_and_part {
                   12440:     my ($prefix,$part)=@_;
                   12441:     my $keyroot;
                   12442:     if (defined($prefix) && $prefix !~ /^__/) {
                   12443: 	# prefix that has a part already
                   12444: 	$keyroot=$prefix;
                   12445:     } elsif (defined($prefix)) {
                   12446: 	# prefix that is missing a part
                   12447: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   12448:     } else {
                   12449: 	# no prefix at all
                   12450: 	if (defined($part)) { $keyroot='_'.$part; }
                   12451:     }
                   12452:     return $keyroot;
                   12453: }
                   12454: 
1.71      www      12455: # ---------------------------------------------------------------- Get metadata
                   12456: 
1.599     albertel 12457: my %metaentry;
1.1070    www      12458: my %importedpartids;
1.1172.2.99  raeburn  12459: my %importedrespids;
1.71      www      12460: sub metadata {
1.176     www      12461:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      12462:     $uri=&declutter($uri);
1.288     albertel 12463:     # if it is a non metadata possible uri return quickly
1.529     albertel 12464:     if (($uri eq '') || 
                   12465: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.146.  .1(raebu 12466:22): 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  12467:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 12468: 	return undef;
                   12469:     }
1.1172.2.49  raeburn  12470:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 12471: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 12472: 	return undef;
1.288     albertel 12473:     }
1.73      www      12474:     my $filename=$uri;
                   12475:     $uri=~s/\.meta$//;
1.172     www      12476: #
                   12477: # Is the metadata already cached?
1.177     www      12478: # Look at timestamp of caching
1.172     www      12479: # Everything is cached by the main uri, libraries are never directly cached
                   12480: #
1.428     albertel 12481:     if (!defined($liburi)) {
1.599     albertel 12482: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 12483: 	if (defined($cached)) { return $result->{':'.$what}; }
                   12484:     }
                   12485:     {
1.1069    www      12486: # Imported parts would go here
1.1172.2.99  raeburn  12487:         my @origfiletagids=();
1.1069    www      12488:         my $importedparts=0;
1.1172.2.99  raeburn  12489: 
                   12490: # Imported responseids would go here
                   12491:         my $importedresponses=0;
1.172     www      12492: #
                   12493: # Is this a recursive call for a library?
                   12494: #
1.599     albertel 12495: #	if (! exists($metacache{$uri})) {
                   12496: #	    $metacache{$uri}={};
                   12497: #	}
1.924     albertel 12498: 	my $cachetime = 60*60;
1.171     www      12499:         if ($liburi) {
                   12500: 	    $liburi=&declutter($liburi);
                   12501:             $filename=$liburi;
1.401     bowersj2 12502:         } else {
1.599     albertel 12503: 	    &devalidate_cache_new('meta',$uri);
                   12504: 	    undef(%metaentry);
1.401     bowersj2 12505: 	}
1.140     www      12506:         my %metathesekeys=();
1.73      www      12507:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 12508: 	my $metastring;
1.1140    www      12509: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 12510: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 12511: 	    $metastring = 
1.929     albertel 12512: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 12513: 					  ('grade_target' => 'meta'));
                   12514: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  12515: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   12516:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 12517: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 12518: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 12519: 	    $metastring=&getfile($file);
1.489     albertel 12520: 	}
1.208     albertel 12521:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      12522:         my $token;
1.140     www      12523:         undef %metathesekeys;
1.71      www      12524:         while ($token=$parser->get_token) {
1.339     albertel 12525: 	    if ($token->[0] eq 'S') {
                   12526: 		if (defined($token->[2]->{'package'})) {
1.172     www      12527: #
                   12528: # This is a package - get package info
                   12529: #
1.339     albertel 12530: 		    my $package=$token->[2]->{'package'};
                   12531: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12532: 		    if (defined($token->[2]->{'id'})) { 
                   12533: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12534: 		    }
1.599     albertel 12535: 		    if ($metaentry{':packages'}) {
                   12536: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12537: 		    } else {
1.599     albertel 12538: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12539: 		    }
1.736     albertel 12540: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12541: 			my $part=$keyroot;
                   12542: 			$part=~s/^\_//;
1.736     albertel 12543: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12544: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12545: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12546: 			    # ignore package.tab specified default values
                   12547:                             # here &package_tab_default() will fetch those
                   12548: 			    if ($subp eq 'default') { next; }
1.736     albertel 12549: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12550: 			    my $unikey;
                   12551: 			    if ($pack =~ /_0$/) {
                   12552: 				$unikey='parameter_0_'.$name;
                   12553: 				$part=0;
                   12554: 			    } else {
                   12555: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12556: 			    }
1.339     albertel 12557: 			    if ($subp eq 'display') {
                   12558: 				$value.=' [Part: '.$part.']';
                   12559: 			    }
1.599     albertel 12560: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12561: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12562: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12563: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12564: 			    }
1.599     albertel 12565: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12566: 				$metaentry{':'.$unikey}=
                   12567: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12568: 			    }
1.339     albertel 12569: 			}
                   12570: 		    }
                   12571: 		} else {
1.172     www      12572: #
                   12573: # This is not a package - some other kind of start tag
1.339     albertel 12574: #
                   12575: 		    my $entry=$token->[1];
1.1068    www      12576: 		    my $unikey='';
1.175     www      12577: 
1.339     albertel 12578: 		    if ($entry eq 'import') {
1.175     www      12579: #
                   12580: # Importing a library here
1.339     albertel 12581: #
1.1067    www      12582:                         my $location=$parser->get_text('/import');
                   12583:                         my $dir=$filename;
                   12584:                         $dir=~s|[^/]*$||;
                   12585:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  12586: 
                   12587:                         my $importid=$token->[2]->{'id'};
1.1068    www      12588:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  12589: #
                   12590: # Check metadata for imported file to
                   12591: # see if it contained response items
                   12592: #
                   12593:                         my %currmetaentry = %metaentry;
                   12594:                         my $libresponseorder = &metadata($location,'responseorder');
                   12595:                         my $origfile;
                   12596:                         if ($libresponseorder ne '') {
                   12597:                             if ($#origfiletagids<0) {
                   12598:                                 undef(%importedrespids);
                   12599:                                 undef(%importedpartids);
                   12600:                             }
                   12601:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   12602:                             if (@{$importedrespids{$importid}} > 0) {
                   12603:                                 $importedresponses = 1;
                   12604: # We need to get the original file and the imported file to get the response order correct
                   12605: # Load and inspect original file
                   12606:                                 if ($#origfiletagids<0) {
                   12607:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12608:                                     $origfile=&getfile($origfilelocation);
                   12609:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12610:                                 }
                   12611:                             }
                   12612:                         }
                   12613: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12614: # hash populated for imported library file
                   12615:                         %metaentry = %currmetaentry;
                   12616:                         undef(%currmetaentry);
1.1068    www      12617:                         if ($importmode eq 'problem') {
1.1069    www      12618: # Import as problem/response
1.1068    www      12619:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12620:                         } elsif ($importmode eq 'part') {
                   12621: # Import as part(s)
1.1069    www      12622:                            $importedparts=1;
                   12623: # We need to get the original file and the imported file to get the part order correct
                   12624: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  12625: # Load and inspect original file if we didn't do that already
                   12626:                            if ($#origfiletagids<0) {
                   12627:                                undef(%importedrespids);
                   12628:                                undef(%importedpartids);
                   12629:                                if ($origfile eq '') {
                   12630:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12631:                                    $origfile=&getfile($origfilelocation);
                   12632:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12633:                                }
1.1070    www      12634:                            }
                   12635: 
1.1069    www      12636: # Load and inspect imported file
                   12637:                            my $impfile=&getfile($location);
                   12638:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12639:                            if ($#impfilepartids>=0) {
                   12640: # This problem had parts
1.1070    www      12641:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12642:                            } else {
                   12643: # Importing by turning a single problem into a problem part
                   12644: # It gets the import-tags ID as part-ID
                   12645:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12646:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12647:                            }
1.1068    www      12648:                         } else {
                   12649: # Normal import
                   12650:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12651:                            if (defined($token->[2]->{'id'})) {
                   12652:                               $unikey.='_'.$token->[2]->{'id'};
                   12653:                            }
1.1067    www      12654:                         }
                   12655: 
1.339     albertel 12656: 			if ($depthcount<20) {
1.736     albertel 12657: 			    my $metadata = 
                   12658: 				&metadata($uri,'keys', $location,$unikey,
                   12659: 					  $depthcount+1);
                   12660: 			    foreach my $meta (split(',',$metadata)) {
                   12661: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12662: 				$metathesekeys{$meta}=1;
1.339     albertel 12663: 			    }
1.1068    www      12664: 			
                   12665:                         }
1.1067    www      12666: 		    } else {
                   12667: #
                   12668: # Not importing, some other kind of non-package, non-library start tag
                   12669: # 
                   12670:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12671:                         if (defined($token->[2]->{'id'})) {
                   12672:                             $unikey.='_'.$token->[2]->{'id'};
                   12673:                         }
1.339     albertel 12674: 			if (defined($token->[2]->{'name'})) { 
                   12675: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12676: 			}
                   12677: 			$metathesekeys{$unikey}=1;
1.736     albertel 12678: 			foreach my $param (@{$token->[3]}) {
                   12679: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12680: 				$token->[2]->{$param};
1.339     albertel 12681: 			}
                   12682: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12683: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12684: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12685: 		 # only ws inside the tag, and not in default, so use default
                   12686: 		 # as value
1.599     albertel 12687: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12688: 			} elsif ( $internaltext =~ /\S/ ) {
                   12689: 		  # something interesting inside the tag
                   12690: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12691: 			} else {
1.908     albertel 12692: 		  # no interesting values, don't set a default
1.339     albertel 12693: 			}
1.172     www      12694: # end of not-a-package not-a-library import
1.339     albertel 12695: 		    }
1.172     www      12696: # end of not-a-package start tag
1.339     albertel 12697: 		}
1.172     www      12698: # the next is the end of "start tag"
1.339     albertel 12699: 	    }
                   12700: 	}
1.483     albertel 12701: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12702: 	$extension = lc($extension);
                   12703: 	if ($extension eq 'htm') { $extension='html'; }
                   12704: 
1.737     albertel 12705: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12706: 	    #no specific packages #how's our extension
                   12707: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12708: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12709: 					 \%metathesekeys);
                   12710: 	}
1.883     albertel 12711: 
                   12712: 	if (!exists($metaentry{':packages'})
                   12713: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12714: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12715: 		#no specific packages well let's get default then
                   12716: 		if ($key!~/^default&/) { next; }
1.488     albertel 12717: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12718: 					     \%metathesekeys);
                   12719: 	    }
                   12720: 	}
1.338     www      12721: # are there custom rights to evaluate
1.599     albertel 12722: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12723: 
1.338     www      12724:     #
                   12725:     # Importing a rights file here
1.339     albertel 12726:     #
                   12727: 	    unless ($depthcount) {
1.599     albertel 12728: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12729: 		my $dir=$filename;
                   12730: 		$dir=~s|[^/]*$||;
                   12731: 		$location=&filelocation($dir,$location);
1.736     albertel 12732: 		my $rights_metadata =
                   12733: 		    &metadata($uri,'keys',$location,'_rights',
                   12734: 			      $depthcount+1);
                   12735: 		foreach my $rights (split(',',$rights_metadata)) {
                   12736: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12737: 		    $metathesekeys{$rights}=1;
1.339     albertel 12738: 		}
                   12739: 	    }
                   12740: 	}
1.737     albertel 12741: 	# uniqifiy package listing
                   12742: 	my %seen;
                   12743: 	my @uniq_packages =
                   12744: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12745: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12746: 
1.1172.2.99  raeburn  12747:         if (($importedresponses) || ($importedparts)) {
                   12748:             if ($importedparts) {
1.1070    www      12749: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  12750:                 $metaentry{':partorder'}='';
                   12751:                 $metathesekeys{'partorder'}=1;
                   12752:             }
                   12753:             if ($importedresponses) {
                   12754: # We had imported responses and need to rebuild responseorder
                   12755:                 $metaentry{':responseorder'}='';
                   12756:                 $metathesekeys{'responseorder'}=1;
                   12757:             }
                   12758:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12759:                 my $origid = $origfiletagids[$index+1];
                   12760:                 if ($origfiletagids[$index] eq 'part') {
                   12761: # Original part, part of the problem
                   12762:                     if ($importedparts) {
                   12763:                         $metaentry{':partorder'}.=','.$origid;
                   12764:                     }
                   12765:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12766:                     if ($importedparts) {
                   12767: # We have imported parts at this position
                   12768:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12769:                     }
                   12770:                     if ($importedresponses) {
                   12771: # We have imported responses at this position
                   12772:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   12773:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   12774:                         }
                   12775:                     }
                   12776:                 } else {
                   12777: # Original response item, part of the problem
                   12778:                     if ($importedresponses) {
                   12779:                         $metaentry{':responseorder'}.=','.$origid;
                   12780:                     }
                   12781:                 }
                   12782:             }
                   12783:             if ($importedparts) {
                   12784:                 $metaentry{':partorder'}=~s/^\,//;
                   12785:             }
                   12786:             if ($importedresponses) {
                   12787:                 $metaentry{':responseorder'}=~s/^\,//;
                   12788:             }
1.1070    www      12789:         }
                   12790: 
1.737     albertel 12791: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12792: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  12793: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 12794: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      12795: # this is the end of "was not already recently cached
1.71      www      12796:     }
1.599     albertel 12797:     return $metaentry{':'.$what};
1.261     albertel 12798: }
                   12799: 
1.488     albertel 12800: sub metadata_create_package_def {
1.483     albertel 12801:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12802:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12803:     if ($subp eq 'default') { next; }
                   12804:     
1.599     albertel 12805:     if (defined($metaentry{':packages'})) {
                   12806: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12807:     } else {
1.599     albertel 12808: 	$metaentry{':packages'}=$package;
1.483     albertel 12809:     }
                   12810:     my $value=$packagetab{$key};
                   12811:     my $unikey;
                   12812:     $unikey='parameter_0_'.$name;
1.599     albertel 12813:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12814:     $$metathesekeys{$unikey}=1;
1.599     albertel 12815:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12816: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12817:     }
1.599     albertel 12818:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12819: 	$metaentry{':'.$unikey}=
                   12820: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12821:     }
                   12822: }
                   12823: 
1.261     albertel 12824: sub metadata_generate_part0 {
                   12825:     my ($metadata,$metacache,$uri) = @_;
                   12826:     my %allnames;
1.737     albertel 12827:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12828: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12829: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12830: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12831: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12832: 	    $allnames{$name}=$part;
                   12833: 	  }
                   12834: 	}
                   12835:     }
                   12836:     foreach my $name (keys(%allnames)) {
                   12837:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12838:       my $key=":parameter_0_$name";
1.261     albertel 12839:       $$metacache{"$key.part"}='0';
                   12840:       $$metacache{"$key.name"}=$name;
1.428     albertel 12841:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12842: 					   $allnames{$name}.'_'.$name.
                   12843: 					   '.type'};
1.428     albertel 12844:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12845: 			     '.display'};
1.644     www      12846:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12847:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12848:       $$metacache{"$key.display"}=$olddis;
                   12849:     }
1.71      www      12850: }
                   12851: 
1.764     albertel 12852: # ------------------------------------------------------ Devalidate title cache
                   12853: 
                   12854: sub devalidate_title_cache {
                   12855:     my ($url)=@_;
                   12856:     if (!$env{'request.course.id'}) { return; }
                   12857:     my $symb=&symbread($url);
                   12858:     if (!$symb) { return; }
                   12859:     my $key=$env{'request.course.id'}."\0".$symb;
                   12860:     &devalidate_cache_new('title',$key);
                   12861: }
                   12862: 
1.1014    droeschl 12863: # ------------------------------------------------- Get the title of a course
                   12864: 
                   12865: sub current_course_title {
                   12866:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12867: }
1.301     www      12868: # ------------------------------------------------- Get the title of a resource
                   12869: 
                   12870: sub gettitle {
                   12871:     my $urlsymb=shift;
                   12872:     my $symb=&symbread($urlsymb);
1.534     albertel 12873:     if ($symb) {
1.620     albertel 12874: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12875: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12876: 	if (defined($cached)) { 
                   12877: 	    return $result;
                   12878: 	}
1.534     albertel 12879: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12880: 	my $title='';
1.907     albertel 12881: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12882: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12883: 	} else {
                   12884: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12885: 		    &GDBM_READER(),0640)) {
                   12886: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12887: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12888: 		untie(%bighash);
                   12889: 	    }
1.534     albertel 12890: 	}
                   12891: 	$title=~s/\&colon\;/\:/gs;
                   12892: 	if ($title) {
1.1159    www      12893: # Remember both $symb and $title for dynamic metadata
                   12894:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12895:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12896: # Cache this title and then return it
1.599     albertel 12897: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12898: 	}
                   12899: 	$urlsymb=$url;
                   12900:     }
                   12901:     my $title=&metadata($urlsymb,'title');
                   12902:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12903:     return $title;
1.301     www      12904: }
1.613     albertel 12905: 
1.614     albertel 12906: sub get_slot {
                   12907:     my ($which,$cnum,$cdom)=@_;
                   12908:     if (!$cnum || !$cdom) {
1.790     albertel 12909: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12910: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12911: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12912:     }
1.703     albertel 12913:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12914:     my %slotinfo;
                   12915:     if (exists($remembered{$key})) {
                   12916: 	$slotinfo{$which} = $remembered{$key};
                   12917:     } else {
                   12918: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12919: 	&Apache::lonhomework::showhash(%slotinfo);
                   12920: 	my ($tmp)=keys(%slotinfo);
                   12921: 	if ($tmp=~/^error:/) { return (); }
                   12922: 	$remembered{$key} = $slotinfo{$which};
                   12923:     }
1.616     albertel 12924:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12925: 	return %{$slotinfo{$which}};
                   12926:     }
                   12927:     return $slotinfo{$which};
1.614     albertel 12928: }
1.1150    raeburn  12929: 
                   12930: sub get_reservable_slots {
                   12931:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12932:     my $now = time;
                   12933:     my $reservable_info;
                   12934:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12935:     if (exists($remembered{$key})) {
                   12936:         $reservable_info = $remembered{$key};
                   12937:     } else {
                   12938:         my %resv;
                   12939:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12940:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12941:         $reservable_info = \%resv;
                   12942:         $remembered{$key} = $reservable_info;
                   12943:     }
                   12944:     return $reservable_info;
                   12945: }
                   12946: 
                   12947: sub get_course_slots {
                   12948:     my ($cnum,$cdom) = @_;
                   12949:     my $hashid=$cnum.':'.$cdom;
                   12950:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12951:     if (defined($cached)) {
                   12952:         if (ref($result) eq 'HASH') {
                   12953:             return %{$result};
                   12954:         }
                   12955:     } else {
                   12956:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12957:         my ($tmp) = keys(%slots);
                   12958:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  12959:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12960:             return %slots;
                   12961:         }
                   12962:     }
                   12963:     return;
                   12964: }
                   12965: 
                   12966: sub devalidate_slots_cache {
                   12967:     my ($cnum,$cdom)=@_;
                   12968:     my $hashid=$cnum.':'.$cdom;
                   12969:     &devalidate_cache_new('allslots',$hashid);
                   12970: }
                   12971: 
1.1172.2.8  raeburn  12972: sub get_coursechange {
                   12973:     my ($cdom,$cnum) = @_;
                   12974:     if ($cdom eq '' || $cnum eq '') {
                   12975:         return unless ($env{'request.course.id'});
                   12976:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12977:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12978:     }
                   12979:     my $hashid=$cdom.'_'.$cnum;
                   12980:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12981:     if ((defined($cached)) && ($change ne '')) {
                   12982:         return $change;
                   12983:     } else {
                   12984:         my %crshash;
                   12985:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12986:         if ($crshash{'internal.contentchange'} eq '') {
                   12987:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12988:             if ($change eq '') {
                   12989:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12990:                 $change = $crshash{'internal.created'};
                   12991:             }
                   12992:         } else {
                   12993:             $change = $crshash{'internal.contentchange'};
                   12994:         }
                   12995:         my $cachetime = 600;
                   12996:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12997:     }
                   12998:     return $change;
                   12999: }
                   13000: 
                   13001: sub devalidate_coursechange_cache {
1.1172.2.146.  .9(raebu 13002:23):     my ($cdom,$cnum)=@_;
                   13003:23):     my $hashid=$cdom.'_'.$cnum;
1.1172.2.8  raeburn  13004:     &devalidate_cache_new('crschange',$hashid);
                   13005: }
                   13006: 
1.1172.2.146.  .9(raebu 13007:23): sub get_suppchange {
                   13008:23):     my ($cdom,$cnum) = @_;
                   13009:23):     if ($cdom eq '' || $cnum eq '') {
                   13010:23):         return unless ($env{'request.course.id'});
                   13011:23):         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   13012:23):         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   13013:23):     }
                   13014:23):     my $hashid=$cdom.'_'.$cnum;
                   13015:23):     my ($change,$cached)=&is_cached_new('suppchange',$hashid);
                   13016:23):     if ((defined($cached)) && ($change ne '')) {
                   13017:23):         return $change;
                   13018:23):     } else {
                   13019:23):         my %crshash = &get('environment',['internal.supplementalchange'],$cdom,$cnum);
                   13020:23):         if ($crshash{'internal.supplementalchange'} eq '') {
                   13021:23):             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   13022:23):             if ($change eq '') {
                   13023:23):                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   13024:23):                 $change = $crshash{'internal.created'};
                   13025:23):             }
                   13026:23):         } else {
                   13027:23):             $change = $crshash{'internal.supplementalchange'};
                   13028:23):         }
                   13029:23):         my $cachetime = 600;
                   13030:23):         &do_cache_new('suppchange',$hashid,$change,$cachetime);
                   13031:23):     }
                   13032:23):     return $change;
                   13033:23): }
                   13034:23): 
                   13035:23): sub devalidate_suppchange_cache {
                   13036:23):     my ($cdom,$cnum)=@_;
                   13037:23):     my $hashid=$cdom.'_'.$cnum;
                   13038:23):     &devalidate_cache_new('suppchange',$hashid);
                   13039:23): }
                   13040:23): 
                   13041:23): sub update_supp_caches {
                   13042:23):     my ($cdom,$cnum) = @_;
                   13043:23):     my %servers = &internet_dom_servers($cdom);
                   13044:23):     my @ids=&current_machine_ids();
                   13045:23):     foreach my $server (keys(%servers)) {
                   13046:23):         next if (grep(/^\Q$server\E$/,@ids));
                   13047:23):         my $hashid=$cnum.':'.$cdom;
                   13048:23):         my $cachekey = &escape('showsupp').':'.&escape($hashid);
                   13049:23):         &remote_devalidate_cache($server,[$cachekey]);
                   13050:23):     }
                   13051:23):     &has_unhidden_suppfiles($cnum,$cdom,1,1);
                   13052:23):     &count_supptools($cnum,$cdom,1);
                   13053:23):     my $now = time;
                   13054:23):     if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   13055:23):         &Apache::lonnet::appenv({'request.course.suppupdated' => $now});
                   13056:23):     }
                   13057:23):     &put('environment',{'internal.supplementalchange' => $now},
                   13058:23):          $cdom,$cnum);
                   13059:23):     &Apache::lonnet::appenv(
                   13060:23):         {'course.'.$cdom.'_'.$cnum.'.internal.supplementalchange' => $now});
                   13061:23):     &do_cache_new('suppchange',$cdom.'_'.$cnum,$now,600);
                   13062:23): }
                   13063:23): 
1.31      www      13064: # ------------------------------------------------- Update symbolic store links
                   13065: 
                   13066: sub symblist {
                   13067:     my ($mapname,%newhash)=@_;
1.438     www      13068:     $mapname=&deversion(&declutter($mapname));
1.31      www      13069:     my %hash;
1.620     albertel 13070:     if (($env{'request.course.fn'}) && (%newhash)) {
                   13071:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 13072:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  13073: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 13074: 		next if ($url eq 'last_known'
                   13075: 			 && $env{'form.no_update_last_known'});
                   13076: 		$hash{declutter($url)}=&encode_symb($mapname,
                   13077: 						    $newhash{$url}->[1],
                   13078: 						    $newhash{$url}->[0]);
1.191     harris41 13079:             }
1.31      www      13080:             if (untie(%hash)) {
                   13081: 		return 'ok';
                   13082:             }
                   13083:         }
                   13084:     }
                   13085:     return 'error';
1.212     www      13086: }
                   13087: 
                   13088: # --------------------------------------------------------------- Verify a symb
                   13089: 
                   13090: sub symbverify {
1.1172.2.11  raeburn  13091:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      13092:     my $thisfn=$thisurl;
1.439     www      13093:     $thisfn=&declutter($thisfn);
1.215     www      13094: # direct jump to resource in page or to a sequence - will construct own symbs
                   13095:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   13096: # check URL part
1.409     www      13097:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      13098: 
1.431     www      13099:     unless ($url eq $thisfn) { return 0; }
1.213     www      13100: 
1.216     www      13101:     $symb=&symbclean($symb);
1.510     www      13102:     $thisurl=&deversion($thisurl);
1.439     www      13103:     $thisfn=&deversion($thisfn);
1.213     www      13104: 
                   13105:     my %bighash;
                   13106:     my $okay=0;
1.431     www      13107: 
1.620     albertel 13108:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13109:                             &GDBM_READER(),0640)) {
1.1032    raeburn  13110:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   13111:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  13112:             if ($map =~ m{^uploaded/.+\.page$}) {
                   13113:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   13114:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   13115:             }
                   13116:         }
                   13117:         my $ids;
1.1172.2.122  raeburn  13118:         if ($map =~ m{^uploaded/.+\.page$}) {
                   13119:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13  raeburn  13120:         } else {
                   13121:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  13122:         }
1.1102    raeburn  13123:         unless ($ids) {
1.1172.2.13  raeburn  13124:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  13125:             $ids=$bighash{$idkey};
1.216     www      13126:         }
                   13127:         if ($ids) {
                   13128: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  13129:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   13130:                 $symb =~ s/\?.+$//;
                   13131:             }
1.800     albertel 13132: 	    foreach my $id (split(/\,/,$ids)) {
                   13133: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      13134:                if (
                   13135:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  13136:    eq $symb) {
1.1172.2.11  raeburn  13137:                    if (ref($encstate)) {
                   13138:                        $$encstate = $bighash{'encrypted_'.$id};
                   13139:                    }
1.1172.2.13  raeburn  13140:                    if (($env{'request.role.adv'}) ||
                   13141:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  13142:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  13143:                        $okay=1;
                   13144:                        last;
                   13145:                    }
                   13146:                }
                   13147:            }
1.216     www      13148:         }
1.213     www      13149: 	untie(%bighash);
                   13150:     }
                   13151:     return $okay;
1.31      www      13152: }
                   13153: 
1.210     www      13154: # --------------------------------------------------------------- Clean-up symb
                   13155: 
                   13156: sub symbclean {
                   13157:     my $symb=shift;
1.568     albertel 13158:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      13159: # remove version from map
                   13160:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      13161: 
1.210     www      13162: # remove version from URL
                   13163:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      13164: 
1.507     www      13165: # remove wrapper
                   13166: 
1.510     www      13167:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 13168:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      13169:     return $symb;
1.409     www      13170: }
                   13171: 
                   13172: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 13173: 
                   13174: sub encode_symb {
                   13175:     my ($map,$resid,$url)=@_;
                   13176:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   13177: }
1.409     www      13178: 
                   13179: sub decode_symb {
1.568     albertel 13180:     my $symb=shift;
                   13181:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   13182:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      13183:     return (&fixversion($map),$resid,&fixversion($url));
                   13184: }
                   13185: 
                   13186: sub fixversion {
                   13187:     my $fn=shift;
1.609     banghart 13188:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      13189:     my %bighash;
                   13190:     my $uri=&clutter($fn);
1.620     albertel 13191:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      13192: # is this cached?
1.599     albertel 13193:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      13194:     if (defined($cached)) { return $result; }
                   13195: # unfortunately not cached, or expired
1.620     albertel 13196:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      13197: 	    &GDBM_READER(),0640)) {
                   13198:  	if ($bighash{'version_'.$uri}) {
                   13199:  	    my $version=$bighash{'version_'.$uri};
1.444     www      13200:  	    unless (($version eq 'mostrecent') || 
                   13201: 		    ($version==&getversion($uri))) {
1.440     www      13202:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   13203:  	    }
                   13204:  	}
                   13205:  	untie %bighash;
1.413     www      13206:     }
1.599     albertel 13207:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      13208: }
                   13209: 
                   13210: sub deversion {
                   13211:     my $url=shift;
                   13212:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   13213:     return $url;
1.210     www      13214: }
                   13215: 
1.31      www      13216: # ------------------------------------------------------ Return symb list entry
                   13217: 
                   13218: sub symbread {
1.1172.2.126  raeburn  13219:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128  raeburn  13220:         $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54  raeburn  13221:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128  raeburn  13222:     if (defined($env{$cache_str})) {
1.1172.2.126  raeburn  13223:         unless (ref($possibles) eq 'HASH') {
                   13224:             if ($ignorecachednull) {
                   13225:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   13226:             } else {
                   13227:                 return $env{$cache_str};
                   13228:             }
1.1172.2.66  raeburn  13229:         }
                   13230:     }
1.242     www      13231: # no filename provided? try from environment
1.1172.2.54  raeburn  13232:     unless ($thisfn) {
1.620     albertel 13233:         if ($env{'request.symb'}) {
1.1172.2.128  raeburn  13234:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13  raeburn  13235:         }
                   13236:         $thisfn=$env{'request.filename'};
1.44      www      13237:     }
1.569     albertel 13238:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      13239: # is that filename actually a symb? Verify, clean, and return
                   13240:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 13241: 	if (&symbverify($thisfn,$1)) {
1.1172.2.128  raeburn  13242: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 13243: 	}
1.242     www      13244:     }
1.44      www      13245:     $thisfn=declutter($thisfn);
1.31      www      13246:     my %hash;
1.37      www      13247:     my %bighash;
                   13248:     my $syval='';
1.620     albertel 13249:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.1172.2.128  raeburn  13250:         unless ($ignoresymbdb) {
1.1172.2.126  raeburn  13251:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   13252:                           &GDBM_READER(),0640)) {
1.1172.2.146.  .7(raebu 13253:22): 	        $syval=$hash{$thisfn};
1.1172.2.126  raeburn  13254:                 untie(%hash);
                   13255:             }
1.1172.2.128  raeburn  13256:             if ($syval && $checkforblock) {
                   13257:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126  raeburn  13258:                 if (@blockers) {
                   13259:                     $syval='';
                   13260:                 }
                   13261:             }
1.37      www      13262:         }
                   13263: # ---------------------------------------------------------- There was an entry
                   13264:         if ($syval) {
1.601     albertel 13265: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 13266: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  13267: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13268: 		    #return $env{$cache_str}='';
1.601     albertel 13269: 		#}    
                   13270: 		#$syval.=$1;
                   13271: 	    #}
1.37      www      13272:         } else {
                   13273: # ------------------------------------------------------- Was not in symb table
1.620     albertel 13274:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13275:                             &GDBM_READER(),0640)) {
1.37      www      13276: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      13277:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      13278:               unless ($ids) { 
                   13279:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      13280:               }
                   13281:               unless ($ids) {
                   13282: # alias?
                   13283: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      13284:               }
1.37      www      13285:               if ($ids) {
                   13286: # ------------------------------------------------------------------- Has ID(s)
                   13287:                  my @possibilities=split(/\,/,$ids);
1.39      www      13288:                  if ($#possibilities==0) {
                   13289: # ----------------------------------------------- There is only one possibility
1.37      www      13290: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 13291: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13292: 						    $resid,$thisfn);
1.1172.2.66  raeburn  13293:                      if (ref($possibles) eq 'HASH') {
1.1172.2.126  raeburn  13294:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   13295:                              $possibles->{$syval} = 1;
                   13296:                          }
1.1172.2.66  raeburn  13297:                      }
                   13298:                      if ($checkforblock) {
1.1172.2.126  raeburn  13299:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127  raeburn  13300:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126  raeburn  13301:                              if (@blockers) {
                   13302:                                  $syval = '';
                   13303:                                  untie(%bighash);
                   13304:                                  return $env{$cache_str}='';
                   13305:                              }
1.1172.2.66  raeburn  13306:                          }
                   13307:                      }
                   13308:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      13309: # ------------------------------------------ There is more than one possibility
                   13310:                      my $realpossible=0;
1.800     albertel 13311:                      foreach my $id (@possibilities) {
                   13312: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  13313:                          my $canaccess;
                   13314:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   13315:                              $canaccess = 1;
                   13316:                          } else {
                   13317:                              $canaccess = &allowed('bre',$file);
                   13318:                          }
                   13319:                          if ($canaccess) {
                   13320:          		     my ($mapid,$resid)=split(/\./,$id);
                   13321:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   13322:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13323:                                                              $resid,$thisfn);
1.1172.2.126  raeburn  13324:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127  raeburn  13325:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66  raeburn  13326:                                  if ($checkforblock) {
1.1172.2.127  raeburn  13327:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126  raeburn  13328:                                      if (@blockers > 0) {
                   13329:                                          $syval = '';
                   13330:                                      } else {
1.1172.2.66  raeburn  13331:                                          $syval = $poss_syval;
                   13332:                                          $realpossible++;
                   13333:                                      }
                   13334:                                  } else {
                   13335:                                      $syval = $poss_syval;
                   13336:                                      $realpossible++;
                   13337:                                  }
1.1172.2.126  raeburn  13338:                                  if ($syval) {
                   13339:                                      if (ref($possibles) eq 'HASH') {
                   13340:                                          $possibles->{$syval} = 1;
                   13341:                                      }
                   13342:                                  }
1.1172.2.66  raeburn  13343:                              }
1.39      www      13344: 			 }
1.191     harris41 13345:                      }
1.39      www      13346: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      13347:                  } else {
                   13348:                      $syval='';
1.37      www      13349:                  }
                   13350: 	      }
1.1172.2.66  raeburn  13351:               untie(%bighash);
1.481     raeburn  13352:            }
1.31      www      13353:         }
1.62      www      13354:         if ($syval) {
1.1172.2.128  raeburn  13355: 	    return $env{$cache_str}=$syval;
1.62      www      13356:         }
1.31      www      13357:     }
1.949     raeburn  13358:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13359:     return $env{$cache_str}='';
1.31      www      13360: }
                   13361: 
                   13362: # ---------------------------------------------------------- Return random seed
                   13363: 
1.32      www      13364: sub numval {
                   13365:     my $txt=shift;
                   13366:     $txt=~tr/A-J/0-9/;
                   13367:     $txt=~tr/a-j/0-9/;
                   13368:     $txt=~tr/K-T/0-9/;
                   13369:     $txt=~tr/k-t/0-9/;
                   13370:     $txt=~tr/U-Z/0-5/;
                   13371:     $txt=~tr/u-z/0-5/;
                   13372:     $txt=~s/\D//g;
1.564     albertel 13373:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      13374:     return int($txt);
1.368     albertel 13375: }
                   13376: 
1.484     albertel 13377: sub numval2 {
                   13378:     my $txt=shift;
                   13379:     $txt=~tr/A-J/0-9/;
                   13380:     $txt=~tr/a-j/0-9/;
                   13381:     $txt=~tr/K-T/0-9/;
                   13382:     $txt=~tr/k-t/0-9/;
                   13383:     $txt=~tr/U-Z/0-5/;
                   13384:     $txt=~tr/u-z/0-5/;
                   13385:     $txt=~s/\D//g;
                   13386:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13387:     my $total;
                   13388:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 13389:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 13390:     return int($total);
                   13391: }
                   13392: 
1.575     albertel 13393: sub numval3 {
                   13394:     use integer;
                   13395:     my $txt=shift;
                   13396:     $txt=~tr/A-J/0-9/;
                   13397:     $txt=~tr/a-j/0-9/;
                   13398:     $txt=~tr/K-T/0-9/;
                   13399:     $txt=~tr/k-t/0-9/;
                   13400:     $txt=~tr/U-Z/0-5/;
                   13401:     $txt=~tr/u-z/0-5/;
                   13402:     $txt=~s/\D//g;
                   13403:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13404:     my $total;
                   13405:     foreach my $val (@txts) { $total+=$val; }
                   13406:     if ($_64bit) { $total=(($total<<32)>>32); }
                   13407:     return $total;
                   13408: }
                   13409: 
1.675     albertel 13410: sub digest {
                   13411:     my ($data)=@_;
                   13412:     my $digest=&Digest::MD5::md5($data);
                   13413:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   13414:     my ($e,$f);
                   13415:     {
                   13416:         use integer;
                   13417:         $e=($a+$b);
                   13418:         $f=($c+$d);
                   13419:         if ($_64bit) {
                   13420:             $e=(($e<<32)>>32);
                   13421:             $f=(($f<<32)>>32);
                   13422:         }
                   13423:     }
                   13424:     if (wantarray) {
                   13425: 	return ($e,$f);
                   13426:     } else {
                   13427: 	my $g;
                   13428: 	{
                   13429: 	    use integer;
                   13430: 	    $g=($e+$f);
                   13431: 	    if ($_64bit) {
                   13432: 		$g=(($g<<32)>>32);
                   13433: 	    }
                   13434: 	}
                   13435: 	return $g;
                   13436:     }
                   13437: }
                   13438: 
1.368     albertel 13439: sub latest_rnd_algorithm_id {
1.675     albertel 13440:     return '64bit5';
1.366     albertel 13441: }
1.32      www      13442: 
1.503     albertel 13443: sub get_rand_alg {
                   13444:     my ($courseid)=@_;
1.790     albertel 13445:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 13446:     if ($courseid) {
1.620     albertel 13447: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 13448:     }
                   13449:     return &latest_rnd_algorithm_id();
                   13450: }
                   13451: 
1.562     albertel 13452: sub validCODE {
                   13453:     my ($CODE)=@_;
                   13454:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   13455:     return 0;
                   13456: }
                   13457: 
1.491     albertel 13458: sub getCODE {
1.620     albertel 13459:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 13460:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   13461: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   13462: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 13463: 	return $Apache::lonhomework::history{'resource.CODE'};
                   13464:     }
                   13465:     return undef;
                   13466: }
1.1133    foxr     13467: #
                   13468: #  Determines the random seed for a specific context:
                   13469: #
                   13470: # parameters:
                   13471: #   symb      - in course context the symb for the seed.
                   13472: #   course_id - The course id of the form domain_coursenum.
                   13473: #   domain    - Domain for the user.
                   13474: #   course    - Course for the user.
                   13475: #   cenv      - environment of the course.
                   13476: #
                   13477: # NOTE:
                   13478: #   All parameters are picked out of the environment if missing
                   13479: #   or not defined.
                   13480: #   If a symb cannot be determined the current time is used instead.
                   13481: #
                   13482: #  For a given well defined symb, courside, domain, username,
                   13483: #  and course environment, the seed is reproducible.
                   13484: #
1.31      www      13485: sub rndseed {
1.1133    foxr     13486:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 13487:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 13488:     if (!defined($symb)) {
1.366     albertel 13489: 	unless ($symb=$wsymb) { return time; }
                   13490:     }
1.1146    foxr     13491:     if (!defined $courseid) { 
                   13492: 	$courseid=$wcourseid; 
                   13493:     }
                   13494:     if (!defined $domain) { $domain=$wdomain; }
                   13495:     if (!defined $username) { $username=$wusername }
1.1133    foxr     13496: 
                   13497:     my $which;
                   13498:     if (defined($cenv->{'rndseed'})) {
                   13499: 	$which = $cenv->{'rndseed'};
                   13500:     } else {
                   13501: 	$which =&get_rand_alg($courseid);
                   13502:     }
1.491     albertel 13503:     if (defined(&getCODE())) {
1.675     albertel 13504: 	if ($which eq '64bit5') {
                   13505: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   13506: 	} elsif ($which eq '64bit4') {
1.575     albertel 13507: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   13508: 	} else {
                   13509: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   13510: 	}
1.675     albertel 13511:     } elsif ($which eq '64bit5') {
                   13512: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 13513:     } elsif ($which eq '64bit4') {
                   13514: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 13515:     } elsif ($which eq '64bit3') {
                   13516: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 13517:     } elsif ($which eq '64bit2') {
                   13518: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 13519:     } elsif ($which eq '64bit') {
                   13520: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   13521:     }
                   13522:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   13523: }
                   13524: 
                   13525: sub rndseed_32bit {
                   13526:     my ($symb,$courseid,$domain,$username)=@_;
                   13527:     {
                   13528: 	use integer;
                   13529: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   13530: 	my $symbseed=numval($symb) << 22;
                   13531: 	my $namechck=unpack("%32C*",$username) << 17;
                   13532: 	my $nameseed=numval($username) << 12;
                   13533: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   13534: 	my $courseseed=unpack("%32C*",$courseid);
                   13535: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 13536: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13537: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13538: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 13539: 	return $num;
                   13540:     }
                   13541: }
                   13542: 
                   13543: sub rndseed_64bit {
                   13544:     my ($symb,$courseid,$domain,$username)=@_;
                   13545:     {
                   13546: 	use integer;
                   13547: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   13548: 	my $symbseed=numval($symb) << 10;
                   13549: 	my $namechck=unpack("%32S*",$username);
                   13550: 	
                   13551: 	my $nameseed=numval($username) << 21;
                   13552: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   13553: 	my $courseseed=unpack("%32S*",$courseid);
                   13554: 	
                   13555: 	my $num1=$symbchck+$symbseed+$namechck;
                   13556: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13557: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13558: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13559: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 13560: 	return "$num1,$num2";
1.155     albertel 13561:     }
1.366     albertel 13562: }
                   13563: 
1.443     albertel 13564: sub rndseed_64bit2 {
                   13565:     my ($symb,$courseid,$domain,$username)=@_;
                   13566:     {
                   13567: 	use integer;
                   13568: 	# strings need to be an even # of cahracters long, it it is odd the
                   13569:         # last characters gets thrown away
                   13570: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13571: 	my $symbseed=numval($symb) << 10;
                   13572: 	my $namechck=unpack("%32S*",$username.' ');
                   13573: 	
                   13574: 	my $nameseed=numval($username) << 21;
1.501     albertel 13575: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13576: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13577: 	
                   13578: 	my $num1=$symbchck+$symbseed+$namechck;
                   13579: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13580: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13581: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13582: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13583: 	return "$num1,$num2";
                   13584:     }
                   13585: }
                   13586: 
                   13587: sub rndseed_64bit3 {
                   13588:     my ($symb,$courseid,$domain,$username)=@_;
                   13589:     {
                   13590: 	use integer;
                   13591: 	# strings need to be an even # of cahracters long, it it is odd the
                   13592:         # last characters gets thrown away
                   13593: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13594: 	my $symbseed=numval2($symb) << 10;
                   13595: 	my $namechck=unpack("%32S*",$username.' ');
                   13596: 	
                   13597: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13598: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13599: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13600: 	
                   13601: 	my $num1=$symbchck+$symbseed+$namechck;
                   13602: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13603: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13604: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13605: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13606: 	
1.503     albertel 13607: 	return "$num1:$num2";
1.443     albertel 13608:     }
                   13609: }
                   13610: 
1.575     albertel 13611: sub rndseed_64bit4 {
                   13612:     my ($symb,$courseid,$domain,$username)=@_;
                   13613:     {
                   13614: 	use integer;
                   13615: 	# strings need to be an even # of cahracters long, it it is odd the
                   13616:         # last characters gets thrown away
                   13617: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13618: 	my $symbseed=numval3($symb) << 10;
                   13619: 	my $namechck=unpack("%32S*",$username.' ');
                   13620: 	
                   13621: 	my $nameseed=numval3($username) << 21;
                   13622: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13623: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13624: 	
                   13625: 	my $num1=$symbchck+$symbseed+$namechck;
                   13626: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13627: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13628: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13629: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13630: 	
1.575     albertel 13631: 	return "$num1:$num2";
                   13632:     }
                   13633: }
                   13634: 
1.675     albertel 13635: sub rndseed_64bit5 {
                   13636:     my ($symb,$courseid,$domain,$username)=@_;
                   13637:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13638:     return "$num1:$num2";
                   13639: }
                   13640: 
1.366     albertel 13641: sub rndseed_CODE_64bit {
                   13642:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13643:     {
1.366     albertel 13644: 	use integer;
1.443     albertel 13645: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13646: 	my $symbseed=numval2($symb);
1.491     albertel 13647: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13648: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13649: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13650: 	my $num1=$symbseed+$CODEchck;
                   13651: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13652: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13653: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13654: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13655: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13656: 	return "$num1:$num2";
1.366     albertel 13657:     }
                   13658: }
                   13659: 
1.575     albertel 13660: sub rndseed_CODE_64bit4 {
                   13661:     my ($symb,$courseid,$domain,$username)=@_;
                   13662:     {
                   13663: 	use integer;
                   13664: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13665: 	my $symbseed=numval3($symb);
                   13666: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13667: 	my $CODEseed=numval3(&getCODE());
                   13668: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13669: 	my $num1=$symbseed+$CODEchck;
                   13670: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13671: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13672: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13673: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13674: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13675: 	return "$num1:$num2";
                   13676:     }
                   13677: }
                   13678: 
1.675     albertel 13679: sub rndseed_CODE_64bit5 {
                   13680:     my ($symb,$courseid,$domain,$username)=@_;
                   13681:     my $code = &getCODE();
                   13682:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13683:     return "$num1:$num2";
                   13684: }
                   13685: 
1.366     albertel 13686: sub setup_random_from_rndseed {
                   13687:     my ($rndseed)=@_;
1.503     albertel 13688:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  13689: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13690:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13691:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13692:         } else {
                   13693:             &Math::Random::random_set_seed($num1,$num2);
                   13694:         }
1.366     albertel 13695:     } else {
                   13696: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13697:     }
1.36      albertel 13698: }
                   13699: 
1.474     albertel 13700: sub latest_receipt_algorithm_id {
1.835     albertel 13701:     return 'receipt3';
1.474     albertel 13702: }
                   13703: 
1.480     www      13704: sub recunique {
                   13705:     my $fucourseid=shift;
                   13706:     my $unique;
1.835     albertel 13707:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13708: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13709: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13710:     } else {
                   13711: 	$unique=$perlvar{'lonReceipt'};
                   13712:     }
                   13713:     return unpack("%32C*",$unique);
                   13714: }
                   13715: 
                   13716: sub recprefix {
                   13717:     my $fucourseid=shift;
                   13718:     my $prefix;
1.835     albertel 13719:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13720: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13721: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13722:     } else {
                   13723: 	$prefix=$perlvar{'lonHostID'};
                   13724:     }
                   13725:     return unpack("%32C*",$prefix);
                   13726: }
                   13727: 
1.76      www      13728: sub ireceipt {
1.474     albertel 13729:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13730: 
                   13731:     my $return =&recprefix($fucourseid).'-';
                   13732: 
                   13733:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13734: 	$env{'request.state'} eq 'construct') {
                   13735: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13736: 	return $return;
                   13737:     }
                   13738: 
1.76      www      13739:     my $cuname=unpack("%32C*",$funame);
                   13740:     my $cudom=unpack("%32C*",$fudom);
                   13741:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13742:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13743:     my $cunique=&recunique($fucourseid);
1.474     albertel 13744:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13745:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13746: 
1.790     albertel 13747: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13748: 			       
                   13749: 	$return.= ($cunique%$cuname+
                   13750: 		   $cunique%$cudom+
                   13751: 		   $cusymb%$cuname+
                   13752: 		   $cusymb%$cudom+
                   13753: 		   $cucourseid%$cuname+
                   13754: 		   $cucourseid%$cudom+
                   13755: 		   $cpart%$cuname+
                   13756: 		   $cpart%$cudom);
                   13757:     } else {
                   13758: 	$return.= ($cunique%$cuname+
                   13759: 		   $cunique%$cudom+
                   13760: 		   $cusymb%$cuname+
                   13761: 		   $cusymb%$cudom+
                   13762: 		   $cucourseid%$cuname+
                   13763: 		   $cucourseid%$cudom);
                   13764:     }
                   13765:     return $return;
1.76      www      13766: }
                   13767: 
                   13768: sub receipt {
1.474     albertel 13769:     my ($part)=@_;
1.790     albertel 13770:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13771:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13772: }
1.260     ng       13773: 
1.790     albertel 13774: sub whichuser {
                   13775:     my ($passedsymb)=@_;
                   13776:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13777:     if (defined($env{'form.grade_symb'})) {
                   13778: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13779: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13780: 	if (!$allowed &&
                   13781: 	    exists($env{'request.course.sec'}) &&
                   13782: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13783: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13784: 			      '/'.$env{'request.course.sec'});
                   13785: 	}
                   13786: 	if ($allowed) {
                   13787: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13788: 	    $courseid=$tmp_courseid;
                   13789: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13790: 	    ($name)=&get_env_multiple('form.grade_username');
                   13791: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13792: 	}
                   13793:     }
                   13794:     if (!$passedsymb) {
                   13795: 	$symb=&symbread();
                   13796:     } else {
                   13797: 	$symb=$passedsymb;
                   13798:     }
                   13799:     $courseid=$env{'request.course.id'};
                   13800:     $domain=$env{'user.domain'};
                   13801:     $name=$env{'user.name'};
                   13802:     if ($name eq 'public' && $domain eq 'public') {
                   13803: 	if (!defined($env{'form.username'})) {
                   13804: 	    $env{'form.username'}.=time.rand(10000000);
                   13805: 	}
                   13806: 	$name.=$env{'form.username'};
                   13807:     }
                   13808:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13809: 
                   13810: }
                   13811: 
1.36      albertel 13812: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13813: # returns either the contents of the file or 
                   13814: # -1 if the file doesn't exist
1.481     raeburn  13815: #
                   13816: # if the target is a file that was uploaded via DOCS, 
                   13817: # a check will be made to see if a current copy exists on the local server,
                   13818: # if it does this will be served, otherwise a copy will be retrieved from
                   13819: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13820: # the local server.   
1.472     albertel 13821: 
1.36      albertel 13822: sub getfile {
1.538     albertel 13823:     my ($file) = @_;
1.609     banghart 13824:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13825:     &repcopy($file);
                   13826:     return &readfile($file);
                   13827: }
                   13828: 
                   13829: sub repcopy_userfile {
                   13830:     my ($file)=@_;
1.1142    raeburn  13831:     my $londocroot = $perlvar{'lonDocRoot'};
                   13832:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13833:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13834:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13835: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13836:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13837:     if (-e "$file") {
1.828     www      13838: # we already have a local copy, check it out
1.538     albertel 13839: 	my @fileinfo = stat($file);
1.828     www      13840: 	my $rtncode;
                   13841: 	my $info;
1.538     albertel 13842: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13843: 	if ($lwpresp ne 'ok') {
1.828     www      13844: # there is no such file anymore, even though we had a local copy
1.482     albertel 13845: 	    if ($rtncode eq '404') {
1.538     albertel 13846: 		unlink($file);
1.482     albertel 13847: 	    }
                   13848: 	    return -1;
                   13849: 	}
                   13850: 	if ($info < $fileinfo[9]) {
1.828     www      13851: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13852: 	    return 'ok';
1.828     www      13853: 	} else {
                   13854: # the file is outdated, get rid of it
                   13855: 	    unlink($file);
1.482     albertel 13856: 	}
1.828     www      13857:     }
                   13858: # one way or the other, at this point, we don't have the file
                   13859: # construct the correct path for the file
                   13860:     my @parts = ($cdom,$cnum); 
                   13861:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13862: 	push @parts, split(/\//,$1);
                   13863:     }
                   13864:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13865:     foreach my $part (@parts) {
                   13866: 	$path .= '/'.$part;
                   13867: 	if (!-e $path) {
                   13868: 	    mkdir($path,0770);
1.482     albertel 13869: 	}
                   13870:     }
1.828     www      13871: # now the path exists for sure
                   13872: # get a user agent
                   13873:     my $ua=new LWP::UserAgent;
                   13874:     my $transferfile=$file.'.in.transfer';
                   13875: # FIXME: this should flock
                   13876:     if (-e $transferfile) { return 'ok'; }
                   13877:     my $request;
                   13878:     $uri=~s/^\///;
1.980     raeburn  13879:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13880:     my $hostname = &hostname($homeserver);
1.980     raeburn  13881:     my $protocol = $protocol{$homeserver};
                   13882:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13883:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      13884:     my $response=$ua->request($request,$transferfile);
                   13885: # did it work?
                   13886:     if ($response->is_error()) {
                   13887: 	unlink($transferfile);
                   13888: 	&logthis("Userfile repcopy failed for $uri");
                   13889: 	return -1;
                   13890:     }
                   13891: # worked, rename the transfer file
                   13892:     rename($transferfile,$file);
1.607     raeburn  13893:     return 'ok';
1.481     raeburn  13894: }
                   13895: 
1.517     albertel 13896: sub tokenwrapper {
                   13897:     my $uri=shift;
1.980     raeburn  13898:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13899:     $uri=~s|^/||;
1.620     albertel 13900:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13901:     my $token=$1;
1.552     albertel 13902:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13903:     if ($udom && $uname && $file) {
                   13904: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13905:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13906:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.120  raeburn  13907:         my $hostname = &hostname($homeserver);
1.980     raeburn  13908:         my $protocol = $protocol{$homeserver};
                   13909:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13910:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 13911:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13912:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13913:     } else {
                   13914:         return '/adm/notfound.html';
                   13915:     }
                   13916: }
                   13917: 
1.828     www      13918: # call with reqtype HEAD: get last modification time
                   13919: # call with reqtype GET: get the file contents
                   13920: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13921: #
1.481     raeburn  13922: sub getuploaded {
                   13923:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13924:     $uri=~s/^\///;
1.980     raeburn  13925:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  13926:     my $hostname = &hostname($homeserver);
1.980     raeburn  13927:     my $protocol = $protocol{$homeserver};
                   13928:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  13929:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  13930:     my $ua=new LWP::UserAgent;
                   13931:     my $request=new HTTP::Request($reqtype,$uri);
                   13932:     my $response=$ua->request($request);
                   13933:     $$rtncode = $response->code;
1.482     albertel 13934:     if (! $response->is_success()) {
                   13935: 	return 'failed';
                   13936:     }      
                   13937:     if ($reqtype eq 'HEAD') {
1.486     www      13938: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13939:     } elsif ($reqtype eq 'GET') {
                   13940: 	$$info = $response->content;
1.472     albertel 13941:     }
1.482     albertel 13942:     return 'ok';
1.36      albertel 13943: }
                   13944: 
1.481     raeburn  13945: sub readfile {
                   13946:     my $file = shift;
                   13947:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13948:     my $fh;
1.1172.2.96  raeburn  13949:     open($fh,"<",$file);
1.481     raeburn  13950:     my $a='';
1.800     albertel 13951:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13952:     return $a;
                   13953: }
                   13954: 
1.36      albertel 13955: sub filelocation {
1.590     banghart 13956:     my ($dir,$file) = @_;
                   13957:     my $location;
                   13958:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13959: 
                   13960:     if ($file =~ m-^/adm/-) {
                   13961: 	$file=~s-^/adm/wrapper/-/-;
                   13962: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13963:     }
1.882     albertel 13964: 
1.1139    www      13965:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13966:         $location = $file;
1.609     banghart 13967:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13968:         my ($udom,$uname,$filename)=
1.811     albertel 13969:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13970:         my $home=&homeserver($uname,$udom);
                   13971:         my $is_me=0;
                   13972:         my @ids=&current_machine_ids();
                   13973:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13974:         if ($is_me) {
1.1117    foxr     13975:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13976:         } else {
                   13977:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13978:   	      $udom.'/'.$uname.'/'.$filename;
                   13979:         }
1.882     albertel 13980:     } elsif ($file =~ m-^/adm/-) {
                   13981: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13982:     } else {
                   13983:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13984:         $file=~s:^/(res|priv)/:/:;
                   13985:         my $space=$1;
1.590     banghart 13986:         if ( !( $file =~ m:^/:) ) {
                   13987:             $location = $dir. '/'.$file;
                   13988:         } else {
1.1142    raeburn  13989:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13990:         }
1.59      albertel 13991:     }
1.590     banghart 13992:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13993:     while ($location=~m{/\.\./}) {
                   13994: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13995: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13996: 	} else {
                   13997: 	    $location=~ s{/\.\./}{/}g;
                   13998: 	}
                   13999:     } #remove dir/..
1.590     banghart 14000:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   14001:     return $location;
1.46      www      14002: }
1.36      albertel 14003: 
1.46      www      14004: sub hreflocation {
                   14005:     my ($dir,$file)=@_;
1.980     raeburn  14006:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 14007: 	$file=filelocation($dir,$file);
1.700     albertel 14008:     } elsif ($file=~m-^/adm/-) {
                   14009: 	$file=~s-^/adm/wrapper/-/-;
                   14010: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 14011:     }
                   14012:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   14013: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   14014:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  14015: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   14016: 	        {/uploaded/$1/$2/}x;
1.46      www      14017:     }
1.913     albertel 14018:     if ($file=~ m{^/userfiles/}) {
                   14019: 	$file =~ s{^/userfiles/}{/uploaded/};
                   14020:     }
1.462     albertel 14021:     return $file;
1.465     albertel 14022: }
                   14023: 
1.1139    www      14024: 
                   14025: 
                   14026: 
                   14027: 
1.465     albertel 14028: sub current_machine_domains {
1.853     albertel 14029:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   14030: }
                   14031: 
                   14032: sub machine_domains {
                   14033:     my ($hostname) = @_;
1.465     albertel 14034:     my @domains;
1.838     albertel 14035:     my %hostname = &all_hostnames();
1.465     albertel 14036:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  14037: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 14038: 	if ($hostname eq $name) {
1.844     albertel 14039: 	    push(@domains,&host_domain($id));
1.465     albertel 14040: 	}
                   14041:     }
                   14042:     return @domains;
                   14043: }
                   14044: 
                   14045: sub current_machine_ids {
1.853     albertel 14046:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   14047: }
                   14048: 
                   14049: sub machine_ids {
                   14050:     my ($hostname) = @_;
                   14051:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 14052:     my @ids;
1.888     albertel 14053:     my %name_to_host = &all_names();
1.889     albertel 14054:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   14055: 	return @{ $name_to_host{$hostname} };
                   14056:     }
                   14057:     return;
1.31      www      14058: }
                   14059: 
1.824     raeburn  14060: sub additional_machine_domains {
                   14061:     my @domains;
1.1172.2.142  raeburn  14062:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
                   14063:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
                   14064:             while( my $line = <$fh>) {
                   14065:                 chomp($line);
                   14066:                 $line =~ s/\s//g;
                   14067:                 push(@domains,$line);
                   14068:             }
                   14069:             close($fh);
                   14070:         }
1.824     raeburn  14071:     }
                   14072:     return @domains;
                   14073: }
                   14074: 
                   14075: sub default_login_domain {
                   14076:     my $domain = $perlvar{'lonDefDomain'};
                   14077:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   14078:     foreach my $posdom (&current_machine_domains(),
                   14079:                         &additional_machine_domains()) {
                   14080:         if (lc($posdom) eq lc($testdomain)) {
                   14081:             $domain=$posdom;
                   14082:             last;
                   14083:         }
                   14084:     }
                   14085:     return $domain;
                   14086: }
                   14087: 
1.1172.2.106  raeburn  14088: sub shared_institution {
1.1172.2.136  raeburn  14089:     my ($dom,$lonhost) = @_;
                   14090:     if ($lonhost eq '') {
                   14091:         $lonhost = $perlvar{'lonHostID'};
                   14092:     }
1.1172.2.106  raeburn  14093:     my $same_intdom;
1.1172.2.136  raeburn  14094:     my $hostintdom = &internet_dom($lonhost);
1.1172.2.106  raeburn  14095:     if ($hostintdom ne '') {
                   14096:         my %iphost = &get_iphost();
                   14097:         my $primary_id = &domain($dom,'primary');
                   14098:         my $primary_ip = &get_host_ip($primary_id);
                   14099:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   14100:             foreach my $id (@{$iphost{$primary_ip}}) {
                   14101:                 my $intdom = &internet_dom($id);
                   14102:                 if ($intdom eq $hostintdom) {
                   14103:                     $same_intdom = 1;
                   14104:                     last;
                   14105:                 }
                   14106:             }
                   14107:         }
                   14108:     }
                   14109:     return $same_intdom;
                   14110: }
                   14111: 
1.1172.2.120  raeburn  14112: sub uses_sts {
                   14113:     my ($ignore_cache) = @_;
                   14114:     my $lonhost = $perlvar{'lonHostID'};
                   14115:     my $hostname = &hostname($lonhost);
                   14116:     my $sts_on;
                   14117:     if ($protocol{$lonhost} eq 'https') {
                   14118:         my $cachetime = 12*3600;
                   14119:         if (!$ignore_cache) {
                   14120:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   14121:             if (defined($cached)) {
                   14122:                 return $sts_on;
                   14123:             }
                   14124:         }
1.1172.2.121  raeburn  14125:         my $ua=new LWP::UserAgent;
1.1172.2.120  raeburn  14126:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   14127:         my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121  raeburn  14128:         my $response=$ua->request($request);
1.1172.2.120  raeburn  14129:         if ($response->is_success) {
                   14130:             my $has_sts = $response->header('Strict-Transport-Security');
                   14131:             if ($has_sts eq '') {
                   14132:                 $sts_on = 0;
                   14133:             } else {
                   14134:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   14135:                     my $maxage = $1;
                   14136:                     if ($maxage) {
                   14137:                         $sts_on = 1;
                   14138:                     } else {
                   14139:                         $sts_on = 0;
                   14140:                     }
                   14141:                 } else {
                   14142:                     $sts_on = 0;
                   14143:                 }
                   14144:             }
                   14145:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   14146:         }
                   14147:     }
                   14148:     return;
                   14149: }
                   14150: 
1.1172.2.142  raeburn  14151: sub waf_allssl {
                   14152:     my ($host_name) = @_;
                   14153:     my $alias = &get_proxy_alias();
                   14154:     if ($host_name eq '') {
                   14155:         $host_name = $ENV{'SERVER_NAME'};
                   14156:     }
                   14157:     if (($host_name ne '') && ($alias eq $host_name)) {
                   14158:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
                   14159:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   14160:         if ($defdomdefaults{'waf_sslopt'}) {
                   14161:             return $defdomdefaults{'waf_sslopt'};
                   14162:         }
                   14163:     }
                   14164:     return;
                   14165: }
                   14166: 
1.1172.2.134  raeburn  14167: sub get_requestor_ip {
                   14168:     my ($r,$nolookup,$noproxy) = @_;
                   14169:     my $from_ip;
                   14170:     if (ref($r)) {
1.1172.2.142  raeburn  14171:         if ($r->can('useragent_ip')) {
                   14172:             if ($noproxy && $r->can('client_ip')) {
                   14173:                 $from_ip = $r->client_ip();
                   14174:             } else {
                   14175:                 $from_ip = $r->useragent_ip();
                   14176:             }
                   14177:         } elsif ($r->connection->can('remote_ip')) {
                   14178:             $from_ip = $r->connection->remote_ip();
                   14179:         } else {
                   14180:             $from_ip = $r->get_remote_host($nolookup);
                   14181:         }
1.1172.2.134  raeburn  14182:     } else {
                   14183:         $from_ip = $ENV{'REMOTE_ADDR'};
                   14184:     }
1.1172.2.142  raeburn  14185:     return $from_ip if ($noproxy);
                   14186:    # Who controls proxy settings for server
                   14187:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14188:     my $proxyinfo = &get_proxy_settings($dom_in_use);
                   14189:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
                   14190:         if ($proxyinfo->{'vpnint'}) {
                   14191:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
                   14192:                 return $from_ip;
                   14193:             }
                   14194:         }
                   14195:         if ($proxyinfo->{'trusted'}) {
                   14196:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
                   14197:                 my $ipheader = $proxyinfo->{'ipheader'};
                   14198:                 my ($ip,$xfor);
                   14199:                 if (ref($r)) {
                   14200:                     if ($ipheader) {
                   14201:                         $ip = $r->headers_in->{$ipheader};
                   14202:                     }
                   14203:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
                   14204:                 } else {
                   14205:                     if ($ipheader) {
                   14206:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
                   14207:                     }
                   14208:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
                   14209:                 }
                   14210:                 if (($ip eq '') && ($xfor ne '')) {
                   14211:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
                   14212:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
                   14213:                             $ip = $poss_ip;
                   14214:                             last;
                   14215:                         }
                   14216:                     }
                   14217:                 }
                   14218:                 if ($ip ne '') {
                   14219:                     return $ip;
                   14220:                 }
                   14221:             }
                   14222:         }
                   14223:     }
1.1172.2.134  raeburn  14224:     return $from_ip;
                   14225: }
                   14226: 
1.1172.2.142  raeburn  14227: sub get_proxy_settings {
                   14228:     my ($dom_in_use) = @_;
                   14229:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   14230:     my $proxyinfo = {
                   14231:                        ipheader => $domdefaults{'waf_ipheader'},
                   14232:                        trusted  => $domdefaults{'waf_trusted'},
                   14233:                        vpnint   => $domdefaults{'waf_vpnint'},
                   14234:                        vpnext   => $domdefaults{'waf_vpnext'},
                   14235:                        sslopt   => $domdefaults{'waf_sslopt'},
                   14236:                     };
                   14237:     return $proxyinfo;
                   14238: }
                   14239: 
                   14240: sub ip_match {
                   14241:     my ($ip,$pattern_str) = @_;
                   14242:     $ip=Net::CIDR::cidrvalidate($ip);
                   14243:     if ($ip) {
                   14244:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
                   14245:     }
                   14246:     return;
                   14247: }
                   14248: 
                   14249: sub get_proxy_alias {
                   14250:     my ($lonid) = @_;
                   14251:     if ($lonid eq '') {
                   14252:         $lonid = $perlvar{'lonHostID'};
                   14253:     }
                   14254:     if (!defined(&hostname($lonid))) {
                   14255:         return;
                   14256:     }
                   14257:     if ($lonid ne '') {
                   14258:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
                   14259:         if ($cached) {
                   14260:             return $alias;
                   14261:         }
                   14262:         my $dom = &Apache::lonnet::host_domain($lonid);
                   14263:         if ($dom ne '') {
                   14264:             my $cachetime = 60*60*24;
                   14265:             my %domconfig =
                   14266:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14267:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14268:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
                   14269:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
                   14270:                 }
                   14271:             }
                   14272:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
                   14273:         }
                   14274:     }
                   14275:     return;
                   14276: }
                   14277: 
                   14278: sub use_proxy_alias {
                   14279:     my ($r,$lonid) = @_;
                   14280:     my $alias = &get_proxy_alias($lonid);
                   14281:     if ($alias) {
                   14282:         my $dom = &host_domain($lonid);
                   14283:         if ($dom ne '') {
                   14284:             my $proxyinfo = &get_proxy_settings($dom);
                   14285:             my ($vpnint,$remote_ip);
                   14286:             if (ref($proxyinfo) eq 'HASH') {
                   14287:                 $vpnint = $proxyinfo->{'vpnint'};
                   14288:                 if ($vpnint) {
                   14289:                     $remote_ip = &get_requestor_ip($r,1,1);
                   14290:                 }
                   14291:             }
                   14292:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
                   14293:                 return $alias;
                   14294:             }
                   14295:         }
                   14296:     }
                   14297:     return;
                   14298: }
                   14299: 
                   14300: sub alias_sso {
                   14301:     my ($lonid) = @_;
                   14302:     if ($lonid eq '') {
                   14303:         $lonid = $perlvar{'lonHostID'};
                   14304:     }
                   14305:     if (!defined(&hostname($lonid))) {
                   14306:         return;
                   14307:     }
                   14308:     if ($lonid ne '') {
                   14309:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
                   14310:         if ($cached) {
                   14311:             return $use_alias;
                   14312:         }
                   14313:         my $dom = &Apache::lonnet::host_domain($lonid);
                   14314:         if ($dom ne '') {
                   14315:             my $cachetime = 60*60*24;
                   14316:             my %domconfig =
                   14317:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14318:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14319:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
                   14320:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
                   14321:                 }
                   14322:             }
                   14323:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
                   14324:         }
                   14325:     }
                   14326:     return;
                   14327: }
                   14328: 
                   14329: sub get_saml_landing {
                   14330:     my ($lonid) = @_;
                   14331:     if ($lonid eq '') {
                   14332:         my $defdom = &default_login_domain();
                   14333:         my @hosts = &current_machine_ids();
                   14334:         if (@hosts > 1) {
                   14335:             foreach my $hostid (@hosts) {
                   14336:                 if (&host_domain($hostid) eq $defdom) {
                   14337:                     $lonid = $hostid;
                   14338:                     last;
                   14339:                 }
                   14340:             }
                   14341:         } else {
                   14342:             $lonid = $perlvar{'lonHostID'};
                   14343:         }
                   14344:         if ($lonid) {
                   14345:             unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
                   14346:                 return;
                   14347:             }
                   14348:         } else {
                   14349:             return;
                   14350:         }
                   14351:     } elsif (!defined(&hostname($lonid))) {
                   14352:         return;
                   14353:     }
                   14354:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
                   14355:     if ($cached) {
                   14356:         return $landing;
                   14357:     }
                   14358:     my $dom = &Apache::lonnet::host_domain($lonid);
                   14359:     if ($dom ne '') {
                   14360:         my $cachetime = 60*60*24;
                   14361:         my %domconfig =
                   14362:             &Apache::lonnet::get_dom('configuration',['login'],$dom);
                   14363:         if (ref($domconfig{'login'}) eq 'HASH') {
                   14364:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
                   14365:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
                   14366:                     $landing = 1;
                   14367:                 }
                   14368:             }
                   14369:         }
                   14370:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
                   14371:     }
                   14372:     return;
                   14373: }
                   14374: 
1.31      www      14375: # ------------------------------------------------------------- Declutters URLs
                   14376: 
                   14377: sub declutter {
                   14378:     my $thisfn=shift;
1.569     albertel 14379:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  14380:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   14381:         $thisfn=~s{^/home/httpd/html}{};
                   14382:     }
1.31      www      14383:     $thisfn=~s/^\///;
1.697     albertel 14384:     $thisfn=~s|^adm/wrapper/||;
                   14385:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      14386:     $thisfn=~s/^res\///;
1.1172    bisitz   14387:     $thisfn=~s/^priv\///;
1.1032    raeburn  14388:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   14389:         $thisfn=~s/\?.+$//;
                   14390:     }
1.268     www      14391:     return $thisfn;
                   14392: }
                   14393: 
                   14394: # ------------------------------------------------------------- Clutter up URLs
                   14395: 
                   14396: sub clutter {
                   14397:     my $thisfn='/'.&declutter(shift);
1.887     albertel 14398:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 14399: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      14400:        $thisfn='/res'.$thisfn; 
                   14401:     }
1.1031    raeburn  14402:     if ($thisfn !~m|^/adm|) {
                   14403: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 14404: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 14405: 	} else {
                   14406: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   14407: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 14408: 	    if ($embstyle eq 'ssi'
                   14409: 		|| ($embstyle eq 'hdn')
                   14410: 		|| ($embstyle eq 'rat')
                   14411: 		|| ($embstyle eq 'prv')
                   14412: 		|| ($embstyle eq 'ign')) {
                   14413: 		#do nothing with these
                   14414: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 14415: 		|| ($embstyle eq 'emb')
                   14416: 		|| ($embstyle eq 'wrp')) {
                   14417: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 14418: 	    } elsif ($embstyle eq 'unk'
                   14419: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 14420: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 14421: 	    } else {
1.718     www      14422: #		&logthis("Got a blank emb style");
1.695     albertel 14423: 	    }
1.694     albertel 14424: 	}
1.1172.2.146.  .1(raebu 14425:22):     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
                   14426:22):         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 14427:     }
1.31      www      14428:     return $thisfn;
1.12      www      14429: }
                   14430: 
1.787     albertel 14431: sub clutter_with_no_wrapper {
                   14432:     my $uri = &clutter(shift);
                   14433:     if ($uri =~ m-^/adm/-) {
                   14434: 	$uri =~ s-^/adm/wrapper/-/-;
                   14435: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   14436:     }
                   14437:     return $uri;
                   14438: }
                   14439: 
1.557     albertel 14440: sub freeze_escape {
                   14441:     my ($value)=@_;
                   14442:     if (ref($value)) {
                   14443: 	$value=&nfreeze($value);
                   14444: 	return '__FROZEN__'.&escape($value);
                   14445:     }
                   14446:     return &escape($value);
                   14447: }
                   14448: 
1.11      www      14449: 
1.557     albertel 14450: sub thaw_unescape {
                   14451:     my ($value)=@_;
                   14452:     if ($value =~ /^__FROZEN__/) {
                   14453: 	substr($value,0,10,undef);
                   14454: 	$value=&unescape($value);
                   14455: 	return &thaw($value);
                   14456:     }
                   14457:     return &unescape($value);
                   14458: }
                   14459: 
1.436     albertel 14460: sub correct_line_ends {
                   14461:     my ($result)=@_;
                   14462:     $$result =~s/\r\n/\n/mg;
                   14463:     $$result =~s/\r/\n/mg;
1.415     albertel 14464: }
1.1       albertel 14465: # ================================================================ Main Program
                   14466: 
1.184     www      14467: sub goodbye {
1.204     albertel 14468:    &logthis("Starting Shut down");
1.443     albertel 14469: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 14470:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 14471: #converted
1.599     albertel 14472: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 14473:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   14474: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   14475: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 14476: #1.1 only
1.870     albertel 14477: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   14478: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   14479: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   14480: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   14481:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 14482:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   14483:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      14484:    &flushcourselogs();
                   14485:    &logthis("Shutting down");
                   14486: }
                   14487: 
1.852     albertel 14488: sub get_dns {
1.1172.2.17  raeburn  14489:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 14490:     if (!$ignore_cache) {
                   14491: 	my ($content,$cached)=
                   14492: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   14493: 	if ($cached) {
1.1172.2.17  raeburn  14494: 	    &$func($content,$hashref);
1.869     albertel 14495: 	    return;
                   14496: 	}
                   14497:     }
                   14498: 
                   14499:     my %alldns;
1.1172.2.96  raeburn  14500:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   14501:         foreach my $dns (<$config>) {
                   14502: 	    next if ($dns !~ /^\^(\S*)/x);
                   14503:             my $line = $1;
                   14504:             my ($host,$protocol) = split(/:/,$line);
                   14505:             if ($protocol ne 'https') {
                   14506:                 $protocol = 'http';
                   14507:             }
                   14508: 	    $alldns{$host} = $protocol;
1.979     raeburn  14509:         }
1.1172.2.96  raeburn  14510:         close($config);
1.869     albertel 14511:     }
                   14512:     while (%alldns) {
1.1172.2.52  raeburn  14513: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1172.2.142  raeburn  14514:         my @content;
                   14515:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
                   14516:             my $command = (split('/',$url))[3];
                   14517:             my ($dir,$file) = &parse_getdns_url($command,$url);
                   14518:             delete($alldns{$dns});
                   14519:             next if (($dir eq '') || ($file eq ''));
                   14520:             if (open(my $config,'<',"$dir/$file")) {
                   14521:                 @content = <$config>;
                   14522:                 close($config);
                   14523:             }
                   14524:         } else {
                   14525: 	    my $ua=new LWP::UserAgent;
                   14526:             $ua->timeout(30);
                   14527: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
                   14528: 	    my $response=$ua->request($request);
                   14529:             delete($alldns{$dns});
                   14530: 	    next if ($response->is_error());
                   14531: 	    @content = split("\n",$response->content);
                   14532:         }
1.1172.2.17  raeburn  14533:         unless ($nocache) {
1.1172.2.23  raeburn  14534: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  14535:         }
                   14536: 	&$func(\@content,$hashref);
1.869     albertel 14537: 	return;
1.852     albertel 14538:     }
1.871     albertel 14539:     my $which = (split('/',$url))[3];
                   14540:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  14541:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   14542:         my @content = <$config>;
                   14543:         &$func(\@content,$hashref);
                   14544:     }
1.1172.2.17  raeburn  14545:     return;
                   14546: }
                   14547: 
                   14548: # ------------------------------------------------------Get DNS checksums file
                   14549: sub parse_dns_checksums_tab {
                   14550:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  14551:     my $lonhost = $perlvar{'lonHostID'};
                   14552:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  14553:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  14554:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   14555:     my $webconfdir = '/etc/httpd/conf';
                   14556:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   14557:         $webconfdir = '/etc/apache2';
                   14558:     } elsif ($distro =~ /^sles(\d+)$/) {
                   14559:         if ($1 >= 10) {
                   14560:             $webconfdir = '/etc/apache2';
                   14561:         }
                   14562:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   14563:         if ($1 >= 10.0) {
                   14564:             $webconfdir = '/etc/apache2';
                   14565:         }
                   14566:     }
1.1172.2.17  raeburn  14567:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14568:     my (%chksum,%revnum);
                   14569:     if (ref($lines) eq 'ARRAY') {
                   14570:         chomp(@{$lines});
1.1172.2.34  raeburn  14571:         my $version = shift(@{$lines});
                   14572:         if ($version eq $release) {
1.1172.2.17  raeburn  14573:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  14574:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  14575:                 if ($file =~ m{^/etc/httpd/conf}) {
                   14576:                     if ($webconfdir eq '/etc/apache2') {
                   14577:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   14578:                     }
                   14579:                 }
1.1172.2.34  raeburn  14580:                 $chksum{$file} = $shasum;
                   14581:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  14582:             }
                   14583:             if (ref($hashref) eq 'HASH') {
                   14584:                 %{$hashref} = (
                   14585:                                 sums     => \%chksum,
                   14586:                                 versions => \%revnum,
                   14587:                               );
                   14588:             }
                   14589:         }
                   14590:     }
1.869     albertel 14591:     return;
1.852     albertel 14592: }
1.1172.2.17  raeburn  14593: 
                   14594: sub fetch_dns_checksums {
                   14595:     my %checksums;
1.1172.2.34  raeburn  14596:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  14597:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  14598:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14599:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  14600:              \%checksums);
                   14601:     return \%checksums;
                   14602: }
                   14603: 
1.1172.2.142  raeburn  14604: sub parse_getdns_url {
                   14605:     my ($command,$url) = @_;
                   14606:     my $dir = $perlvar{'lonTabDir'};
                   14607:     my $file;
                   14608:     if ($command eq 'hosts') {
                   14609:         $file = 'dns_hosts.tab';
                   14610:     } elsif ($command eq 'domain') {
                   14611:         $file = 'dns_domain.tab';
                   14612:     } elsif ($command eq 'checksums') {
                   14613:         my $version = (split('/',$url))[4];
                   14614:         $file = "dns_checksums/$version.tab",
                   14615:     }
                   14616:     return ($dir,$file);
                   14617: }
                   14618: 
1.327     albertel 14619: # ------------------------------------------------------------ Read domain file
                   14620: {
1.852     albertel 14621:     my $loaded;
1.846     albertel 14622:     my %domain;
                   14623: 
1.852     albertel 14624:     sub parse_domain_tab {
                   14625: 	my ($lines) = @_;
                   14626: 	foreach my $line (@$lines) {
                   14627: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      14628: 
1.846     albertel 14629: 	    chomp($line);
1.852     albertel 14630: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 14631: 	    my %this_domain;
                   14632: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   14633: 			       'lang_def', 'city', 'longi', 'lati',
                   14634: 			       'primary') {
                   14635: 		$this_domain{$field} = shift(@elements);
                   14636: 	    }
                   14637: 	    $domain{$name} = \%this_domain;
1.852     albertel 14638: 	}
                   14639:     }
1.864     albertel 14640: 
                   14641:     sub reset_domain_info {
                   14642: 	undef($loaded);
                   14643: 	undef(%domain);
                   14644:     }
                   14645: 
1.852     albertel 14646:     sub load_domain_tab {
1.1172.2.70  raeburn  14647: 	my ($ignore_cache,$nocache) = @_;
                   14648: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 14649: 	my $fh;
1.1172.2.96  raeburn  14650: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 14651: 	    my @lines = <$fh>;
                   14652: 	    &parse_domain_tab(\@lines);
1.448     albertel 14653: 	}
1.852     albertel 14654: 	close($fh);
                   14655: 	$loaded = 1;
1.327     albertel 14656:     }
1.846     albertel 14657: 
                   14658:     sub domain {
1.852     albertel 14659: 	&load_domain_tab() if (!$loaded);
                   14660: 
1.846     albertel 14661: 	my ($name,$what) = @_;
                   14662: 	return if ( !exists($domain{$name}) );
                   14663: 
                   14664: 	if (!$what) {
                   14665: 	    return $domain{$name}{'description'};
                   14666: 	}
                   14667: 	return $domain{$name}{$what};
                   14668:     }
1.974     raeburn  14669: 
                   14670:     sub domain_info {
                   14671:         &load_domain_tab() if (!$loaded);
                   14672:         return %domain;
                   14673:     }
                   14674: 
1.327     albertel 14675: }
                   14676: 
                   14677: 
1.1       albertel 14678: # ------------------------------------------------------------- Read hosts file
                   14679: {
1.838     albertel 14680:     my %hostname;
1.844     albertel 14681:     my %hostdom;
1.845     albertel 14682:     my %libserv;
1.852     albertel 14683:     my $loaded;
1.888     albertel 14684:     my %name_to_host;
1.1074    raeburn  14685:     my %internetdom;
1.1107    raeburn  14686:     my %LC_dns_serv;
1.852     albertel 14687: 
                   14688:     sub parse_hosts_tab {
                   14689: 	my ($file) = @_;
                   14690: 	foreach my $configline (@$file) {
                   14691: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  14692:             chomp($configline);
                   14693: 	    if ($configline =~ /^\^/) {
                   14694:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   14695:                     $LC_dns_serv{$1} = 1;
                   14696:                 }
                   14697:                 next;
                   14698:             }
1.1074    raeburn  14699: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 14700: 	    $name=~s/\s//g;
                   14701: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  14702:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   14703:                     my $curr = $hostname{$id};
                   14704:                     my $skip;
                   14705:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   14706:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   14707:                             $skip = 1;
                   14708:                         } else {
                   14709:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   14710:                         }
                   14711:                     }
                   14712:                     unless ($skip) {
                   14713:                         push(@{$name_to_host{$name}},$id);
                   14714:                     }
                   14715:                 } else {
                   14716:                     push(@{$name_to_host{$name}},$id);
                   14717:                 }
1.852     albertel 14718: 		$hostname{$id}=$name;
                   14719: 		$hostdom{$id}=$domain;
                   14720: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  14721:                 if (defined($protocol)) {
                   14722:                     if ($protocol eq 'https') {
                   14723:                         $protocol{$id} = $protocol;
                   14724:                     } else {
                   14725:                         $protocol{$id} = 'http'; 
                   14726:                     }
1.968     raeburn  14727:                 } else {
1.969     raeburn  14728:                     $protocol{$id} = 'http';
1.968     raeburn  14729:                 }
1.1074    raeburn  14730:                 if (defined($intdom)) {
                   14731:                     $internetdom{$id} = $intdom;
                   14732:                 }
1.852     albertel 14733: 	    }
                   14734: 	}
                   14735:     }
1.864     albertel 14736:     
                   14737:     sub reset_hosts_info {
1.897     albertel 14738: 	&purge_remembered();
1.864     albertel 14739: 	&reset_domain_info();
                   14740: 	&reset_hosts_ip_info();
1.892     albertel 14741: 	undef(%name_to_host);
1.864     albertel 14742: 	undef(%hostname);
                   14743: 	undef(%hostdom);
                   14744: 	undef(%libserv);
                   14745: 	undef($loaded);
                   14746:     }
1.1       albertel 14747: 
1.852     albertel 14748:     sub load_hosts_tab {
1.1172.2.70  raeburn  14749: 	my ($ignore_cache,$nocache) = @_;
                   14750: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  14751: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 14752: 	my @config = <$config>;
                   14753: 	&parse_hosts_tab(\@config);
                   14754: 	close($config);
                   14755: 	$loaded=1;
1.1       albertel 14756:     }
1.852     albertel 14757: 
1.838     albertel 14758:     sub hostname {
1.852     albertel 14759: 	&load_hosts_tab() if (!$loaded);
                   14760: 
1.838     albertel 14761: 	my ($lonid) = @_;
                   14762: 	return $hostname{$lonid};
                   14763:     }
1.845     albertel 14764: 
1.838     albertel 14765:     sub all_hostnames {
1.852     albertel 14766: 	&load_hosts_tab() if (!$loaded);
                   14767: 
1.838     albertel 14768: 	return %hostname;
                   14769:     }
1.845     albertel 14770: 
1.888     albertel 14771:     sub all_names {
1.1172.2.70  raeburn  14772:         my ($ignore_cache,$nocache) = @_;
                   14773: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 14774: 
                   14775: 	return %name_to_host;
                   14776:     }
                   14777: 
1.974     raeburn  14778:     sub all_host_domain {
                   14779:         &load_hosts_tab() if (!$loaded);
                   14780:         return %hostdom;
                   14781:     }
                   14782: 
1.845     albertel 14783:     sub is_library {
1.852     albertel 14784: 	&load_hosts_tab() if (!$loaded);
                   14785: 
1.845     albertel 14786: 	return exists($libserv{$_[0]});
                   14787:     }
                   14788: 
                   14789:     sub all_library {
1.852     albertel 14790: 	&load_hosts_tab() if (!$loaded);
                   14791: 
1.845     albertel 14792: 	return %libserv;
                   14793:     }
                   14794: 
1.1062    droeschl 14795:     sub unique_library {
                   14796: 	#2x reverse removes all hostnames that appear more than once
                   14797:         my %unique = reverse &all_library();
                   14798:         return reverse %unique;
                   14799:     }
                   14800: 
1.841     albertel 14801:     sub get_servers {
1.852     albertel 14802: 	&load_hosts_tab() if (!$loaded);
                   14803: 
1.841     albertel 14804: 	my ($domain,$type) = @_;
                   14805: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   14806: 	                                          : %hostname;
                   14807: 	my %result;
1.842     albertel 14808: 	if (ref($domain) eq 'ARRAY') {
                   14809: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 14810: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 14811: 		    $result{$host} = $hostname;
                   14812: 		}
                   14813: 	    }
                   14814: 	} else {
                   14815: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   14816: 		if ($hostdom{$host} eq $domain) {
                   14817: 		    $result{$host} = $hostname;
                   14818: 		}
1.841     albertel 14819: 	    }
                   14820: 	}
                   14821: 	return %result;
                   14822:     }
1.845     albertel 14823: 
1.1062    droeschl 14824:     sub get_unique_servers {
                   14825:         my %unique = reverse &get_servers(@_);
                   14826: 	return reverse %unique;
                   14827:     }
                   14828: 
1.844     albertel 14829:     sub host_domain {
1.852     albertel 14830: 	&load_hosts_tab() if (!$loaded);
                   14831: 
1.844     albertel 14832: 	my ($lonid) = @_;
                   14833: 	return $hostdom{$lonid};
                   14834:     }
                   14835: 
1.841     albertel 14836:     sub all_domains {
1.852     albertel 14837: 	&load_hosts_tab() if (!$loaded);
                   14838: 
1.841     albertel 14839: 	my %seen;
                   14840: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   14841: 	return @uniq;
                   14842:     }
1.1074    raeburn  14843: 
                   14844:     sub internet_dom {
                   14845:         &load_hosts_tab() if (!$loaded);
                   14846: 
                   14847:         my ($lonid) = @_;
                   14848:         return $internetdom{$lonid};
                   14849:     }
1.1107    raeburn  14850: 
                   14851:     sub is_LC_dns {
                   14852:         &load_hosts_tab() if (!$loaded);
                   14853: 
                   14854:         my ($hostname) = @_;
                   14855:         return exists($LC_dns_serv{$hostname});
                   14856:     }
                   14857: 
1.1       albertel 14858: }
                   14859: 
1.847     albertel 14860: { 
                   14861:     my %iphost;
1.856     albertel 14862:     my %name_to_ip;
                   14863:     my %lonid_to_ip;
1.869     albertel 14864: 
1.847     albertel 14865:     sub get_hosts_from_ip {
                   14866: 	my ($ip) = @_;
                   14867: 	my %iphosts = &get_iphost();
                   14868: 	if (ref($iphosts{$ip})) {
                   14869: 	    return @{$iphosts{$ip}};
                   14870: 	}
                   14871: 	return;
1.839     albertel 14872:     }
1.864     albertel 14873:     
                   14874:     sub reset_hosts_ip_info {
                   14875: 	undef(%iphost);
                   14876: 	undef(%name_to_ip);
                   14877: 	undef(%lonid_to_ip);
                   14878:     }
1.856     albertel 14879: 
                   14880:     sub get_host_ip {
                   14881: 	my ($lonid) = @_;
                   14882: 	if (exists($lonid_to_ip{$lonid})) {
                   14883: 	    return $lonid_to_ip{$lonid};
                   14884: 	}
                   14885: 	my $name=&hostname($lonid);
                   14886:    	my $ip = gethostbyname($name);
                   14887: 	return if (!$ip || length($ip) ne 4);
                   14888: 	$ip=inet_ntoa($ip);
                   14889: 	$name_to_ip{$name}   = $ip;
                   14890: 	$lonid_to_ip{$lonid} = $ip;
                   14891: 	return $ip;
                   14892:     }
1.847     albertel 14893:     
                   14894:     sub get_iphost {
1.1172.2.70  raeburn  14895: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 14896: 
1.869     albertel 14897: 	if (!$ignore_cache) {
                   14898: 	    if (%iphost) {
                   14899: 		return %iphost;
                   14900: 	    }
                   14901: 	    my ($ip_info,$cached)=
                   14902: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   14903: 	    if ($cached) {
                   14904: 		%iphost      = %{$ip_info->[0]};
                   14905: 		%name_to_ip  = %{$ip_info->[1]};
                   14906: 		%lonid_to_ip = %{$ip_info->[2]};
                   14907: 		return %iphost;
                   14908: 	    }
                   14909: 	}
1.894     albertel 14910: 
                   14911: 	# get yesterday's info for fallback
                   14912: 	my %old_name_to_ip;
                   14913: 	my ($ip_info,$cached)=
                   14914: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   14915: 	if ($cached) {
                   14916: 	    %old_name_to_ip = %{$ip_info->[1]};
                   14917: 	}
                   14918: 
1.1172.2.70  raeburn  14919: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 14920: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 14921: 	    my $ip;
                   14922: 	    if (!exists($name_to_ip{$name})) {
                   14923: 		$ip = gethostbyname($name);
                   14924: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 14925: 		    if (defined($old_name_to_ip{$name})) {
                   14926: 			$ip = $old_name_to_ip{$name};
                   14927: 			&logthis("Can't find $name defaulting to old $ip");
                   14928: 		    } else {
                   14929: 			&logthis("Name $name no IP found");
                   14930: 			next;
                   14931: 		    }
                   14932: 		} else {
                   14933: 		    $ip=inet_ntoa($ip);
1.847     albertel 14934: 		}
                   14935: 		$name_to_ip{$name} = $ip;
                   14936: 	    } else {
                   14937: 		$ip = $name_to_ip{$name};
1.653     albertel 14938: 	    }
1.888     albertel 14939: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   14940: 		$lonid_to_ip{$id} = $ip;
                   14941: 	    }
                   14942: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 14943: 	}
1.1172.2.70  raeburn  14944:         unless ($nocache) {
                   14945: 	    &do_cache_new('iphost','iphost',
                   14946: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   14947: 		          48*60*60);
                   14948:         }
1.869     albertel 14949: 
1.847     albertel 14950: 	return %iphost;
1.598     albertel 14951:     }
                   14952: 
1.992     raeburn  14953:     #
                   14954:     #  Given a DNS returns the loncapa host name for that DNS 
                   14955:     # 
                   14956:     sub host_from_dns {
                   14957:         my ($dns) = @_;
                   14958:         my @hosts;
                   14959:         my $ip;
                   14960: 
1.993     raeburn  14961:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  14962:             $ip = $name_to_ip{$dns};
                   14963:         }
                   14964:         if (!$ip) {
                   14965:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   14966:             if (length($ip) == 4) { 
                   14967: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   14968:             }
                   14969:         }
                   14970:         if ($ip) {
                   14971: 	    @hosts = get_hosts_from_ip($ip);
                   14972: 	    return $hosts[0];
                   14973:         }
                   14974:         return undef;
1.986     foxr     14975:     }
1.992     raeburn  14976: 
1.1074    raeburn  14977:     sub get_internet_names {
                   14978:         my ($lonid) = @_;
                   14979:         return if ($lonid eq '');
                   14980:         my ($idnref,$cached)=
                   14981:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   14982:         if ($cached) {
                   14983:             return $idnref;
                   14984:         }
                   14985:         my $ip = &get_host_ip($lonid);
                   14986:         my @hosts = &get_hosts_from_ip($ip);
                   14987:         my %iphost = &get_iphost();
                   14988:         my (@idns,%seen);
                   14989:         foreach my $id (@hosts) {
                   14990:             my $dom = &host_domain($id);
                   14991:             my $prim_id = &domain($dom,'primary');
                   14992:             my $prim_ip = &get_host_ip($prim_id);
                   14993:             next if ($seen{$prim_ip});
                   14994:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   14995:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   14996:                     my $intdom = &internet_dom($id);
                   14997:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   14998:                         push(@idns,$intdom);
                   14999:                     }
                   15000:                 }
                   15001:             }
                   15002:             $seen{$prim_ip} = 1;
                   15003:         }
1.1172.2.23  raeburn  15004:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  15005:     }
                   15006: 
1.986     foxr     15007: }
                   15008: 
1.1079    raeburn  15009: sub all_loncaparevs {
1.1172.2.39  raeburn  15010:     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  15011: }
                   15012: 
1.1172.2.27  raeburn  15013: # ------------------------------------------------------- Read loncaparev table
                   15014: {
                   15015:     sub load_loncaparevs {
                   15016:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  15017:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  15018:                 while (my $configline=<$config>) {
                   15019:                     chomp($configline);
                   15020:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   15021:                     $loncaparevs{$hostid}=$loncaparev;
                   15022:                 }
                   15023:                 close($config);
                   15024:             }
                   15025:         }
                   15026:     }
                   15027: }
                   15028: 
                   15029: # ----------------------------------------------------- Read serverhostID table
                   15030: {
                   15031:     sub load_serverhomeIDs {
                   15032:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  15033:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  15034:                 while (my $configline=<$config>) {
                   15035:                     chomp($configline);
                   15036:                     my ($name,$id)=split(/:/,$configline);
                   15037:                     $serverhomeIDs{$name}=$id;
                   15038:                 }
                   15039:                 close($config);
                   15040:             }
                   15041:         }
                   15042:     }
                   15043: }
                   15044: 
                   15045: 
1.862     albertel 15046: BEGIN {
                   15047: 
                   15048: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   15049:     unless ($readit) {
                   15050: {
                   15051:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   15052:     %perlvar = (%perlvar,%{$configvars});
                   15053: }
                   15054: 
                   15055: 
1.1       albertel 15056: # ------------------------------------------------------ Read spare server file
                   15057: {
1.1172.2.96  raeburn  15058:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 15059: 
                   15060:     while (my $configline=<$config>) {
                   15061:        chomp($configline);
1.284     matthew  15062:        if ($configline) {
1.784     albertel 15063: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 15064: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 15065: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 15066:        }
                   15067:     }
1.448     albertel 15068:     close($config);
1.1       albertel 15069: }
1.11      www      15070: # ------------------------------------------------------------ Read permissions
                   15071: {
1.1172.2.96  raeburn  15072:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      15073: 
                   15074:     while (my $configline=<$config>) {
1.448     albertel 15075: 	chomp($configline);
                   15076: 	if ($configline) {
                   15077: 	    my ($role,$perm)=split(/ /,$configline);
                   15078: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   15079: 	}
1.11      www      15080:     }
1.448     albertel 15081:     close($config);
1.11      www      15082: }
                   15083: 
                   15084: # -------------------------------------------- Read plain texts for permissions
                   15085: {
1.1172.2.96  raeburn  15086:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      15087: 
                   15088:     while (my $configline=<$config>) {
1.448     albertel 15089: 	chomp($configline);
                   15090: 	if ($configline) {
1.742     raeburn  15091: 	    my ($short,@plain)=split(/:/,$configline);
                   15092:             %{$prp{$short}} = ();
                   15093: 	    if (@plain > 0) {
                   15094:                 $prp{$short}{'std'} = $plain[0];
                   15095:                 for (my $i=1; $i<@plain; $i++) {
                   15096:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   15097:                 }
                   15098:             }
1.448     albertel 15099: 	}
1.135     www      15100:     }
1.448     albertel 15101:     close($config);
1.135     www      15102: }
                   15103: 
                   15104: # ---------------------------------------------------------- Read package table
                   15105: {
1.1172.2.96  raeburn  15106:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      15107: 
                   15108:     while (my $configline=<$config>) {
1.483     albertel 15109: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 15110: 	chomp($configline);
                   15111: 	my ($short,$plain)=split(/:/,$configline);
                   15112: 	my ($pack,$name)=split(/\&/,$short);
                   15113: 	if ($plain ne '') {
                   15114: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   15115: 	    $packagetab{$short}=$plain; 
                   15116: 	}
1.11      www      15117:     }
1.448     albertel 15118:     close($config);
1.329     matthew  15119: }
                   15120: 
1.1172.2.27  raeburn  15121: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  15122: 
1.1172.2.27  raeburn  15123: &load_loncaparevs();
                   15124: 
                   15125: # ------------------------------------------------------- Read serverhostID table
                   15126: 
                   15127: &load_serverhomeIDs();
1.1074    raeburn  15128: 
1.1172.2.27  raeburn  15129: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  15130: {
                   15131:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   15132:     if (-e $file) {
                   15133:         my $parser = HTML::LCParser->new($file);
                   15134:         while (my $token = $parser->get_token()) {
                   15135:             if ($token->[0] eq 'S') {
                   15136:                 my $item = $token->[1];
                   15137:                 my $name = $token->[2]{'name'};
                   15138:                 my $value = $token->[2]{'value'};
                   15139:                 if ($item ne '' && $name ne '' && $value ne '') {
                   15140:                     my $release = $parser->get_text();
                   15141:                     $release =~ s/(^\s*|\s*$ )//gx;
                   15142:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   15143:                 }
                   15144:             }
                   15145:         }
                   15146:     }
1.1073    raeburn  15147: }
                   15148: 
1.1138    raeburn  15149: # ---------------------------------------------------------- Read managers table
                   15150: {
                   15151:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  15152:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  15153:             while (my $configline=<$config>) {
                   15154:                 chomp($configline);
                   15155:                 next if ($configline =~ /^\#/);
                   15156:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   15157:                     $managerstab{$configline} = 1;
                   15158:                 }
                   15159:             }
                   15160:             close($config);
                   15161:         }
                   15162:     }
                   15163: }
                   15164: 
1.329     matthew  15165: # ------------- set up temporary directory
                   15166: {
1.1117    foxr     15167:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  15168: 
1.11      www      15169: }
                   15170: 
1.1172.2.104  raeburn  15171: # ------------- set default texengine (domain default overrides this)
                   15172: {
                   15173:     $deftex = LONCAPA::texengine();
                   15174: }
                   15175: 
1.1172.2.114  raeburn  15176: # ------------- set default minimum length for passwords for internal auth users
                   15177: {
                   15178:     $passwdmin = LONCAPA::passwd_min();
                   15179: }
                   15180: 
1.794     albertel 15181: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   15182: 				'compress_threshold'=> 20_000,
                   15183:  			        });
1.185     www      15184: 
1.281     www      15185: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      15186: $dumpcount=0;
1.958     www      15187: $locknum=0;
1.22      www      15188: 
1.163     harris41 15189: &logtouch();
1.672     albertel 15190: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      15191: $readit=1;
1.564     albertel 15192:     {
                   15193: 	use integer;
                   15194: 	my $test=(2**32)+1;
1.568     albertel 15195: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 15196: 	&logthis(" Detected 64bit platform ($_64bit)");
                   15197:     }
1.195     www      15198: }
1.1       albertel 15199: }
1.179     www      15200: 
1.1       albertel 15201: 1;
1.191     harris41 15202: __END__
                   15203: 
1.243     albertel 15204: =pod
                   15205: 
1.191     harris41 15206: =head1 NAME
                   15207: 
1.243     albertel 15208: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 15209: 
                   15210: =head1 SYNOPSIS
                   15211: 
1.243     albertel 15212: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 15213: 
                   15214:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   15215: 
1.243     albertel 15216: Common parameters:
                   15217: 
                   15218: =over 4
                   15219: 
                   15220: =item *
                   15221: 
                   15222: $uname : an internal username (if $cname expecting a course Id specifically)
                   15223: 
                   15224: =item *
                   15225: 
                   15226: $udom : a domain (if $cdom expecting a course's domain specifically)
                   15227: 
                   15228: =item *
                   15229: 
                   15230: $symb : a resource instance identifier
                   15231: 
                   15232: =item *
                   15233: 
                   15234: $namespace : the name of a .db file that contains the data needed or
                   15235: being set.
                   15236: 
                   15237: =back
                   15238: 
1.394     bowersj2 15239: =head1 OVERVIEW
1.191     harris41 15240: 
1.394     bowersj2 15241: lonnet provides subroutines which interact with the
                   15242: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   15243: about classes, users, and resources.
1.243     albertel 15244: 
                   15245: For many of these objects you can also use this to store data about
                   15246: them or modify them in various ways.
1.191     harris41 15247: 
1.394     bowersj2 15248: =head2 Symbs
1.191     harris41 15249: 
1.394     bowersj2 15250: To identify a specific instance of a resource, LON-CAPA uses symbols
                   15251: or "symbs"X<symb>. These identifiers are built from the URL of the
                   15252: map, the resource number of the resource in the map, and the URL of
                   15253: the resource itself. The latter is somewhat redundant, but might help
                   15254: if maps change.
                   15255: 
                   15256: An example is
                   15257: 
                   15258:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   15259: 
                   15260: The respective map entry is
                   15261: 
                   15262:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   15263:   title="Problem 2">
                   15264:  </resource>
                   15265: 
                   15266: Symbs are used by the random number generator, as well as to store and
                   15267: restore data specific to a certain instance of for example a problem.
                   15268: 
                   15269: =head2 Storing And Retrieving Data
                   15270: 
                   15271: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   15272: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   15273: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   15274: is is the non-critical message twin of cstore. These functions are for
                   15275: handlers to store a perl hash to a user's permanent data space in an
                   15276: easy manner, and to retrieve it again on another call. It is expected
                   15277: that a handler would use this once at the beginning to retrieve data,
                   15278: and then again once at the end to send only the new data back.
                   15279: 
                   15280: The data is stored in the user's data directory on the user's
                   15281: homeserver under the ID of the course.
                   15282: 
                   15283: The hash that is returned by restore will have all of the previous
                   15284: value for all of the elements of the hash.
                   15285: 
                   15286: Example:
                   15287: 
                   15288:  #creating a hash
                   15289:  my %hash;
                   15290:  $hash{'foo'}='bar';
                   15291: 
                   15292:  #storing it
                   15293:  &Apache::lonnet::cstore(\%hash);
                   15294: 
                   15295:  #changing a value
                   15296:  $hash{'foo'}='notbar';
                   15297: 
                   15298:  #adding a new value
                   15299:  $hash{'bar'}='foo';
                   15300:  &Apache::lonnet::cstore(\%hash);
                   15301: 
                   15302:  #retrieving the hash
                   15303:  my %history=&Apache::lonnet::restore();
                   15304: 
                   15305:  #print the hash
                   15306:  foreach my $key (sort(keys(%history))) {
                   15307:    print("\%history{$key} = $history{$key}");
                   15308:  }
                   15309: 
                   15310: Will print out:
1.191     harris41 15311: 
1.394     bowersj2 15312:  %history{1:foo} = bar
                   15313:  %history{1:keys} = foo:timestamp
                   15314:  %history{1:timestamp} = 990455579
                   15315:  %history{2:bar} = foo
                   15316:  %history{2:foo} = notbar
                   15317:  %history{2:keys} = foo:bar:timestamp
                   15318:  %history{2:timestamp} = 990455580
                   15319:  %history{bar} = foo
                   15320:  %history{foo} = notbar
                   15321:  %history{timestamp} = 990455580
                   15322:  %history{version} = 2
                   15323: 
                   15324: Note that the special hash entries C<keys>, C<version> and
                   15325: C<timestamp> were added to the hash. C<version> will be equal to the
                   15326: total number of versions of the data that have been stored. The
                   15327: C<timestamp> attribute will be the UNIX time the hash was
                   15328: stored. C<keys> is available in every historical section to list which
                   15329: keys were added or changed at a specific historical revision of a
                   15330: hash.
                   15331: 
                   15332: B<Warning>: do not store the hash that restore returns directly. This
                   15333: will cause a mess since it will restore the historical keys as if the
                   15334: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 15335: 
1.394     bowersj2 15336: Calling convention:
1.191     harris41 15337: 
1.1172.2.27  raeburn  15338:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  15339:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 15340: 
1.394     bowersj2 15341: For more detailed information, see lonnet specific documentation.
1.191     harris41 15342: 
1.394     bowersj2 15343: =head1 RETURN MESSAGES
1.191     harris41 15344: 
1.394     bowersj2 15345: =over 4
1.191     harris41 15346: 
1.394     bowersj2 15347: =item * B<con_lost>: unable to contact remote host
1.191     harris41 15348: 
1.394     bowersj2 15349: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   15350: when the connection is brought back up
1.191     harris41 15351: 
1.394     bowersj2 15352: =item * B<con_failed>: unable to contact remote host and unable to save message
                   15353: for later delivery
1.191     harris41 15354: 
1.967     bisitz   15355: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 15356: 
1.394     bowersj2 15357: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 15358: that was requested
1.191     harris41 15359: 
1.243     albertel 15360: =back
1.191     harris41 15361: 
1.243     albertel 15362: =head1 PUBLIC SUBROUTINES
1.191     harris41 15363: 
1.243     albertel 15364: =head2 Session Environment Functions
1.191     harris41 15365: 
1.243     albertel 15366: =over 4
1.191     harris41 15367: 
1.394     bowersj2 15368: =item * 
                   15369: X<appenv()>
1.949     raeburn  15370: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 15371: the user envirnoment file, and will be restored for each access this
1.620     albertel 15372: user makes during this session, also modifies the %env for the current
1.949     raeburn  15373: process. Optional rolesarrayref - if defined contains a reference to an array
                   15374: of roles which are exempt from the restriction on modifying user.role entries 
                   15375: in the user's environment.db and in %env.    
1.191     harris41 15376: 
                   15377: =item *
1.394     bowersj2 15378: X<delenv()>
1.987     raeburn  15379: B<delenv($delthis,$regexp)>: removes all items from the session
                   15380: environment file that begin with $delthis. If the 
                   15381: optional second arg - $regexp - is true, $delthis is treated as a 
                   15382: regular expression, otherwise \Q$delthis\E is used. 
                   15383: The values are also deleted from the current processes %env.
1.191     harris41 15384: 
1.795     albertel 15385: =item * get_env_multiple($name) 
                   15386: 
                   15387: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   15388: values may be defined and end up as an array ref.
                   15389: 
                   15390: returns an array of values
                   15391: 
1.243     albertel 15392: =back
                   15393: 
                   15394: =head2 User Information
1.191     harris41 15395: 
1.243     albertel 15396: =over 4
1.191     harris41 15397: 
                   15398: =item *
1.394     bowersj2 15399: X<queryauthenticate()>
                   15400: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 15401: authentication scheme
                   15402: 
                   15403: =item *
1.394     bowersj2 15404: X<authenticate()>
1.1073    raeburn  15405: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 15406: authenticate user from domain's lib servers (first use the current
                   15407: one). C<$upass> should be the users password.
1.1073    raeburn  15408: $checkdefauth is optional (value is 1 if a check should be made to
                   15409:    authenticate user using default authentication method, and allow
                   15410:    account creation if username does not have account in the domain).
                   15411: $clientcancheckhost is optional (value is 1 if checking whether the
                   15412:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 15413: 
                   15414: =item *
1.394     bowersj2 15415: X<homeserver()>
                   15416: B<homeserver($uname,$udom)>: find the server which has
                   15417: the user's directory and files (there must be only one), this caches
                   15418: the answer, and also caches if there is a borken connection.
1.191     harris41 15419: 
                   15420: =item *
1.394     bowersj2 15421: X<idget()>
                   15422: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   15423: (IDs are a unique resource in a domain, there must be only 1 ID per
                   15424: username, and only 1 username per ID in a specific domain) (returns
                   15425: hash: id=>name,id=>name)
1.191     harris41 15426: 
                   15427: =item *
1.394     bowersj2 15428: X<idrget()>
                   15429: B<idrget($udom,@unames)>: find the IDs behind a list of
                   15430: usernames (returns hash: name=>id,name=>id)
1.191     harris41 15431: 
                   15432: =item *
1.394     bowersj2 15433: X<idput()>
                   15434: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 15435: 
                   15436: =item *
1.394     bowersj2 15437: X<rolesinit()>
1.1169    droeschl 15438: B<rolesinit($udom,$username)>: get user privileges.
                   15439: returns user role, first access and timer interval hashes
1.243     albertel 15440: 
                   15441: =item *
1.1171    droeschl 15442: X<privileged()>
                   15443: B<privileged($username,$domain)>: returns a true if user has a
                   15444: privileged and active role (i.e. su or dc), false otherwise.
                   15445: 
                   15446: =item *
1.551     albertel 15447: X<getsection()>
                   15448: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 15449: course $cname, return section name/number or '' for "not in course"
                   15450: and '-1' for "no section"
                   15451: 
                   15452: =item *
1.394     bowersj2 15453: X<userenvironment()>
                   15454: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 15455: passed in @what from the requested user's environment, returns a hash
                   15456: 
1.858     raeburn  15457: =item * 
                   15458: X<userlog_query()>
1.859     albertel 15459: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   15460: activity.log file. %filters defines filters applied when parsing the
                   15461: log file. These can be start or end timestamps, or the type of action
                   15462: - log to look for Login or Logout events, check for Checkin or
                   15463: Checkout, role for role selection. The response is in the form
                   15464: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   15465: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  15466: 
1.243     albertel 15467: =back
                   15468: 
                   15469: =head2 User Roles
                   15470: 
                   15471: =over 4
                   15472: 
                   15473: =item *
                   15474: 
1.1172.2.65  raeburn  15475: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   15476: returns codes for allowed actions.
                   15477: 
                   15478: The first argument is required, all others are optional.
                   15479: 
                   15480: $priv is the privilege being checked.
                   15481: $uri contains additional information about what is being checked for access (e.g.,
                   15482: URL, course ID etc.).
                   15483: $symb is the unique resource instance identifier in a course; if needed,
                   15484: but not provided, it will be retrieved via a call to &symbread().
                   15485: $role is the role for which a priv is being checked (only used if priv is evb).
                   15486: $clientip is the user's IP address (only used when checking for access to portfolio
                   15487: files).
                   15488: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   15489: prevents recursive calls to &allowed.
                   15490: 
1.243     albertel 15491:  F: full access
                   15492:  U,I,K: authentication modes (cxx only)
                   15493:  '': forbidden
                   15494:  1: user needs to choose course
                   15495:  2: browse allowed
1.766     albertel 15496:  A: passphrase authentication needed
1.1172.2.65  raeburn  15497:  B: access temporarily blocked because of a blocking event in a course.
1.1172.2.146.  .1(raebu 15498:22):  D: access blocked because access is required via session initiated via deep-link
1.243     albertel 15499: 
                   15500: =item *
                   15501: 
1.1172.2.13  raeburn  15502: constructaccess($url,$setpriv) : check for access to construction space URL
                   15503: 
                   15504: See if the owner domain and name in the URL match those in the
                   15505: expected environment.  If so, return three element list
                   15506: ($ownername,$ownerdomain,$ownerhome).
                   15507: 
                   15508: Otherwise return the null string.
                   15509: 
                   15510: If second argument 'setpriv' is true, it assigns the privileges,
                   15511: and returns the same three element list, unless the owner has
                   15512: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   15513: in which case the null string is returned.
                   15514: 
                   15515: =item *
                   15516: 
1.1172.2.84  raeburn  15517: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   15518: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   15519: for system, domain, and course level. $uname and $udom are optional (current
                   15520: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 15521: 
                   15522: =item *
                   15523: 
1.988     raeburn  15524: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   15525: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  15526: $type is Course (default) or Community.
1.988     raeburn  15527: If $forcedefault evaluates to true, text returned will be default 
                   15528: text for $type. Otherwise, if this is a course, the text returned 
                   15529: will be a custom name for the role (if defined in the course's 
                   15530: environment).  If no custom name is defined the default is returned.
                   15531:    
1.832     raeburn  15532: =item *
                   15533: 
1.1172.2.23  raeburn  15534: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  15535: All arguments are optional. Returns a hash of a roles, either for
                   15536: co-author/assistant author roles for a user's Construction Space
1.906     albertel 15537: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  15538: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   15539: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   15540: For each key, value is set to colon-separated start and end times for
                   15541: the role.  If no username and domain are specified, will default to
1.934     raeburn  15542: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  15543: of role statuses (active, future or previous), roles 
                   15544: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   15545: to restrict the list of roles reported. If no array ref is 
                   15546: provided for types, will default to return only active roles.
1.834     albertel 15547: 
1.1172.2.13  raeburn  15548: =item *
                   15549: 
                   15550: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   15551: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   15552: 
                   15553: Additional optional arguments are: $type (if role checking is to be restricted
                   15554: to certain user status types -- previous (expired roles), active (currently
                   15555: available roles) or future (roles available in the future), and
                   15556: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  15557: have active Domain Coordinator role in course's domain or in additional
                   15558: domains (specified in 'Domains to check for privileged users' in course
                   15559: environment -- set via:  Course Settings -> Classlists and staff listing).
                   15560: 
                   15561: =item *
                   15562: 
                   15563: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   15564: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   15565: $possdomains and $possroles are optional array refs -- to domains to check and
                   15566: roles to check.  If $possdomains is not specified, a dump will be done of the
                   15567: users' roles.db to check for a dc or su role in any domain. This can be
                   15568: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   15569: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   15570: this then allows &privileged_by_domain() to be used, which caches the identity
                   15571: of privileged users, eliminating the need for repeated calls to &dump().
                   15572: 
                   15573: =item *
                   15574: 
                   15575: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   15576: where the outer hash keys are domains specified in the $possdomains array ref,
                   15577: next inner hash keys are privileged roles specified in the $roles array ref,
                   15578: and the innermost hash contains key = value pairs for username:domain = end:start
                   15579: for active or future "privileged" users with that role in that domain. To avoid
                   15580: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   15581: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  15582: 
1.243     albertel 15583: =back
                   15584: 
                   15585: =head2 User Modification
                   15586: 
                   15587: =over 4
                   15588: 
                   15589: =item *
                   15590: 
1.957     raeburn  15591: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 15592: user for the level given by URL.  Optional start and end dates (leave empty
                   15593: string or zero for "no date")
1.191     harris41 15594: 
                   15595: =item *
                   15596: 
1.243     albertel 15597: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   15598: change a users, password, possible return values are: ok,
                   15599: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   15600: refused
1.191     harris41 15601: 
                   15602: =item *
                   15603: 
1.243     albertel 15604: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 15605: 
                   15606: =item *
                   15607: 
1.1058    raeburn  15608: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   15609:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   15610: 
                   15611: will update user information (firstname,middlename,lastname,generation,
                   15612: permanentemail), and if forceid is true, student/employee ID also.
                   15613: A user's institutional affiliation(s) can also be updated.
                   15614: User information fields will not be overwritten with empty entries 
                   15615: unless the field is included in the $candelete array reference.
                   15616: This array is included when a single user is modified via "Manage Users",
                   15617: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 15618: 
                   15619: =item *
                   15620: 
1.286     matthew  15621: modifystudent
                   15622: 
1.957     raeburn  15623: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  15624: The course id is resolved based on the current user's environment.  
                   15625: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  15626: associated with a course.
                   15627: 
1.297     matthew  15628: This call is essentially a wrapper for lonnet::modifyuser and
                   15629: lonnet::modify_student_enrollment
1.286     matthew  15630: 
                   15631: Inputs: 
                   15632: 
                   15633: =over 4
                   15634: 
1.957     raeburn  15635: =item B<$udom> Student's loncapa domain
1.286     matthew  15636: 
1.957     raeburn  15637: =item B<$uname> Student's loncapa login name
1.286     matthew  15638: 
1.964     bisitz   15639: =item B<$uid> Student/Employee ID
1.286     matthew  15640: 
1.957     raeburn  15641: =item B<$umode> Student's authentication mode
1.286     matthew  15642: 
1.957     raeburn  15643: =item B<$upass> Student's password
1.286     matthew  15644: 
1.957     raeburn  15645: =item B<$first> Student's first name
1.286     matthew  15646: 
1.957     raeburn  15647: =item B<$middle> Student's middle name
1.286     matthew  15648: 
1.957     raeburn  15649: =item B<$last> Student's last name
1.286     matthew  15650: 
1.957     raeburn  15651: =item B<$gene> Student's generation
1.286     matthew  15652: 
1.957     raeburn  15653: =item B<$usec> Student's section in course
1.286     matthew  15654: 
                   15655: =item B<$end> Unix time of the roles expiration
                   15656: 
                   15657: =item B<$start> Unix time of the roles start date
                   15658: 
                   15659: =item B<$forceid> If defined, allow $uid to be changed
                   15660: 
                   15661: =item B<$desiredhome> server to use as home server for student
                   15662: 
1.957     raeburn  15663: =item B<$email> Student's permanent e-mail address
                   15664: 
                   15665: =item B<$type> Type of enrollment (auto or manual)
                   15666: 
1.963     raeburn  15667: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   15668: 
                   15669: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  15670: 
1.963     raeburn  15671: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  15672: 
1.963     raeburn  15673: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  15674: 
1.1172.2.19  raeburn  15675: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   15676: 
                   15677: =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  15678: 
1.286     matthew  15679: =back
1.297     matthew  15680: 
                   15681: =item *
                   15682: 
                   15683: modify_student_enrollment
                   15684: 
1.1172.2.31  raeburn  15685: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  15686: 'role.request.course' must be defined for this function to proceed.
                   15687: 
                   15688: Inputs:
                   15689: 
                   15690: =over 4
                   15691: 
1.1172.2.31  raeburn  15692: =item $udom, student's domain
1.297     matthew  15693: 
1.1172.2.31  raeburn  15694: =item $uname, student's name
1.297     matthew  15695: 
1.1172.2.31  raeburn  15696: =item $uid, student's user id
1.297     matthew  15697: 
1.1172.2.31  raeburn  15698: =item $first, student's first name
1.297     matthew  15699: 
                   15700: =item $middle
                   15701: 
                   15702: =item $last
                   15703: 
                   15704: =item $gene
                   15705: 
                   15706: =item $usec
                   15707: 
                   15708: =item $end
                   15709: 
                   15710: =item $start
                   15711: 
1.957     raeburn  15712: =item $type
                   15713: 
                   15714: =item $locktype
                   15715: 
                   15716: =item $cid
                   15717: 
                   15718: =item $selfenroll
                   15719: 
                   15720: =item $context
                   15721: 
1.1172.2.19  raeburn  15722: =item $credits, number of credits student will earn from this class
                   15723: 
1.1172.2.76  raeburn  15724: =item $instsec, institutional course section code for student
                   15725: 
1.297     matthew  15726: =back
                   15727: 
1.191     harris41 15728: 
                   15729: =item *
                   15730: 
1.243     albertel 15731: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   15732: custom role; give a custom role to a user for the level given by URL.  Specify
                   15733: name and domain of role author, and role name
1.191     harris41 15734: 
                   15735: =item *
                   15736: 
1.243     albertel 15737: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 15738: 
                   15739: =item *
                   15740: 
1.243     albertel 15741: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   15742: 
                   15743: =back
                   15744: 
                   15745: =head2 Course Infomation
                   15746: 
                   15747: =over 4
1.191     harris41 15748: 
                   15749: =item *
                   15750: 
1.1118    foxr     15751: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 15752: specified course id, including all environment settings for the
                   15753: course, the description of the course will be in the hash under the
                   15754: key 'description'
1.191     harris41 15755: 
1.1118    foxr     15756: $options is an optional parameter that if supplied is a hash reference that controls
                   15757: what how this function works.  It has the following key/values:
                   15758: 
                   15759: =over 4
                   15760: 
                   15761: =item freshen_cache
                   15762: 
                   15763: If defined, and the environment cache for the course is valid, it is 
                   15764: returned in the returned hash.
                   15765: 
                   15766: =item one_time
                   15767: 
                   15768: If defined, the last cache time is set to _now_
                   15769: 
                   15770: =item user
                   15771: 
                   15772: If defined, the supplied username is used instead of the current user.
                   15773: 
                   15774: 
                   15775: =back
                   15776: 
1.191     harris41 15777: =item *
                   15778: 
1.624     albertel 15779: resdata($name,$domain,$type,@which) : request for current parameter
                   15780: setting for a specific $type, where $type is either 'course' or 'user',
                   15781: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  15782: answers for 10 minutes.
1.243     albertel 15783: 
1.877     foxr     15784: =item *
                   15785: 
                   15786: get_courseresdata($courseid, $domain) : dump the entire course resource
                   15787: data base, returning a hash that is keyed by the resource name and has
                   15788: values that are the resource value.  I believe that the timestamps and
                   15789: versions are also returned.
                   15790: 
1.243     albertel 15791: =back
                   15792: 
                   15793: =head2 Course Modification
                   15794: 
                   15795: =over 4
1.191     harris41 15796: 
                   15797: =item *
                   15798: 
1.243     albertel 15799: writecoursepref($courseid,%prefs) : write preferences (environment
                   15800: database) for a course
1.191     harris41 15801: 
                   15802: =item *
                   15803: 
1.1011    raeburn  15804: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   15805: 
                   15806: =item *
                   15807: 
1.1038    raeburn  15808: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 15809: 
1.1167    droeschl 15810: =item *
                   15811: 
                   15812: is_course($courseid), is_course($cdom, $cnum)
                   15813: 
                   15814: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   15815: two component version $cdom, $cnum. It checks if the specified course exists.
                   15816: 
                   15817: Returns:
                   15818:     undef if the course doesn't exist, otherwise
                   15819:     in scalar context the combined courseid.
                   15820:     in list context the two components of the course identifier, domain and 
                   15821:     courseid.    
                   15822: 
1.243     albertel 15823: =back
                   15824: 
1.1172.2.109  raeburn  15825: =head2 Bubblesheet Configuration
                   15826: 
                   15827: =over 4
                   15828: 
                   15829: =item *
                   15830: 
                   15831: get_scantron_config($which)
                   15832: 
                   15833: $which - the name of the configuration to parse from the file.
                   15834: 
                   15835: Parses and returns the bubblesheet configuration line selected as a
                   15836: hash of configuration file fields.
                   15837: 
                   15838: 
                   15839: Returns:
                   15840:     If the named configuration is not in the file, an empty
                   15841:     hash is returned.
                   15842: 
                   15843:     a hash with the fields
                   15844:       name         - internal name for the this configuration setup
                   15845:       description  - text to display to operator that describes this config
                   15846:       CODElocation - if 0 or the string 'none'
                   15847:                           - no CODE exists for this config
                   15848:                      if -1 || the string 'letter'
                   15849:                           - a CODE exists for this config and is
                   15850:                             a string of letters
                   15851:                      Unsupported value (but planned for future support)
                   15852:                           if a positive integer
                   15853:                                - The CODE exists as the first n items from
                   15854:                                  the question section of the form
                   15855:                           if the string 'number'
                   15856:                                - The CODE exists for this config and is
                   15857:                                  a string of numbers
                   15858:       CODEstart   - (only matter if a CODE exists) column in the line where
                   15859:                      the CODE starts
                   15860:       CODElength  - length of the CODE
                   15861:       IDstart     - column where the student/employee ID starts
                   15862:       IDlength    - length of the student/employee ID info
                   15863:       Qstart      - column where the information from the bubbled
                   15864:                     'questions' start
                   15865:       Qlength     - number of columns comprising a single bubble line from
                   15866:                     the sheet. (usually either 1 or 10)
                   15867:       Qon         - either a single character representing the character used
                   15868:                     to signal a bubble was chosen in the positional setup, or
                   15869:                     the string 'letter' if the letter of the chosen bubble is
                   15870:                     in the final, or 'number' if a number representing the
                   15871:                     chosen bubble is in the file (1->A 0->J)
                   15872:       Qoff        - the character used to represent that a bubble was
                   15873:                     left blank
                   15874:       PaperID     - if the scanning process generates a unique number for each
                   15875:                     sheet scanned the column that this ID number starts in
                   15876:       PaperIDlength - number of columns that comprise the unique ID number
                   15877:                       for the sheet of paper
                   15878:       FirstName   - column that the first name starts in
                   15879:       FirstNameLength - number of columns that the first name spans
                   15880:       LastName    - column that the last name starts in
                   15881:       LastNameLength - number of columns that the last name spans
                   15882:       BubblesPerRow - number of bubbles available in each row used to
                   15883:                       bubble an answer. (If not specified, 10 assumed).
                   15884: 
                   15885: 
                   15886: =item *
                   15887: 
                   15888: get_scantronformat_file($cdom)
                   15889: 
                   15890: $cdom - the course's domain (optional); if not supplied, uses
                   15891: domain for current $env{'request.course.id'}.
                   15892: 
                   15893: Returns an array containing lines from the scantron format file for
                   15894: the domain of the course.
                   15895: 
                   15896: If a url for a custom.tab file is listed in domain's configuration.db,
                   15897: lines are from this file.
                   15898: 
                   15899: Otherwise, if a default.tab has been published in RES space by the
                   15900: domainconfig user, lines are from this file.
                   15901: 
                   15902: Otherwise, fall back to getting lines from the legacy file on the
                   15903: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   15904: 
                   15905: =back
                   15906: 
1.243     albertel 15907: =head2 Resource Subroutines
                   15908: 
                   15909: =over 4
1.191     harris41 15910: 
                   15911: =item *
                   15912: 
1.243     albertel 15913: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 15914: 
                   15915: =item *
                   15916: 
1.243     albertel 15917: repcopy($filename) : subscribes to the requested file, and attempts to
                   15918: replicate from the owning library server, Might return
1.607     raeburn  15919: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   15920: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 15921: resource. Expects the local filesystem pathname
                   15922: (/home/httpd/html/res/....)
                   15923: 
                   15924: =back
                   15925: 
                   15926: =head2 Resource Information
                   15927: 
                   15928: =over 4
1.191     harris41 15929: 
                   15930: =item *
                   15931: 
1.1172.2.28  raeburn  15932: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   15933: and returns the value of a variety of different possible values,
                   15934: $varname should be a request string, and the other parameters can be
                   15935: used to specify who and what one is asking about. Ordinarily, $cid 
                   15936: does not need to be specified, as it is retrived from 
                   15937: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   15938: within lonuserstate::loadmap() when initializing a course, before
                   15939: $env{'request.course.id'} has been set, so it needs to be provided
                   15940: in that one case.
1.243     albertel 15941: 
                   15942: Possible values for $varname are environment.lastname (or other item
                   15943: from the envirnment hash), user.name (or someother aspect about the
                   15944: user), resource.0.maxtries (or some other part and parameter of a
                   15945: resource)
1.204     albertel 15946: 
                   15947: =item *
                   15948: 
1.243     albertel 15949: directcondval($number) : get current value of a condition; reads from a state
                   15950: string
1.204     albertel 15951: 
                   15952: =item *
                   15953: 
1.243     albertel 15954: condval($condidx) : value of condition index based on state
1.204     albertel 15955: 
                   15956: =item *
                   15957: 
1.243     albertel 15958: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   15959: resource's metadata, $what should be either a specific key, or either
                   15960: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   15961: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   15962: 
                   15963: this function automatically caches all requests
1.191     harris41 15964: 
                   15965: =item *
                   15966: 
1.243     albertel 15967: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   15968: network of library servers; returns file handle of where SQL and regex results
                   15969: will be stored for query
1.191     harris41 15970: 
                   15971: =item *
                   15972: 
1.1172.2.66  raeburn  15973: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   15974: return symbolic list entry (all arguments optional).
                   15975: 
                   15976: Args: filename is the filename (including path) for the file for which a symb
                   15977: is required; donotrecurse, if true will prevent calls to allowed() being made
                   15978: to check access status if more than one resource was found in the bighash
                   15979: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   15980: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   15981: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   15982: cause possible symbs to be checked to determine if they are subject to content
                   15983: blocking, if so they will not be included as possible symbs; possibles is a
                   15984: ref to a hash, which, as a side effect, will be populated with all possible
                   15985: symbs (content blocking not tested).
                   15986: 
1.243     albertel 15987: returns the data handle
1.191     harris41 15988: 
                   15989: =item *
                   15990: 
1.1172.2.17  raeburn  15991: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  15992: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 15993: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  15994: on failure, user must be in a course, as it assumes the existence of
                   15995: the course initial hash, and uses $env('request.course.id'}.  The third
                   15996: arg is an optional reference to a scalar.  If this arg is passed in the
                   15997: call to symbverify, it will be set to 1 if the symb has been set to be 
                   15998: encrypted; otherwise it will be null.
1.243     albertel 15999: 
1.191     harris41 16000: =item *
                   16001: 
1.243     albertel 16002: symbclean($symb) : removes versions numbers from a symb, returns the
                   16003: cleaned symb
1.191     harris41 16004: 
                   16005: =item *
                   16006: 
1.243     albertel 16007: is_on_map($uri) : checks if the $uri is somewhere on the current
                   16008: course map, user must be in a course for it to work.
1.191     harris41 16009: 
                   16010: =item *
                   16011: 
1.243     albertel 16012: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 16013: 
                   16014: =item *
                   16015: 
1.243     albertel 16016: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   16017: a random seed, all arguments are optional, if they aren't sent it uses the
                   16018: environment to derive them. Note: if symb isn't sent and it can't get one
                   16019: from &symbread it will use the current time as its return value
1.191     harris41 16020: 
                   16021: =item *
                   16022: 
1.243     albertel 16023: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   16024: unfakeable, receipt
1.191     harris41 16025: 
                   16026: =item *
                   16027: 
1.620     albertel 16028: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 16029: 
                   16030: =item *
                   16031: 
1.243     albertel 16032: countacc($url) : count the number of accesses to a given URL
1.191     harris41 16033: 
                   16034: =item *
                   16035: 
1.243     albertel 16036: 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 16037: 
                   16038: =item *
                   16039: 
1.243     albertel 16040: 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 16041: 
                   16042: =item *
                   16043: 
1.243     albertel 16044: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 16045: 
                   16046: =item *
                   16047: 
1.243     albertel 16048: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   16049: forcing spreadsheet to reevaluate the resource scores next time.
                   16050: 
1.1172.2.13  raeburn  16051: =item *
                   16052: 
                   16053: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   16054: when viewing in course context.
                   16055: 
                   16056:  input: six args -- filename (decluttered), course number, course domain,
                   16057:                     url, symb (if registered) and group (if this is a
                   16058:                     group item -- e.g., bulletin board, group page etc.).
                   16059: 
                   16060:  output: array of five scalars --
                   16061:          $cfile -- url for file editing if editable on current server
                   16062:          $home -- homeserver of resource (i.e., for author if published,
                   16063:                                           or course if uploaded.).
                   16064:          $switchserver --  1 if server switch will be needed.
                   16065:          $forceedit -- 1 if icon/link should be to go to edit mode
                   16066:          $forceview -- 1 if icon/link should be to go to view mode
                   16067: 
                   16068: =item *
                   16069: 
                   16070: is_course_upload($file,$cnum,$cdom)
                   16071: 
                   16072: Used in course context to determine if current file was uploaded to
                   16073: the course (i.e., would be found in /userfiles/docs on the course's
                   16074: homeserver.
                   16075: 
                   16076:   input: 3 args -- filename (decluttered), course number and course domain.
                   16077:   output: boolean -- 1 if file was uploaded.
                   16078: 
1.243     albertel 16079: =back
                   16080: 
                   16081: =head2 Storing/Retreiving Data
                   16082: 
                   16083: =over 4
1.191     harris41 16084: 
                   16085: =item *
                   16086: 
1.1172.2.64  raeburn  16087: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   16088: permanently for this url; hashref needs to be given and should be a \%hashname;
                   16089: the remaining args aren't required and if they aren't passed or are '' they will
                   16090: be derived from the env (with the exception of $laststore, which is an
                   16091: optional arg used when a user's submission is stored in grading).
                   16092: $laststore is $version=$timestamp, where $version is the most recent version
                   16093: number retrieved for the corresponding $symb in the $namespace db file, and
                   16094: $timestamp is the timestamp for that transaction (UNIX time).
                   16095: $laststore is currently only passed when cstore() is called by
                   16096: structuretags::finalize_storage().
1.191     harris41 16097: 
                   16098: =item *
                   16099: 
1.1172.2.64  raeburn  16100: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   16101: but uses critical subroutine
1.191     harris41 16102: 
                   16103: =item *
                   16104: 
1.243     albertel 16105: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   16106: all args are optional
1.191     harris41 16107: 
                   16108: =item *
                   16109: 
1.717     albertel 16110: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   16111: dumps the complete (or key matching regexp) namespace into a hash
                   16112: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   16113: normally &store()ed into
                   16114: 
                   16115: $range should be either an integer '100' (give me the first 100
                   16116:                                            matching records)
                   16117:               or be  two integers sperated by a - with no spaces
                   16118:                  '30-50' (give me the 30th through the 50th matching
                   16119:                           records)
                   16120: 
                   16121: 
                   16122: =item *
                   16123: 
1.1172.2.59  raeburn  16124: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 16125: replaces a &store() version of data with a replacement set of data
                   16126: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  16127: reference. If $tolog is true, the transaction is logged in the courselog
                   16128: with an action=PUTSTORE.
1.717     albertel 16129: 
                   16130: =item *
                   16131: 
1.243     albertel 16132: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   16133: works very similar to store/cstore, but all data is stored in a
                   16134: temporary location and can be reset using tmpreset, $storehash should
                   16135: be a hash reference, returns nothing on success
1.191     harris41 16136: 
                   16137: =item *
                   16138: 
1.243     albertel 16139: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   16140: similar to restore, but all data is stored in a temporary location and
                   16141: can be reset using tmpreset. Returns a hash of values on success,
                   16142: error string otherwise.
1.191     harris41 16143: 
                   16144: =item *
                   16145: 
1.243     albertel 16146: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   16147: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 16148: 
                   16149: =item *
                   16150: 
1.243     albertel 16151: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16152: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 16153: 
                   16154: =item *
                   16155: 
1.243     albertel 16156: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   16157: namesp ($udom and $uname are optional)
1.191     harris41 16158: 
                   16159: =item *
                   16160: 
1.702     albertel 16161: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 16162: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 16163: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  16164: 
1.702     albertel 16165: $range should be either an integer '100' (give me the first 100
                   16166:                                            matching records)
                   16167:               or be  two integers sperated by a - with no spaces
                   16168:                  '30-50' (give me the 30th through the 50th matching
                   16169:                           records)
1.449     matthew  16170: =item *
                   16171: 
                   16172: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   16173: $store can be a scalar, an array reference, or if the amount to be 
                   16174: incremented is > 1, a hash reference.
                   16175: 
                   16176: ($udom and $uname are optional)
1.191     harris41 16177: 
                   16178: =item *
                   16179: 
1.243     albertel 16180: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   16181: ($udom and $uname are optional)
1.191     harris41 16182: 
                   16183: =item *
                   16184: 
1.243     albertel 16185: cput($namespace,$storehash,$udom,$uname) : critical put
                   16186: ($udom and $uname are optional)
1.191     harris41 16187: 
                   16188: =item *
                   16189: 
1.748     albertel 16190: newput($namespace,$storehash,$udom,$uname) :
                   16191: 
                   16192: Attempts to store the items in the $storehash, but only if they don't
                   16193: currently exist, if this succeeds you can be certain that you have 
                   16194: successfully created a new key value pair in the $namespace db.
                   16195: 
                   16196: 
                   16197: Args:
                   16198:  $namespace: name of database to store values to
                   16199:  $storehash: hashref to store to the db
                   16200:  $udom: (optional) domain of user containing the db
                   16201:  $uname: (optional) name of user caontaining the db
                   16202: 
                   16203: Returns:
                   16204:  'ok' -> succeeded in storing all keys of $storehash
                   16205:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   16206:                         least <key> already existed in the db (other
                   16207:                         requested keys may also already exist)
1.967     bisitz   16208:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 16209:  'con_lost' -> unable to contact request server
                   16210:  'refused' -> action was not allowed by remote machine
                   16211: 
                   16212: 
                   16213: =item *
                   16214: 
1.243     albertel 16215: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16216: reference filled in from namesp (encrypts the return communication)
                   16217: ($udom and $uname are optional)
1.191     harris41 16218: 
                   16219: =item *
                   16220: 
1.243     albertel 16221: log($udom,$name,$home,$message) : write to permanent log for user; use
                   16222: critical subroutine
                   16223: 
1.806     raeburn  16224: =item *
                   16225: 
1.860     raeburn  16226: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   16227: array reference filled in from namespace found in domain level on either
                   16228: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  16229: 
                   16230: =item *
                   16231: 
1.860     raeburn  16232: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   16233: domain level either on specified domain server ($uhome) or primary domain 
                   16234: server ($udom and $uhome are optional)
1.806     raeburn  16235: 
1.943     raeburn  16236: =item * 
                   16237: 
1.1172.2.35  raeburn  16238: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   16239: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   16240: the target domain.
                   16241: 
                   16242: May also include additional key => value pairs for the following groups:
                   16243: 
                   16244: =over
                   16245: 
                   16246: =item
                   16247: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   16248: 
                   16249: =over
                   16250: 
                   16251: =item defaultquota, authorquota
                   16252: 
                   16253: =back
                   16254: 
                   16255: =item
                   16256: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   16257: portfolio for users).
                   16258: 
                   16259: =over
                   16260: 
                   16261: =item
                   16262: aboutme, blog, webdav, portfolio
                   16263: 
                   16264: =back
                   16265: 
                   16266: =item
                   16267: requestcourses: ability to request courses, and how requests are processed.
                   16268: 
                   16269: =over
                   16270: 
                   16271: =item
1.1172.2.37  raeburn  16272: official, unofficial, community, textbook
1.1172.2.35  raeburn  16273: 
                   16274: =back
                   16275: 
                   16276: =item
                   16277: inststatus: types of institutional affiliation, and order in which they are displayed.
                   16278: 
                   16279: =over
                   16280: 
                   16281: =item
1.1172.2.44  raeburn  16282: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  16283: 
                   16284: =back
                   16285: 
                   16286: =item
                   16287: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   16288: for course's uploaded content.
                   16289: 
                   16290: =over
                   16291: 
                   16292: =item
1.1172.2.68  raeburn  16293: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   16294: communityquota, textbookquota
1.1172.2.35  raeburn  16295: 
                   16296: =back
                   16297: 
                   16298: =item
                   16299: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   16300: on your servers.
                   16301: 
                   16302: =over
                   16303: 
                   16304: =item
                   16305: remotesessions, hostedsessions
                   16306: 
                   16307: =back
                   16308: 
                   16309: =back
                   16310: 
                   16311: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   16312: utility to create a configuration.db file on a domain's primary library server
                   16313: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   16314: -- corresponding values are authentication type (internal, krb4, krb5,
                   16315: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   16316: will be available. Values are retrieved from cache (if current), unless the
                   16317: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   16318: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   16319: 
                   16320: Typical usage:
1.943     raeburn  16321: 
1.1172.2.35  raeburn  16322: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  16323: 
1.243     albertel 16324: =back
                   16325: 
                   16326: =head2 Network Status Functions
                   16327: 
                   16328: =over 4
1.191     harris41 16329: 
                   16330: =item *
                   16331: 
1.1137    raeburn  16332: dirlist() : return directory list based on URI (first arg).
                   16333: 
                   16334: Inputs: 1 required, 5 optional.
                   16335: 
                   16336: =over
                   16337: 
                   16338: =item 
                   16339: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   16340: 
                   16341: =item
                   16342: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   16343: 
                   16344: =item
                   16345: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   16346: 
                   16347: =item
                   16348: $getpropath - boolean: 1 if prepend path using &propath(). 
                   16349: 
                   16350: =item
                   16351: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   16352: 
                   16353: =item 
                   16354: $alternateRoot - path to prepend in place of path from $uri.
                   16355: 
                   16356: =back
                   16357: 
                   16358: Returns: Array of up to two items.
                   16359: 
                   16360: =over
                   16361: 
                   16362: a reference to an array of files/subdirectories
                   16363: 
                   16364: =over
                   16365: 
                   16366: Each element in the array of files/subdirectories is a & separated list of
                   16367: item name and the result of running stat on the item.  If dirlist was requested
                   16368: for a file instead of a directory, the item name will be ''. For a directory 
                   16369: listing, if the item is a metadata file, the element will end &N&M 
                   16370: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   16371: default copyright set (1).  
                   16372: 
                   16373: =back
                   16374: 
                   16375: a scalar containing error condition (if encountered).
                   16376: 
                   16377: =over
                   16378: 
                   16379: =item 
                   16380: no_host (no homeserver identified for $username:$domain).
                   16381: 
                   16382: =item 
                   16383: no_such_host (server contacted for listing not identified as valid host).
                   16384: 
                   16385: =item 
                   16386: con_lost (connection to remote server failed).
                   16387: 
                   16388: =item 
                   16389: refused (invalid $username:$domain received on lond side).
                   16390: 
                   16391: =item 
                   16392: no_such_dir (directory at specified path on lond side does not exist). 
                   16393: 
                   16394: =item 
                   16395: empty (directory at specified path on lond side is empty).
                   16396: 
                   16397: =over
                   16398: 
                   16399: This is currently not encountered because the &ls3, &ls2, 
                   16400: &ls (_handler) routines on the lond side do not filter out
                   16401: . and .. from a directory listing. 
                   16402: 
                   16403: =back
                   16404: 
                   16405: =back
                   16406: 
                   16407: =back
1.191     harris41 16408: 
                   16409: =item *
                   16410: 
1.243     albertel 16411: spareserver() : find server with least workload from spare.tab
                   16412: 
1.986     foxr     16413: 
                   16414: =item *
                   16415: 
                   16416: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   16417: if there is no corresponding loncapa host.
                   16418: 
1.243     albertel 16419: =back
                   16420: 
1.986     foxr     16421: 
1.243     albertel 16422: =head2 Apache Request
                   16423: 
                   16424: =over 4
1.191     harris41 16425: 
                   16426: =item *
                   16427: 
1.243     albertel 16428: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   16429: localhost, posts hash
                   16430: 
                   16431: =back
                   16432: 
                   16433: =head2 Data to String to Data
                   16434: 
                   16435: =over 4
1.191     harris41 16436: 
                   16437: =item *
                   16438: 
1.243     albertel 16439: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   16440: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 16441: 
                   16442: =item *
                   16443: 
1.243     albertel 16444: hashref2str($hashref) : convert a hashref into a string complete with
                   16445: escaping and '=' and '&' separators, supports elements that are
                   16446: arrayrefs and hashrefs
1.191     harris41 16447: 
                   16448: =item *
                   16449: 
1.243     albertel 16450: arrayref2str($arrayref) : convert an arrayref into a string complete
                   16451: with escaping and '&' separators, supports elements that are arrayrefs
                   16452: and hashrefs
1.191     harris41 16453: 
                   16454: =item *
                   16455: 
1.243     albertel 16456: str2hash($string) : convert string to hash using unescaping and
                   16457: splitting on '=' and '&', supports elements that are arrayrefs and
                   16458: hashrefs
1.191     harris41 16459: 
                   16460: =item *
                   16461: 
1.243     albertel 16462: str2array($string) : convert string to hash using unescaping and
                   16463: splitting on '&', supports elements that are arrayrefs and hashrefs
                   16464: 
                   16465: =back
                   16466: 
                   16467: =head2 Logging Routines
                   16468: 
                   16469: 
                   16470: These routines allow one to make log messages in the lonnet.log and
                   16471: lonnet.perm logfiles.
1.191     harris41 16472: 
1.1119    foxr     16473: =over 4
                   16474: 
1.191     harris41 16475: =item *
                   16476: 
1.243     albertel 16477: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 16478: 
                   16479: =item *
                   16480: 
1.243     albertel 16481: logthis() : append message to the normal lonnet.log file, it gets
                   16482: preiodically rolled over and deleted.
1.191     harris41 16483: 
                   16484: =item *
                   16485: 
1.243     albertel 16486: logperm() : append a permanent message to lonnet.perm.log, this log
                   16487: file never gets deleted by any automated portion of the system, only
                   16488: messages of critical importance should go in here.
                   16489: 
1.1119    foxr     16490: 
1.243     albertel 16491: =back
                   16492: 
                   16493: =head2 General File Helper Routines
                   16494: 
                   16495: =over 4
1.191     harris41 16496: 
                   16497: =item *
                   16498: 
1.481     raeburn  16499: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   16500: (a) files in /uploaded
                   16501:   (i) If a local copy of the file exists - 
                   16502:       compares modification date of local copy with last-modified date for 
                   16503:       definitive version stored on home server for course. If local copy is 
                   16504:       stale, requests a new version from the home server and stores it. 
                   16505:       If the original has been removed from the home server, then local copy 
                   16506:       is unlinked.
                   16507:   (ii) If local copy does not exist -
                   16508:       requests the file from the home server and stores it. 
                   16509:   
                   16510:   If $caller is 'uploadrep':  
                   16511:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   16512:     for request for files originally uploaded via DOCS. 
                   16513:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   16514:   
                   16515:   Otherwise:
                   16516:      This indicates a call from the content generation phase of the request.
                   16517:      -  returns the entire contents of the file or -1.
                   16518:      
                   16519: (b) files in /res
                   16520:    - returns the entire contents of a file or -1; 
                   16521:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 16522: 
1.712     albertel 16523: 
                   16524: =item *
                   16525: 
                   16526: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   16527:                   reference
                   16528: 
                   16529: returns either a stat() list of data about the file or an empty list
                   16530: if the file doesn't exist or couldn't find out about it (connection
                   16531: problems or user unknown)
                   16532: 
1.191     harris41 16533: =item *
                   16534: 
1.243     albertel 16535: filelocation($dir,$file) : returns file system location of a file
                   16536: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   16537: directory that relative $file lookups are to looked in ($dir of /a/dir
                   16538: and a file of ../bob will become /a/bob)
1.191     harris41 16539: 
                   16540: =item *
                   16541: 
                   16542: hreflocation($dir,$file) : returns file system location or a URL; same as
                   16543: filelocation except for hrefs
                   16544: 
                   16545: =item *
                   16546: 
1.1172.2.49  raeburn  16547: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   16548: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 16549: 
1.243     albertel 16550: =back
                   16551: 
1.608     albertel 16552: =head2 Usererfile file routines (/uploaded*)
                   16553: 
                   16554: =over 4
                   16555: 
                   16556: =item *
                   16557: 
                   16558: userfileupload(): main rotine for putting a file in a user or course's
                   16559:                   filespace, arguments are,
                   16560: 
1.620     albertel 16561:  formname - required - this is the name of the element in $env where the
1.608     albertel 16562:            filename, and the contents of the file to create/modifed exist
1.620     albertel 16563:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   16564:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  16565:  context - if coursedoc, store the file in the course of the active role
                   16566:              of the current user; 
                   16567:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   16568:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 16569:  subdir - required - subdirectory to put the file in under ../userfiles/
                   16570:          if undefined, it will be placed in "unknown"
                   16571: 
                   16572:  (This routine calls clean_filename() to remove any dangerous
                   16573:  characters from the filename, and then calls finuserfileupload() to
                   16574:  complete the transaction)
                   16575: 
                   16576:  returns either the url of the uploaded file (/uploaded/....) if successful
                   16577:  and /adm/notfound.html if unsuccessful
                   16578: 
                   16579: =item *
                   16580: 
                   16581: clean_filename(): routine for cleaing a filename up for storage in
                   16582:                  userfile space, argument is:
                   16583: 
                   16584:  filename - proposed filename
                   16585: 
                   16586: returns: the new clean filename
                   16587: 
                   16588: =item *
                   16589: 
1.1090    raeburn  16590: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 16591: userspace, probably shouldn't be called directly
                   16592: 
                   16593:   docuname: username or courseid of destination for the file
                   16594:   docudom: domain of user/course of destination for the file
                   16595:   formname: same as for userfileupload()
1.1090    raeburn  16596:   fname: filename (including subdirectories) for the file
                   16597:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  16598:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  16599:   allfiles: reference to hash used to store objects found by parser
                   16600:   codebase: reference to hash used for codebases of java objects found by parser
                   16601:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   16602:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   16603:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   16604:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   16605:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   16606:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  16607:   mimetype: reference to scalar to accommodate mime type determined
                   16608:             from File::MMagic if $parser = parse.
1.608     albertel 16609: 
                   16610:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  16611:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   16612:  was 'overwrite').
                   16613:  
1.608     albertel 16614: 
                   16615: =item *
                   16616: 
                   16617: renameuserfile(): renames an existing userfile to a new name
                   16618: 
                   16619:   Args:
                   16620:    docuname: username or courseid of destination for the file
                   16621:    docudom: domain of user/course of destination for the file
                   16622:    old: current file name (including any subdirs under userfiles)
                   16623:    new: desired file name (including any subdirs under userfiles)
                   16624: 
                   16625: =item *
                   16626: 
                   16627: mkdiruserfile(): creates a directory is a userfiles dir
                   16628: 
                   16629:   Args:
                   16630:    docuname: username or courseid of destination for the file
                   16631:    docudom: domain of user/course of destination for the file
                   16632:    dir: dir to create (including any subdirs under userfiles)
                   16633: 
                   16634: =item *
                   16635: 
                   16636: removeuserfile(): removes a file that exists in userfiles
                   16637: 
                   16638:   Args:
                   16639:    docuname: username or courseid of destination for the file
                   16640:    docudom: domain of user/course of destination for the file
                   16641:    fname: filname to delete (including any subdirs under userfiles)
                   16642: 
                   16643: =item *
                   16644: 
                   16645: removeuploadedurl(): convience function for removeuserfile()
                   16646: 
                   16647:   Args:
                   16648:    url:  a full /uploaded/... url to delete
                   16649: 
1.747     albertel 16650: =item * 
                   16651: 
                   16652: get_portfile_permissions():
                   16653:   Args:
                   16654:     domain: domain of user or course contain the portfolio files
                   16655:     user: name of user or num of course contain the portfolio files
                   16656:   Returns:
                   16657:     hashref of a dump of the proper file_permissions.db
                   16658:    
                   16659: 
                   16660: =item * 
                   16661: 
                   16662: get_access_controls():
                   16663: 
                   16664: Args:
                   16665:   current_permissions: the hash ref returned from get_portfile_permissions()
                   16666:   group: (optional) the group you want the files associated with
                   16667:   file: (optional) the file you want access info on
                   16668: 
                   16669: Returns:
1.749     raeburn  16670:     a hash (keys are file names) of hashes containing
                   16671:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   16672:         values are XML containing access control settings (see below) 
1.747     albertel 16673: 
                   16674: Internal notes:
                   16675: 
1.749     raeburn  16676:  access controls are stored in file_permissions.db as key=value pairs.
                   16677:     key -> path to file/file_name\0uniqueID:scope_end_start
                   16678:         where scope -> public,guest,course,group,domains or users.
                   16679:               end -> UNIX time for end of access (0 -> no end date)
                   16680:               start -> UNIX time for start of access
                   16681: 
                   16682:     value -> XML description of access control
                   16683:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   16684:             <start></start>
                   16685:             <end></end>
                   16686: 
                   16687:             <password></password>  for scope type = guest
                   16688: 
                   16689:             <domain></domain>     for scope type = course or group
                   16690:             <number></number>
                   16691:             <roles id="">
                   16692:              <role></role>
                   16693:              <access></access>
                   16694:              <section></section>
                   16695:              <group></group>
                   16696:             </roles>
                   16697: 
                   16698:             <dom></dom>         for scope type = domains
                   16699: 
                   16700:             <users>             for scope type = users
                   16701:              <user>
                   16702:               <uname></uname>
                   16703:               <udom></udom>
                   16704:              </user>
                   16705:             </users>
                   16706:            </scope> 
                   16707:               
                   16708:  Access data is also aggregated for each file in an additional key=value pair:
                   16709:  key -> path to file/file_name\0accesscontrol 
                   16710:  value -> reference to hash
                   16711:           hash contains key = value pairs
                   16712:           where key = uniqueID:scope_end_start
                   16713:                 value = UNIX time record was last updated
                   16714: 
                   16715:           Used to improve speed of look-ups of access controls for each file.  
                   16716:  
                   16717:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   16718: 
1.1172.2.13  raeburn  16719: =item *
                   16720: 
1.749     raeburn  16721: modify_access_controls():
                   16722: 
                   16723: Modifies access controls for a portfolio file
                   16724: Args
                   16725: 1. file name
                   16726: 2. reference to hash of required changes,
                   16727: 3. domain
                   16728: 4. username
                   16729:   where domain,username are the domain of the portfolio owner 
                   16730:   (either a user or a course) 
                   16731: 
                   16732: Returns:
                   16733: 1. result of additions or updates ('ok' or 'error', with error message). 
                   16734: 2. result of deletions ('ok' or 'error', with error message).
                   16735: 3. reference to hash of any new or updated access controls.
                   16736: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   16737:    key = integer (inbound ID)
1.1172.2.13  raeburn  16738:    value = uniqueID
                   16739: 
                   16740: =item *
                   16741: 
                   16742: get_timebased_id():
                   16743: 
                   16744: Attempts to get a unique timestamp-based suffix for use with items added to a
                   16745: course via the Course Editor (e.g., folders, composite pages,
                   16746: group bulletin boards).
                   16747: 
                   16748: Args: (first three required; six others optional)
                   16749: 
                   16750: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   16751:    docssequence, or name of group
                   16752: 
                   16753: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   16754:    e.g., num, boardids
                   16755: 
                   16756: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   16757:    file will be named nohist_namespace.db
                   16758: 
                   16759: 4. cdom: domain of course; default is current course domain from %env
                   16760: 
                   16761: 5. cnum: course number; default is current course number from %env
                   16762: 
                   16763: 6. idtype: set to concat if an additional digit is to be appended to the
                   16764:    unix timestamp to form the suffix, if the plain timestamp is already
                   16765:    in use.  Default is to not do this, but simply increment the unix
                   16766:    timestamp by 1 until a unique key is obtained.
                   16767: 
                   16768: 7. who: holder of locking key; defaults to user:domain for user.
                   16769: 
                   16770: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   16771:    retrying); default is 3.
                   16772: 
                   16773: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   16774: 
                   16775: Returns:
                   16776: 
                   16777: 1. suffix obtained (numeric)
                   16778: 
                   16779: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   16780: 
                   16781: 3. error: contains (localized) error message if an error occurred.
                   16782: 
1.747     albertel 16783: 
1.608     albertel 16784: =back
                   16785: 
1.243     albertel 16786: =head2 HTTP Helper Routines
                   16787: 
                   16788: =over 4
                   16789: 
1.191     harris41 16790: =item *
                   16791: 
                   16792: escape() : unpack non-word characters into CGI-compatible hex codes
                   16793: 
                   16794: =item *
                   16795: 
                   16796: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   16797: 
1.243     albertel 16798: =back
                   16799: 
                   16800: =head1 PRIVATE SUBROUTINES
                   16801: 
                   16802: =head2 Underlying communication routines (Shouldn't call)
                   16803: 
                   16804: =over 4
                   16805: 
                   16806: =item *
                   16807: 
                   16808: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   16809: 
                   16810: =item *
                   16811: 
                   16812: reply() : uses subreply to send a message to remote machine, logs all failures
                   16813: 
                   16814: =item *
                   16815: 
                   16816: critical() : passes a critical message to another server; if cannot
                   16817: get through then place message in connection buffer directory and
                   16818: returns con_delayed, if incapable of saving message, returns
                   16819: con_failed
                   16820: 
                   16821: =item *
                   16822: 
                   16823: reconlonc() : tries to reconnect lonc client processes.
                   16824: 
                   16825: =back
                   16826: 
                   16827: =head2 Resource Access Logging
                   16828: 
                   16829: =over 4
                   16830: 
                   16831: =item *
                   16832: 
                   16833: flushcourselogs() : flush (save) buffer logs and access logs
                   16834: 
                   16835: =item *
                   16836: 
                   16837: courselog($what) : save message for course in hash
                   16838: 
                   16839: =item *
                   16840: 
                   16841: courseacclog($what) : save message for course using &courselog().  Perform
                   16842: special processing for specific resource types (problems, exams, quizzes, etc).
                   16843: 
1.191     harris41 16844: =item *
                   16845: 
                   16846: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   16847: as a PerlChildExitHandler
1.243     albertel 16848: 
                   16849: =back
                   16850: 
                   16851: =head2 Other
                   16852: 
                   16853: =over 4
                   16854: 
                   16855: =item *
                   16856: 
                   16857: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 16858: 
                   16859: =back
                   16860: 
                   16861: =cut
1.877     foxr     16862: 

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