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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.146.  .16(raeb    4:-23): # $Id: lonnet.pm,v 1.1172.2.146.2.15 2023/09/06 13:33:33 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
1.1172.2.107  raeburn    77: use CGI::Cookie;
1.977     amueller   78: 
1.1172.2.104  raeburn    79: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
1.1138    raeburn    80:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
1.1172.2.114  raeburn    81:             %managerstab $passwdmin);
1.871     albertel   82: 
                     83: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     84:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     85:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        86:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        87: 
1.1       albertel   88: use IO::Socket;
1.31      www        89: use GDBM_File;
1.208     albertel   90: use HTML::LCParser;
1.88      www        91: use Fcntl qw(:flock);
1.870     albertel   92: use Storable qw(thaw nfreeze);
1.1172.2.79  raeburn    93: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   94: use Cache::Memcached;
1.676     albertel   95: use Digest::MD5;
1.790     albertel   96: use Math::Random;
1.1024    raeburn    97: use File::MMagic;
1.1172.2.142  raeburn    98: use Net::CIDR;
                     99: use Sys::Hostname::FQDN();
1.807     albertel  100: use LONCAPA qw(:DEFAULT :match);
1.740     www       101: use LONCAPA::Configuration;
1.1160    www       102: use LONCAPA::lonmetadata;
1.1172.2.22  raeburn   103: use LONCAPA::Lond;
1.1172.2.110  raeburn   104: use LONCAPA::transliterate;
1.1117    foxr      105: 
1.1090    raeburn   106: use File::Copy;
1.676     albertel  107: 
1.195     www       108: my $readit;
1.1172.2.79  raeburn   109: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  110: 
1.619     albertel  111: require Exporter;
                    112: 
                    113: our @ISA = qw (Exporter);
                    114: our @EXPORT = qw(%env);
                    115: 
1.1172.2.9  raeburn   116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       117: {
                    118:     my $logid;
1.1172.2.9  raeburn   119:     sub write_log {
                    120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    121:         if ($context eq 'course') {
                    122:             if (($cnum eq '') || ($cdom eq '')) {
                    123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    125:             }
1.957     raeburn   126:         }
1.1172.2.13  raeburn   127: 	$logid ++;
1.957     raeburn   128:         my $now = time();
                    129: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1172.2.146.  .1(raebu  130:22):         my $ip = &get_requestor_ip();
1.1172.2.9  raeburn   131:         my $logentry = {
                    132:                          $id => {
                    133:                                   'exe_uname' => $env{'user.name'},
                    134:                                   'exe_udom'  => $env{'user.domain'},
                    135:                                   'exe_time'  => $now,
1.1172.2.134  raeburn   136:                                   'exe_ip'    => $ip,
1.1172.2.9  raeburn   137:                                   'delflag'   => $delflag,
                    138:                                   'logentry'  => $storehash,
                    139:                                   'uname'     => $uname,
                    140:                                   'udom'      => $udom,
                    141:                                 }
                    142:                        };
                    143:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       144:     }
                    145: }
1.1       albertel  146: 
1.163     harris41  147: sub logtouch {
                    148:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  149:     unless (-e "$execdir/logs/lonnet.log") {	
1.1172.2.96  raeburn   150: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  151: 	close $fh;
                    152:     }
                    153:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    154:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    155: }
                    156: 
1.1       albertel  157: sub logthis {
                    158:     my $message=shift;
                    159:     my $execdir=$perlvar{'lonDaemons'};
                    160:     my $now=time;
                    161:     my $local=localtime($now);
1.1172.2.96  raeburn   162:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      163: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    164: 	print $fh $logstring;
1.448     albertel  165: 	close($fh);
                    166:     }
1.1       albertel  167:     return 1;
                    168: }
                    169: 
                    170: sub logperm {
                    171:     my $message=shift;
                    172:     my $execdir=$perlvar{'lonDaemons'};
                    173:     my $now=time;
                    174:     my $local=localtime($now);
1.1172.2.96  raeburn   175:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  176: 	print $fh "$now:$message:$local\n";
                    177: 	close($fh);
                    178:     }
1.1       albertel  179:     return 1;
                    180: }
                    181: 
1.850     albertel  182: sub create_connection {
1.853     albertel  183:     my ($hostname,$lonid) = @_;
1.851     albertel  184:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  185: 				     Type    => SOCK_STREAM,
                    186: 				     Timeout => 10);
                    187:     return 0 if (!$client);
1.890     albertel  188:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  189:     my $result = <$client>;
                    190:     chomp($result);
                    191:     return 1 if ($result eq 'done');
                    192:     return 0;
                    193: }
                    194: 
1.983     raeburn   195: sub get_server_timezone {
                    196:     my ($cnum,$cdom) = @_;
                    197:     my $home=&homeserver($cnum,$cdom);
                    198:     if ($home ne 'no_host') {
                    199:         my $cachetime = 24*3600;
                    200:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    201:         if (defined($cached)) {
                    202:             return $timezone;
                    203:         } else {
                    204:             my $timezone = &reply('servertimezone',$home);
                    205:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    206:         }
                    207:     }
                    208: }
1.850     albertel  209: 
1.1106    raeburn   210: sub get_server_distarch {
                    211:     my ($lonhost,$ignore_cache) = @_;
                    212:     if (defined($lonhost)) {
                    213:         if (!defined(&hostname($lonhost))) {
                    214:             return;
                    215:         }
                    216:         my $cachetime = 12*3600;
                    217:         if (!$ignore_cache) {
                    218:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    219:             if (defined($cached)) {
                    220:                 return $distarch;
                    221:             }
                    222:         }
                    223:         my $rep = &reply('serverdistarch',$lonhost);
                    224:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    225:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    226:                 $rep eq '') {
                    227:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    228:         }
                    229:     }
                    230:     return;
                    231: }
                    232: 
1.993     raeburn   233: sub get_server_loncaparev {
1.1073    raeburn   234:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   235:     if (defined($lonhost)) {
                    236:         if (!defined(&hostname($lonhost))) {
                    237:             undef($lonhost);
                    238:         }
                    239:     }
                    240:     if (!defined($lonhost)) {
                    241:         if (defined(&domain($dom,'primary'))) {
                    242:             $lonhost=&domain($dom,'primary');
                    243:             if ($lonhost eq 'no_host') {
                    244:                 undef($lonhost);
                    245:             }
                    246:         }
                    247:     }
                    248:     if (defined($lonhost)) {
1.1073    raeburn   249:         my $cachetime = 12*3600;
                    250:         if (!$ignore_cache) {
                    251:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    252:             if (defined($cached)) {
                    253:                 return $loncaparev;
                    254:             }
                    255:         }
                    256:         my ($answer,$loncaparev);
                    257:         my @ids=&current_machine_ids();
                    258:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    259:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   260:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   261:                 $loncaparev = $1;
                    262:             }
                    263:         } else {
                    264:             $answer = &reply('serverloncaparev',$lonhost);
                    265:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    266:                 if ($caller eq 'loncron') {
                    267:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   268:                     $ua->timeout(4);
1.1172.2.120  raeburn   269:                     my $hostname = &hostname($lonhost);
1.1073    raeburn   270:                     my $protocol = $protocol{$lonhost};
                    271:                     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn   272:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073    raeburn   273:                     my $request=new HTTP::Request('GET',$url);
                    274:                     my $response=$ua->request($request);
                    275:                     unless ($response->is_error()) {
                    276:                         my $content = $response->content;
1.1081    raeburn   277:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   278:                             $loncaparev = $1;
                    279:                         }
                    280:                     }
                    281:                 } else {
                    282:                     $loncaparev = $loncaparevs{$lonhost};
                    283:                 }
1.1081    raeburn   284:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   285:                 $loncaparev = $1;
                    286:             }
1.993     raeburn   287:         }
1.1073    raeburn   288:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   289:     }
                    290: }
                    291: 
1.1074    raeburn   292: sub get_server_homeID {
                    293:     my ($hostname,$ignore_cache,$caller) = @_;
                    294:     unless ($ignore_cache) {
                    295:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    296:         if (defined($cached)) {
                    297:             return $serverhomeID;
                    298:         }
                    299:     }
                    300:     my $cachetime = 12*3600;
                    301:     my $serverhomeID;
                    302:     if ($caller eq 'loncron') { 
                    303:         my @machine_ids = &machine_ids($hostname);
                    304:         foreach my $id (@machine_ids) {
                    305:             my $response = &reply('serverhomeID',$id);
                    306:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    307:                 $serverhomeID = $response;
                    308:                 last;
                    309:             }
                    310:         }
                    311:         if ($serverhomeID eq '') {
                    312:             $serverhomeID = $machine_ids[-1];
                    313:         }
                    314:     } else {
                    315:         $serverhomeID = $serverhomeIDs{$hostname};
                    316:     }
                    317:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    318: }
                    319: 
1.1121    raeburn   320: sub get_remote_globals {
                    321:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   322:     my ($result,%returnhash,%whatneeded);
                    323:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   324:         foreach my $what (sort(keys(%{$whathash}))) {
                    325:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   326:             my ($response,$cached);
1.1121    raeburn   327:             unless ($ignore_cache) {
1.1125    raeburn   328:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   329:             }
                    330:             if (defined($cached)) {
1.1125    raeburn   331:                 $returnhash{$what} = $response;
1.1121    raeburn   332:             } else {
1.1125    raeburn   333:                 $whatneeded{$what} = 1;
1.1121    raeburn   334:             }
                    335:         }
1.1125    raeburn   336:         if (keys(%whatneeded) == 0) {
                    337:             $result = 'ok';
                    338:         } else {
1.1121    raeburn   339:             my $requested = &freeze_escape(\%whatneeded);
                    340:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   341:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    342:                 ($rep eq 'unknown_cmd')) {
                    343:                 $result = $rep;
                    344:             } else {
                    345:                 $result = 'ok';
1.1121    raeburn   346:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   347:                 foreach my $item (@pairs) {
                    348:                     my ($key,$value)=split(/=/,$item,2);
                    349:                     my $what = &unescape($key);
                    350:                     my $hashid = $lonhost.'-'.$what;
                    351:                     $returnhash{$what}=&thaw_unescape($value);
                    352:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   353:                 }
                    354:             }
                    355:         }
                    356:     }
1.1125    raeburn   357:     return ($result,\%returnhash);
1.1121    raeburn   358: }
                    359: 
1.1124    raeburn   360: sub remote_devalidate_cache {
1.1172.2.35  raeburn   361:     my ($lonhost,$cachekeys) = @_;
                    362:     my $items;
                    363:     return unless (ref($cachekeys) eq 'ARRAY');
                    364:     my $cachestr = join('&',@{$cachekeys});
                    365:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   366: }
                    367: 
1.1172.2.146.  .13(raeb  368:-23): sub sign_lti {
                    369:-23):     my ($cdom,$cnum,$crsdef,$type,$context,$url,$ltinum,$keynum,$paramsref,$inforef) = @_;
                    370:-23):     my $chome;
                    371:-23):     if (&domain($cdom) ne '') {
                    372:-23):         if ($crsdef) {
                    373:-23):             $chome = &homeserver($cnum,$cdom);
                    374:-23):         } else {
                    375:-23):             $chome = &domain($cdom,'primary');
                    376:-23):         }
                    377:-23):     }
                    378:-23):     if ($cdom && $chome && ($chome ne 'no_host')) {
                    379:-23):         if ((ref($paramsref) eq 'HASH') &&
                    380:-23):             (ref($inforef) eq 'HASH')) {
                    381:-23):             my $rep;
                    382:-23):             if (grep { $_ eq $chome } &current_machine_ids()) {
                    383:-23):                 # domain information is hosted on this machine
                    384:-23):                 $rep =
                    385:-23):                     &LONCAPA::Lond::sign_lti_payload($cdom,$cnum,$crsdef,$type,
                    386:-23):                                                      $context,$url,$ltinum,$keynum,
                    387:-23):                                                      $perlvar{'lonVersion'},
                    388:-23):                                                      $paramsref,$inforef);
                    389:-23):                 if (ref($rep) eq 'HASH') {
                    390:-23):                     return ('ok',$rep);
                    391:-23):                 }
                    392:-23):             } else {
                    393:-23):                 my ($escurl,$params,$info);
                    394:-23):                 $escurl = &escape($url);
                    395:-23):                 if (ref($paramsref) eq 'HASH') {
                    396:-23):                     $params = &freeze_escape($paramsref);
                    397:-23):                 }
                    398:-23):                 if (ref($inforef) eq 'HASH') {
                    399:-23):                     $info = &freeze_escape($inforef);
                    400:-23):                 }
                    401:-23):                 $rep=&reply("encrypt:signlti:$cdom:$cnum:$crsdef:$type:$context:$escurl:$ltinum:$keynum:$params:$info",$chome);
                    402:-23):             }
                    403:-23):             if (($rep eq '') || ($rep =~ /^con_lost|error|no_such_host|unknown_cmd/i)) {
                    404:-23):                 return ();
                    405:-23):             } elsif (($inforef->{'respfmt'} eq 'to_post_body') ||
                    406:-23):                      ($inforef->{'respfmt'} eq 'to_authorization_header')) {
                    407:-23):                 return ('ok',$rep);
                    408:-23):             } else {
                    409:-23):                 my %returnhash;
                    410:-23):                 foreach my $item (split(/\&/,$rep)) {
                    411:-23):                     my ($name,$value)=split(/\=/,$item);
                    412:-23):                     $returnhash{&unescape($name)}=&thaw_unescape($value);
                    413:-23):                 }
                    414:-23):                 return('ok',\%returnhash);
                    415:-23):             }
                    416:-23):         } else {
                    417:-23):             return ();
                    418:-23):         }
                    419:-23):     } else {
                    420:-23):         return ();
                    421:-23):         &logthis("sign_lti failed - no homeserver and/or domain ($cdom) ($chome)");
                    422:-23):     }
                    423:-23): }
                    424:-23): 
1.1       albertel  425: # -------------------------------------------------- Non-critical communication
                    426: sub subreply {
                    427:     my ($cmd,$server)=@_;
1.838     albertel  428:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      429:     #
                    430:     #  With loncnew process trimming, there's a timing hole between lonc server
                    431:     #  process exit and the master server picking up the listen on the AF_UNIX
                    432:     #  socket.  In that time interval, a lock file will exist:
                    433: 
                    434:     my $lockfile=$peerfile.".lock";
                    435:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1172.2.79  raeburn   436: 	sleep(0.1);
1.549     foxr      437:     }
                    438:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      439:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      440:     #
1.550     foxr      441:     #   We'll give the connection a few tries before abandoning it.  If
                    442:     #   connection is not possible, we'll con_lost back to the client.
                    443:     #   
                    444:     my $client;
                    445:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    446: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    447: 				      Type    => SOCK_STREAM,
                    448: 				      Timeout => 10);
1.869     albertel  449: 	if ($client) {
1.550     foxr      450: 	    last;		# Connected!
1.850     albertel  451: 	} else {
1.853     albertel  452: 	    &create_connection(&hostname($server),$server);
1.550     foxr      453: 	}
1.1172.2.79  raeburn   454:         sleep(0.1);		# Try again later if failed connection.
1.550     foxr      455:     }
                    456:     my $answer;
                    457:     if ($client) {
1.704     albertel  458: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      459: 	$answer=<$client>;
                    460: 	if (!$answer) { $answer="con_lost"; }
                    461: 	chomp($answer);
                    462:     } else {
                    463: 	$answer = 'con_lost';	# Failed connection.
                    464:     }
1.1       albertel  465:     return $answer;
                    466: }
                    467: 
                    468: sub reply {
                    469:     my ($cmd,$server)=@_;
1.838     albertel  470:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  471:     my $answer=subreply($cmd,$server);
1.65      www       472:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1172.2.111  raeburn   473:         my $logged = $cmd;
                    474:         if ($cmd =~ /^encrypt:([^:]+):/) {
                    475:             my $subcmd = $1;
                    476:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
                    477:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
1.1172.2.146.  .13(raeb  478:-23):                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades') ||
                    479:-23):                 ($subcmd eq 'put')) {
1.1172.2.111  raeburn   480:                 (undef,undef,my @rest) = split(/:/,$cmd);
                    481:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
                    482:                     splice(@rest,2,1,'Hidden');
                    483:                 } elsif ($subcmd eq 'passwd') {
                    484:                     splice(@rest,2,2,('Hidden','Hidden'));
                    485:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
1.1172.2.146.  .13(raeb  486:-23):                          ($subcmd eq 'autoexportgrades') || ($subcmd eq 'put')) {
1.1172.2.111  raeburn   487:                     splice(@rest,3,1,'Hidden');
                    488:                 }
                    489:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
                    490:             }
                    491:         }
                    492:         &logthis("<font color=\"blue\">WARNING:".
                    493:                  " $logged to $server returned $answer</font>");
1.12      www       494:     }
1.1       albertel  495:     return $answer;
                    496: }
                    497: 
                    498: # ----------------------------------------------------------- Send USR1 to lonc
                    499: 
                    500: sub reconlonc {
1.891     albertel  501:     my ($lonid) = @_;
                    502:     if ($lonid) {
1.1172.2.72  raeburn   503:         my $hostname = &hostname($lonid);
1.891     albertel  504: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    505: 	if ($hostname && -e $peerfile) {
                    506: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    507: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    508: 					     Type    => SOCK_STREAM,
                    509: 					     Timeout => 10);
                    510: 	    if ($client) {
                    511: 		print $client ("reset_retries\n");
                    512: 		my $answer=<$client>;
                    513: 		#reset just this one.
                    514: 	    }
                    515: 	}
                    516: 	return;
                    517:     }
                    518: 
1.836     www       519:     &logthis("Trying to reconnect lonc");
1.1       albertel  520:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1172.2.96  raeburn   521:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  522: 	my $loncpid=<$fh>;
                    523:         chomp($loncpid);
                    524:         if (kill 0 => $loncpid) {
                    525: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    526:             kill USR1 => $loncpid;
                    527:             sleep 1;
1.836     www       528:          } else {
1.12      www       529: 	    &logthis(
1.672     albertel  530:                "<font color=\"blue\">WARNING:".
1.12      www       531:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  532:         }
                    533:     } else {
1.836     www       534: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  535:     }
                    536: }
                    537: 
                    538: # ------------------------------------------------------ Critical communication
1.12      www       539: 
1.1       albertel  540: sub critical {
                    541:     my ($cmd,$server)=@_;
1.838     albertel  542:     unless (&hostname($server)) {
1.672     albertel  543:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       544:                " Critical message to unknown server ($server)</font>");
                    545:         return 'no_such_host';
                    546:     }
1.1       albertel  547:     my $answer=reply($cmd,$server);
                    548:     if ($answer eq 'con_lost') {
1.1172.2.72  raeburn   549: 	&reconlonc($server);
1.589     albertel  550: 	my $answer=reply($cmd,$server);
1.1       albertel  551:         if ($answer eq 'con_lost') {
                    552:             my $now=time;
                    553:             my $middlename=$cmd;
1.5       www       554:             $middlename=substr($middlename,0,16);
1.1       albertel  555:             $middlename=~s/\W//g;
                    556:             my $dfilename=
1.305     www       557:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    558:             $dumpcount++;
1.1       albertel  559:             {
1.448     albertel  560: 		my $dfh;
1.1172.2.96  raeburn   561: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  562: 		    print $dfh "$cmd\n"; 
                    563: 		    close($dfh);
                    564: 		}
1.1       albertel  565:             }
1.1172.2.79  raeburn   566:             sleep 1;
1.1       albertel  567:             my $wcmd='';
                    568:             {
1.448     albertel  569: 		my $dfh;
1.1172.2.96  raeburn   570: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  571: 		    $wcmd=<$dfh>; 
                    572: 		    close($dfh);
                    573: 		}
1.1       albertel  574:             }
                    575:             chomp($wcmd);
1.7       www       576:             if ($wcmd eq $cmd) {
1.672     albertel  577: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       578:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  579:                 &logperm("D:$server:$cmd");
                    580: 	        return 'con_delayed';
                    581:             } else {
1.672     albertel  582:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       583:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  584:                 &logperm("F:$server:$cmd");
                    585:                 return 'con_failed';
                    586:             }
                    587:         }
                    588:     }
                    589:     return $answer;
1.405     albertel  590: }
                    591: 
1.755     albertel  592: # ------------------------------------------- check if return value is an error
                    593: 
                    594: sub error {
                    595:     my ($result) = @_;
1.756     albertel  596:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  597: 	if ($2 == 2) { return undef; }
                    598: 	return $1;
                    599:     }
                    600:     return undef;
                    601: }
                    602: 
1.783     albertel  603: sub convert_and_load_session_env {
                    604:     my ($lonidsdir,$handle)=@_;
                    605:     my @profile;
                    606:     {
1.917     albertel  607: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    608: 	if (!$opened) {
1.915     albertel  609: 	    return 0;
                    610: 	}
1.783     albertel  611: 	flock($idf,LOCK_SH);
                    612: 	@profile=<$idf>;
                    613: 	close($idf);
                    614:     }
                    615:     my %temp_env;
                    616:     foreach my $line (@profile) {
1.786     albertel  617: 	if ($line !~ m/=/) {
                    618: 	    return 0;
                    619: 	}
1.783     albertel  620: 	chomp($line);
                    621: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    622: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    623:     }
                    624:     unlink("$lonidsdir/$handle.id");
                    625:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    626: 	    0640)) {
                    627: 	%disk_env = %temp_env;
                    628: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    629: 	untie(%disk_env);
                    630:     }
1.786     albertel  631:     return 1;
1.783     albertel  632: }
                    633: 
1.374     www       634: # ------------------------------------------- Transfer profile into environment
1.780     albertel  635: my $env_loaded;
                    636: sub transfer_profile_to_env {
1.788     albertel  637:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    638:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       639: 
1.720     albertel  640:     if (!defined($lonidsdir)) {
                    641: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    642:     }
                    643:     if (!defined($handle)) {
                    644:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    645:     }
                    646: 
1.786     albertel  647:     my $convert;
                    648:     {
1.917     albertel  649:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    650: 	if (!$opened) {
1.915     albertel  651: 	    return;
                    652: 	}
1.786     albertel  653: 	flock($idf,LOCK_SH);
                    654: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    655: 		&GDBM_READER(),0640)) {
                    656: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    657: 	    untie(%disk_env);
                    658: 	} else {
                    659: 	    $convert = 1;
                    660: 	}
                    661:     }
                    662:     if ($convert) {
                    663: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    664: 	    &logthis("Failed to load session, or convert session.");
                    665: 	}
1.374     www       666:     }
1.783     albertel  667: 
1.786     albertel  668:     my %remove;
1.783     albertel  669:     while ( my $envname = each(%env) ) {
1.433     matthew   670:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    671:             if ($time < time-300) {
1.783     albertel  672:                 $remove{$key}++;
1.433     matthew   673:             }
                    674:         }
                    675:     }
1.783     albertel  676: 
1.619     albertel  677:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  678:     $env_loaded=1;
1.783     albertel  679:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   680:         &delenv($expired_key);
1.374     www       681:     }
1.1       albertel  682: }
                    683: 
1.916     albertel  684: # ---------------------------------------------------- Check for valid session 
                    685: sub check_for_valid_session {
1.1172.2.96  raeburn   686:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  687:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1172.2.108  raeburn   688:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
1.1155    raeburn   689:     if ($name eq 'lonDAV') {
                    690:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    691:     } else {
                    692:         $lonidsdir=$r->dir_config('lonIDsDir');
1.1172.2.108  raeburn   693:         if ($name eq '') {
                    694:             $name = 'lonID';
                    695:         }
                    696:     }
                    697:     if ($name eq 'lonID') {
                    698:         $secure = 'lonSID';
                    699:         $linkname = 'lonLinkID';
                    700:         $pubname = 'lonPubID';
                    701:         if (exists($cookies{$secure})) {
                    702:             $lonid=$cookies{$secure};
                    703:         } elsif (exists($cookies{$name})) {
                    704:             $lonid=$cookies{$name};
                    705:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
                    706:             $lonid=$cookies{$linkname};
                    707:         } elsif (exists($cookies{$pubname})) {
                    708:             $lonid=$cookies{$pubname};
                    709:         }
                    710:     } else {
                    711:         $lonid=$cookies{$name};
                    712:     }
                    713:     return undef if (!$lonid);
                    714: 
                    715:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    716:     if (-l "$lonidsdir/$handle.id") {
                    717:         my $link = readlink("$lonidsdir/$handle.id");
                    718:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    719:             $handle = $1;
                    720:         }
1.1155    raeburn   721:     }
1.1172.2.96  raeburn   722:     if (!-e "$lonidsdir/$handle.id") {
                    723:         if ((ref($domref)) && ($name eq 'lonID') &&
                    724:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    725:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    726:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    727:                 $$domref = $possudom;
                    728:             }
                    729:         }
                    730:         return undef;
                    731:     }
1.916     albertel  732: 
1.917     albertel  733:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    734:     return undef if (!$opened);
1.916     albertel  735: 
                    736:     flock($idf,LOCK_SH);
                    737:     my %disk_env;
                    738:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    739: 	    &GDBM_READER(),0640)) {
                    740: 	return undef;	
                    741:     }
                    742: 
                    743:     if (!defined($disk_env{'user.name'})
                    744: 	|| !defined($disk_env{'user.domain'})) {
1.1172.2.107  raeburn   745:         untie(%disk_env);
1.916     albertel  746: 	return undef;
                    747:     }
1.1172.2.18  raeburn   748: 
1.1172.2.36  raeburn   749:     if (ref($userhashref) eq 'HASH') {
                    750:         $userhashref->{'name'} = $disk_env{'user.name'};
                    751:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1172.2.142  raeburn   752:         if ($disk_env{'request.role'}) {
                    753:             $userhashref->{'role'} = $disk_env{'request.role'};
                    754:         }
1.1172.2.146.  .13(raeb  755:-23):         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
                    756:-23):         if ($userhashref->{'lti'}) {
                    757:-23):             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
                    758:-23):             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
                    759:-23):         }
1.1172.2.18  raeburn   760:     }
1.1172.2.107  raeburn   761:     untie(%disk_env);
1.1172.2.18  raeburn   762: 
1.916     albertel  763:     return $handle;
                    764: }
                    765: 
1.830     albertel  766: sub timed_flock {
                    767:     my ($file,$lock_type) = @_;
                    768:     my $failed=0;
                    769:     eval {
                    770: 	local $SIG{__DIE__}='DEFAULT';
                    771: 	local $SIG{ALRM}=sub {
                    772: 	    $failed=1;
                    773: 	    die("failed lock");
                    774: 	};
                    775: 	alarm(13);
                    776: 	flock($file,$lock_type);
                    777: 	alarm(0);
                    778:     };
                    779:     if ($failed) {
                    780: 	return undef;
                    781:     } else {
                    782: 	return 1;
                    783:     }
                    784: }
                    785: 
1.1172.2.107  raeburn   786: sub get_sessionfile_vars {
                    787:     my ($handle,$lonidsdir,$storearr) = @_;
                    788:     my %returnhash;
                    789:     unless (ref($storearr) eq 'ARRAY') {
                    790:         return %returnhash;
                    791:     }
                    792:     if (-l "$lonidsdir/$handle.id") {
                    793:         my $link = readlink("$lonidsdir/$handle.id");
                    794:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    795:             $handle = $1;
                    796:         }
                    797:     }
                    798:     if ((-e "$lonidsdir/$handle.id") &&
                    799:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    800:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    801:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    802:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    803:                 flock($idf,LOCK_SH);
                    804:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    805:                         &GDBM_READER(),0640)) {
                    806:                     foreach my $item (@{$storearr}) {
                    807:                         $returnhash{$item} = $disk_env{$item};
                    808:                     }
                    809:                     untie(%disk_env);
                    810:                 }
                    811:             }
                    812:         }
                    813:     }
                    814:     return %returnhash;
                    815: }
                    816: 
1.5       www       817: # ---------------------------------------------------------- Append Environment
                    818: 
                    819: sub appenv {
1.949     raeburn   820:     my ($newenv,$roles) = @_;
                    821:     if (ref($newenv) eq 'HASH') {
                    822:         foreach my $key (keys(%{$newenv})) {
                    823:             my $refused = 0;
                    824: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    825:                 $refused = 1;
                    826:                 if (ref($roles) eq 'ARRAY') {
1.1172.2.40  raeburn   827:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   828:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    829:                         $refused = 0;
                    830:                     }
                    831:                 }
                    832:             }
                    833:             if ($refused) {
                    834:                 &logthis("<font color=\"blue\">WARNING: ".
                    835:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    836:                          .'</font>');
                    837: 	        delete($newenv->{$key});
                    838:             } else {
                    839:                 $env{$key}=$newenv->{$key};
                    840:             }
                    841:         }
1.1172.2.96  raeburn   842:         my $lonids = $perlvar{'lonIDsDir'};
                    843:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    844:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    845:             if ($opened
                    846: 	        && &timed_flock($env_file,LOCK_EX)
                    847: 	        &&
                    848: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    849: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    850: 	        while (my ($key,$value) = each(%{$newenv})) {
                    851: 	            $disk_env{$key} = $value;
                    852: 	        }
                    853: 	        untie(%disk_env);
                    854:             }
1.35      www       855:         }
1.191     harris41  856:     }
1.56      www       857:     return 'ok';
                    858: }
                    859: # ----------------------------------------------------- Delete from Environment
                    860: 
                    861: sub delenv {
1.1104    raeburn   862:     my ($delthis,$regexp,$roles) = @_;
                    863:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    864:         my $refused = 1;
                    865:         if (ref($roles) eq 'ARRAY') {
                    866:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    867:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    868:                 $refused = 0;
                    869:             }
                    870:         }
                    871:         if ($refused) {
                    872:             &logthis("<font color=\"blue\">WARNING: ".
                    873:                      "Attempt to delete from environment ".$delthis);
                    874:             return 'error';
                    875:         }
1.56      www       876:     }
1.917     albertel  877:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    878:     if ($opened
1.915     albertel  879: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  880: 	&&
                    881: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    882: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  883: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   884: 	    if ($regexp) {
                    885:                 if ($key=~/^$delthis/) {
                    886:                     delete($env{$key});
                    887:                     delete($disk_env{$key});
                    888:                 } 
                    889:             } else {
                    890:                 if ($key=~/^\Q$delthis\E/) {
                    891: 		    delete($env{$key});
                    892: 		    delete($disk_env{$key});
                    893: 	        }
                    894:             }
1.448     albertel  895: 	}
1.783     albertel  896: 	untie(%disk_env);
1.5       www       897:     }
                    898:     return 'ok';
1.369     albertel  899: }
                    900: 
1.790     albertel  901: sub get_env_multiple {
                    902:     my ($name) = @_;
                    903:     my @values;
                    904:     if (defined($env{$name})) {
                    905:         # exists is it an array
                    906:         if (ref($env{$name})) {
                    907:             @values=@{ $env{$name} };
                    908:         } else {
                    909:             $values[0]=$env{$name};
                    910:         }
                    911:     }
                    912:     return(@values);
                    913: }
                    914: 
1.958     www       915: # ------------------------------------------------------------------- Locking
                    916: 
                    917: sub set_lock {
                    918:     my ($text)=@_;
                    919:     $locknum++;
                    920:     my $id=$$.'-'.$locknum;
                    921:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    922:              'session.lock.'.$id => $text});
                    923:     return $id;
                    924: }
                    925: 
                    926: sub get_locks {
                    927:     my $num=0;
                    928:     my %texts=();
                    929:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    930:        if ($lock=~/\w/) {
                    931:           $num++;
                    932:           $texts{$lock}=$env{'session.lock.'.$lock};
                    933:        }
                    934:    }
                    935:    return ($num,%texts);
                    936: }
                    937: 
                    938: sub remove_lock {
                    939:     my ($id)=@_;
                    940:     my $newlocks='';
                    941:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    942:        if (($lock=~/\w/) && ($lock ne $id)) {
                    943:           $newlocks.=','.$lock;
                    944:        }
                    945:     }
                    946:     &appenv({'session.locks' => $newlocks});
                    947:     &delenv('session.lock.'.$id);
                    948: }
                    949: 
                    950: sub remove_all_locks {
                    951:     my $activelocks=$env{'session.locks'};
                    952:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    953:        if ($lock=~/\w/) {
                    954:           &remove_lock($lock);
                    955:        }
                    956:     }
                    957: }
                    958: 
                    959: 
1.369     albertel  960: # ------------------------------------------ Find out current server userload
                    961: sub userload {
                    962:     my $numusers=0;
                    963:     {
                    964: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    965: 	my $filename;
                    966: 	my $curtime=time;
                    967: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  968: 	    next if ($filename eq '.' || $filename eq '..');
                    969: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1172.2.112  raeburn   970:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel  971: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  972: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  973: 	}
                    974: 	closedir(LONIDS);
                    975:     }
                    976:     my $userloadpercent=0;
                    977:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    978:     if ($maxuserload) {
1.371     albertel  979: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  980:     }
1.372     albertel  981:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  982:     return $userloadpercent;
1.283     www       983: }
                    984: 
1.1       albertel  985: # ------------------------------ Find server with least workload from spare.tab
1.11      www       986: 
1.1       albertel  987: sub spareserver {
1.1172.2.142  raeburn   988:     my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  989:     my $spare_server;
1.370     albertel  990:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  991:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    992:                                                      :  $userloadpercent;
1.1083    raeburn   993:     my ($uint_dom,$remotesessions);
                    994:     if (($udom ne '') && (&domain($udom) ne '')) {
                    995:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    996:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    997:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    998:         $remotesessions = $udomdefaults{'remotesessions'};
                    999:     }
1.1123    raeburn  1000:     my $spareshash = &this_host_spares($udom);
                   1001:     if (ref($spareshash) eq 'HASH') {
                   1002:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1003:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1172.2.62  raeburn  1004:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                   1005:                                              $try_server));
1.1123    raeburn  1006: 	        ($spare_server, $lowest_load) =
                   1007: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                   1008:             }
1.1083    raeburn  1009:         }
1.784     albertel 1010: 
1.1123    raeburn  1011:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                   1012: 
                   1013:         if (!$found_server) {
                   1014:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                   1015: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1172.2.62  raeburn  1016:                     next unless (&spare_can_host($udom,$uint_dom,
                   1017:                                                  $remotesessions,$try_server));
1.1123    raeburn  1018: 	            ($spare_server, $lowest_load) =
                   1019: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                   1020:                 }
                   1021: 	    }
                   1022:         }
1.784     albertel 1023:     }
                   1024: 
                   1025:     if (!$want_server_name) {
1.1001    raeburn  1026:         if (defined($spare_server)) {
                   1027:             my $hostname = &hostname($spare_server);
1.1083    raeburn  1028:             if (defined($hostname)) {
1.1172.2.120  raeburn  1029:                 my $protocol = 'http';
                   1030:                 if ($protocol{$spare_server} eq 'https') {
                   1031:                     $protocol = $protocol{$spare_server};
                   1032:                 }
1.1172.2.142  raeburn  1033:                 my $alias = &Apache::lonnet::use_proxy_alias($r,$spare_server);
                   1034:                 $hostname = $alias if ($alias ne '');
1.1001    raeburn  1035: 	        $spare_server = $protocol.'://'.$hostname;
                   1036:             }
                   1037:         }
1.784     albertel 1038:     }
                   1039:     return $spare_server;
                   1040: }
                   1041: 
                   1042: sub compare_server_load {
1.1172.2.41  raeburn  1043:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                   1044: 
                   1045:     if ($required) {
                   1046:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   1047:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1048:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   1049:         if (($major eq '' && $minor eq '') ||
                   1050:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   1051:             return ($spare_server,$lowest_load);
                   1052:         }
                   1053:     }
1.784     albertel 1054: 
                   1055:     my $loadans     = &reply('load',    $try_server);
                   1056:     my $userloadans = &reply('userload',$try_server);
                   1057: 
                   1058:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn  1059: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel 1060:     }
                   1061: 
                   1062:     my $load;
                   1063:     if ($loadans =~ /\d/) {
                   1064: 	if ($userloadans =~ /\d/) {
                   1065: 	    #both are numbers, pick the bigger one
                   1066: 	    $load = ($loadans > $userloadans) ? $loadans 
                   1067: 		                              : $userloadans;
1.411     albertel 1068: 	} else {
1.784     albertel 1069: 	    $load = $loadans;
1.411     albertel 1070: 	}
1.784     albertel 1071:     } else {
                   1072: 	$load = $userloadans;
                   1073:     }
                   1074: 
                   1075:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1076: 	$spare_server = $try_server;
                   1077: 	$lowest_load  = $load;
1.370     albertel 1078:     }
1.784     albertel 1079:     return ($spare_server,$lowest_load);
1.202     matthew  1080: }
1.914     albertel 1081: 
                   1082: # --------------------------- ask offload servers if user already has a session
                   1083: sub find_existing_session {
                   1084:     my ($udom,$uname) = @_;
1.1123    raeburn  1085:     my $spareshash = &this_host_spares($udom);
                   1086:     if (ref($spareshash) eq 'HASH') {
                   1087:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1088:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1089:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1090:             }
                   1091:         }
                   1092:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1093:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1094:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1095:             }
                   1096:         }
1.914     albertel 1097:     }
                   1098:     return;
                   1099: }
                   1100: 
1.1172.2.146.  .13(raeb 1101:-23): sub delusersession {
                   1102:-23):     my ($lonid,$udom,$uname) = @_;
                   1103:-23):     my $uprimary_id = &domain($udom,'primary');
                   1104:-23):     my $uintdom = &internet_dom($uprimary_id);
                   1105:-23):     my $intdom = &internet_dom($lonid);
                   1106:-23):     my $serverhomedom = &host_domain($lonid);
                   1107:-23):     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1108:-23):         return &reply(join(':','delusersession',
                   1109:-23):                             map {&escape($_)} ($udom,$uname)),$lonid);
                   1110:-23):     }
                   1111:-23):     return;
                   1112:-23): }
                   1113:-23): 
                   1114:-23): 
1.1172.2.107  raeburn  1115: # check if user's browser sent load balancer cookie and server still has session
                   1116: # and is not overloaded.
                   1117: sub check_for_balancer_cookie {
                   1118:     my ($r,$update_mtime) = @_;
                   1119:     my ($otherserver,$cookie);
                   1120:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1121:     if (exists($cookies{'balanceID'})) {
                   1122:         my $balid = $cookies{'balanceID'};
                   1123:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1124:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1125:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1126:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1127:                 my ($possudom,$possuname) = ($1,$2);
                   1128:                 my $has_session = 0;
                   1129:                 if ((&domain($possudom) ne '') &&
                   1130:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1131:                     my $try_server;
                   1132:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1133:                     if ($opened) {
                   1134:                         flock($idf,LOCK_SH);
                   1135:                         while (my $line = <$idf>) {
                   1136:                             chomp($line);
                   1137:                             if (&hostname($line) ne '') {
                   1138:                                 $try_server = $line;
                   1139:                                 last;
                   1140:                             }
                   1141:                         }
                   1142:                         close($idf);
                   1143:                         if (($try_server) &&
                   1144:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1145:                             my $lowest_load = 30000;
                   1146:                             ($otherserver,$lowest_load) =
                   1147:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1148:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1149:                                 $has_session = 1;
                   1150:                             } else {
                   1151:                                 undef($otherserver);
                   1152:                             }
                   1153:                         }
                   1154:                     }
                   1155:                 }
                   1156:                 if ($has_session) {
                   1157:                     if ($update_mtime) {
                   1158:                         my $atime = my $mtime = time;
                   1159:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1160:                     }
                   1161:                 } else {
                   1162:                     unlink("$balancedir/$cookie.id");
                   1163:                 }
                   1164:             }
                   1165:         }
                   1166:     }
                   1167:     return ($otherserver,$cookie);
                   1168: }
                   1169: 
1.1172.2.130  raeburn  1170: sub updatebalcookie {
                   1171:     my ($cookie,$balancer,$lastentry)=@_;
                   1172:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1173:         my ($udom,$uname) = ($1,$2);
                   1174:         my $uprimary_id = &domain($udom,'primary');
                   1175:         my $uintdom = &internet_dom($uprimary_id);
                   1176:         my $intdom = &internet_dom($balancer);
                   1177:         my $serverhomedom = &host_domain($balancer);
                   1178:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1179:             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
                   1180:         }
                   1181:     }
                   1182:     return;
                   1183: }
                   1184: 
1.1172.2.107  raeburn  1185: sub delbalcookie {
                   1186:     my ($cookie,$balancer) =@_;
                   1187:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1188:         my ($udom,$uname) = ($1,$2);
                   1189:         my $uprimary_id = &domain($udom,'primary');
                   1190:         my $uintdom = &internet_dom($uprimary_id);
                   1191:         my $intdom = &internet_dom($balancer);
                   1192:         my $serverhomedom = &host_domain($balancer);
                   1193:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1172.2.130  raeburn  1194:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1172.2.107  raeburn  1195:         }
                   1196:     }
                   1197: }
                   1198: 
1.914     albertel 1199: # -------------------------------- ask if server already has a session for user
                   1200: sub has_user_session {
                   1201:     my ($lonid,$udom,$uname) = @_;
                   1202:     my $result = &reply(join(':','userhassession',
                   1203: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1204:     return 1 if ($result eq 'ok');
                   1205: 
                   1206:     return 0;
                   1207: }
                   1208: 
1.1076    raeburn  1209: # --------- determine least loaded server in a user's domain which allows login
                   1210: 
                   1211: sub choose_server {
1.1172.2.47  raeburn  1212:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1213:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1214:     my %servers = &get_servers($udom);
1.1076    raeburn  1215:     my $lowest_load = 30000;
1.1172.2.47  raeburn  1216:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1217:     if ($skiploadbal) {
                   1218:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1219:         unless (defined($cached)) {
                   1220:             my $cachetime = 60*60*24;
                   1221:             my %domconfig =
                   1222:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1223:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1224:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1225:                                            $cachetime);
                   1226:             }
                   1227:         }
                   1228:     }
1.1076    raeburn  1229:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn  1230:         my $loginvia;
1.1172.2.47  raeburn  1231:         if ($skiploadbal) {
                   1232:             if (ref($balancers) eq 'HASH') {
                   1233:                 next if (exists($balancers->{$lonhost}));
                   1234:             }
                   1235:         }
1.1115    raeburn  1236:         if ($checkloginvia) {
                   1237:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1238:             if ($loginvia) {
                   1239:                 my ($server,$path) = split(/:/,$loginvia);
                   1240:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1241:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1242:                 if ($login_host eq $server) {
                   1243:                     $portal_path = $path;
1.1151    raeburn  1244:                     $isredirect = 1;
1.1116    raeburn  1245:                 }
                   1246:             } else {
                   1247:                 ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1248:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1249:                 if ($login_host eq $lonhost) {
                   1250:                     $portal_path = '';
1.1151    raeburn  1251:                     $isredirect = ''; 
1.1116    raeburn  1252:                 }
                   1253:             }
                   1254:         } else {
1.1076    raeburn  1255:             ($login_host, $lowest_load) =
1.1172.2.41  raeburn  1256:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1257:         }
                   1258:     }
                   1259:     if ($login_host ne '') {
1.1116    raeburn  1260:         $hostname = &hostname($login_host);
1.1076    raeburn  1261:     }
1.1172.2.88  raeburn  1262:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1263: }
                   1264: 
1.1172.2.123  raeburn  1265: sub get_course_sessions {
                   1266:     my ($cnum,$cdom,$lastactivity) = @_;
                   1267:     my %servers = &internet_dom_servers($cdom);
                   1268:     my %returnhash;
                   1269:     foreach my $server (sort(keys(%servers))) {
                   1270:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
                   1271:         my @pairs=split(/\&/,$rep);
                   1272:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
                   1273:             foreach my $item (@pairs) {
                   1274:                 my ($key,$value)=split(/=/,$item,2);
                   1275:                 $key = &unescape($key);
                   1276:                 next if ($key =~ /^error: 2 /);
                   1277:                 if (exists($returnhash{$key})) {
                   1278:                     next if ($value < $returnhash{$key});
                   1279:                 }
                   1280:                 $returnhash{$key}=$value;
                   1281:             }
                   1282:         }
                   1283:     }
                   1284:     return %returnhash;
                   1285: }
                   1286: 
1.202     matthew  1287: # --------------------------------------------- Try to change a user's password
                   1288: 
                   1289: sub changepass {
1.799     raeburn  1290:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1291:     $currentpass = &escape($currentpass);
                   1292:     $newpass     = &escape($newpass);
1.1030    raeburn  1293:     my $lonhost = $perlvar{'lonHostID'};
                   1294:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1295: 		       $server);
                   1296:     if (! $answer) {
                   1297: 	&logthis("No reply on password change request to $server ".
                   1298: 		 "by $uname in domain $udom.");
                   1299:     } elsif ($answer =~ "^ok") {
                   1300:         &logthis("$uname in $udom successfully changed their password ".
                   1301: 		 "on $server.");
                   1302:     } elsif ($answer =~ "^pwchange_failure") {
                   1303: 	&logthis("$uname in $udom was unable to change their password ".
                   1304: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1305: 		 "or pwchange");
                   1306:     } elsif ($answer =~ "^non_authorized") {
                   1307:         &logthis("$uname in $udom did not get their password correct when ".
                   1308: 		 "attempting to change it on $server.");
                   1309:     } elsif ($answer =~ "^auth_mode_error") {
                   1310:         &logthis("$uname in $udom attempted to change their password despite ".
                   1311: 		 "not being locally or internally authenticated on $server.");
                   1312:     } elsif ($answer =~ "^unknown_user") {
                   1313:         &logthis("$uname in $udom attempted to change their password ".
                   1314: 		 "on $server but were unable to because $server is not ".
                   1315: 		 "their home server.");
                   1316:     } elsif ($answer =~ "^refused") {
                   1317: 	&logthis("$server refused to change $uname in $udom password because ".
                   1318: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1319:     } elsif ($answer =~ "invalid_client") {
                   1320:         &logthis("$server refused to change $uname in $udom password because ".
                   1321:                  "it was a reset by e-mail originating from an invalid server.");
1.1172.2.113  raeburn  1322:     } elsif ($answer =~ "^prioruse") {
                   1323:        &logthis("$server refused to change $uname in $udom password because ".
                   1324:                 "the password had been used before");
1.202     matthew  1325:     }
                   1326:     return $answer;
1.1       albertel 1327: }
                   1328: 
1.169     harris41 1329: # ----------------------- Try to determine user's current authentication scheme
                   1330: 
                   1331: sub queryauthenticate {
                   1332:     my ($uname,$udom)=@_;
1.456     albertel 1333:     my $uhome=&homeserver($uname,$udom);
1.1172.2.146.  .5(raebu 1334:22):     if ((!$uhome) || ($uhome eq 'no_host')) {
1.456     albertel 1335: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1336: 	return 'no_host';
                   1337:     }
                   1338:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1339:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1340: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1341:     }
1.456     albertel 1342:     return $answer;
1.169     harris41 1343: }
                   1344: 
1.1       albertel 1345: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1346: 
1.1       albertel 1347: sub authenticate {
1.1073    raeburn  1348:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1349:     $upass=&escape($upass);
                   1350:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1351:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1352:     my $newhome;
1.836     www      1353:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1354: # Maybe the machine was offline and only re-appeared again recently?
                   1355:         &reconlonc();
                   1356: # One more
1.952     raeburn  1357: 	$uhome=&homeserver($uname,$udom,1);
                   1358:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1359:             if (defined(&domain($udom,'primary'))) {
                   1360:                 $newhome=&domain($udom,'primary');
                   1361:             }
                   1362:             if ($newhome ne '') {
                   1363:                 $uhome = $newhome;
                   1364:             }
                   1365:         }
1.836     www      1366: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1367: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1368: 	    return 'no_host';
                   1369:         }
1.1       albertel 1370:     }
1.1073    raeburn  1371:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1372:     if ($answer eq 'authorized') {
1.952     raeburn  1373:         if ($newhome) {
                   1374:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1375:             return 'no_account_on_host'; 
                   1376:         } else {
                   1377:             &logthis("User $uname at $udom authorized by $uhome");
                   1378:             return $uhome;
                   1379:         }
1.471     albertel 1380:     }
                   1381:     if ($answer eq 'non_authorized') {
                   1382: 	&logthis("User $uname at $udom rejected by $uhome");
1.1172.2.146.  .5(raebu 1383:22): 	return 'no_host';
1.9       www      1384:     }
1.471     albertel 1385:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1386:     return 'no_host';
                   1387: }
                   1388: 
1.1172.2.146.  .6(raebu 1389:22): sub can_switchserver {
                   1390:22):     my ($udom,$home) = @_;
                   1391:22):     my ($canswitch,@intdoms);
                   1392:22):     my $internet_names = &get_internet_names($home);
                   1393:22):     if (ref($internet_names) eq 'ARRAY') {
                   1394:22):         @intdoms = @{$internet_names};
                   1395:22):     }
                   1396:22):     my $uint_dom = &internet_dom(&domain($udom,'primary'));
                   1397:22):     if ($uint_dom ne '' && grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1398:22):         $canswitch = 1;
                   1399:22):     } else {
                   1400:22):          my $serverhomeID = &get_server_homeID(&hostname($home));
                   1401:22):          my $serverhomedom = &host_domain($serverhomeID);
                   1402:22):          my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1403:22):          my %udomdefaults = &get_domain_defaults($udom);
                   1404:22):          my $remoterev = &get_server_loncaparev('',$home);
                   1405:22):          $canswitch = &can_host_session($udom,$home,$remoterev,
                   1406:22):                                         $udomdefaults{'remotesessions'},
                   1407:22):                                         $defdomdefaults{'hostedsessions'});
                   1408:22):     }
                   1409:22):     return $canswitch;
                   1410:22): }
                   1411:22): 
1.1073    raeburn  1412: sub can_host_session {
1.1074    raeburn  1413:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1414:     my $canhost = 1;
1.1074    raeburn  1415:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1416:     if (ref($remotesessions) eq 'HASH') {
                   1417:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1418:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1419:                 $canhost = 0;
                   1420:             } else {
                   1421:                 $canhost = 1;
                   1422:             }
                   1423:         }
                   1424:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1425:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1426:                 $canhost = 1;
                   1427:             } else {
                   1428:                 $canhost = 0;
                   1429:             }
                   1430:         }
                   1431:         if ($canhost) {
                   1432:             if ($remotesessions->{'version'} ne '') {
                   1433:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1434:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1435:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1436:                         my $major = $1;
                   1437:                         my $minor = $2;
                   1438:                         if (($major < $reqmajor ) ||
                   1439:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1440:                             $canhost = 0;
                   1441:                         }
                   1442:                     } else {
                   1443:                         $canhost = 0;
                   1444:                     }
                   1445:                 }
                   1446:             }
                   1447:         }
                   1448:     }
                   1449:     if ($canhost) {
                   1450:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1451:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1452:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1453:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1454:                 if (($uint_dom ne '') && 
                   1455:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1456:                     $canhost = 0;
                   1457:                 } else {
                   1458:                     $canhost = 1;
                   1459:                 }
                   1460:             }
                   1461:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1462:                 if (($uint_dom ne '') && 
                   1463:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1464:                     $canhost = 1;
                   1465:                 } else {
                   1466:                     $canhost = 0;
                   1467:                 }
                   1468:             }
                   1469:         }
                   1470:     }
                   1471:     return $canhost;
                   1472: }
                   1473: 
1.1083    raeburn  1474: sub spare_can_host {
                   1475:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1476:     my $canhost=1;
1.1172.2.62  raeburn  1477:     my $try_server_hostname = &hostname($try_server);
                   1478:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1479:     my $serverhomedom = &host_domain($serverhomeID);
                   1480:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1481:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1482:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1483:             $canhost = 0;
                   1484:         }
                   1485:     }
1.1172.2.136  raeburn  1486:     if ($canhost) {
                   1487:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
                   1488:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
                   1489:                 unless (&shared_institution($udom,$try_server)) {
                   1490:                     $canhost = 0;
                   1491:                 }
                   1492:             }
                   1493:         }
                   1494:     }
1.1172.2.62  raeburn  1495:     if (($canhost) && ($uint_dom)) {
                   1496:         my @intdoms;
                   1497:         my $internet_names = &get_internet_names($try_server);
                   1498:         if (ref($internet_names) eq 'ARRAY') {
                   1499:             @intdoms = @{$internet_names};
                   1500:         }
                   1501:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1502:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1503:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1504:                                          $remotesessions,
                   1505:                                          $defdomdefaults{'hostedsessions'});
                   1506:         }
1.1083    raeburn  1507:     }
                   1508:     return $canhost;
                   1509: }
                   1510: 
1.1123    raeburn  1511: sub this_host_spares {
                   1512:     my ($dom) = @_;
1.1126    raeburn  1513:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1514:     my @hosts = &current_machine_ids();
                   1515:     foreach my $lonhost (@hosts) {
                   1516:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1517:             $dom_in_use = $dom;
                   1518:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1519:             last;
                   1520:         }
                   1521:     }
1.1126    raeburn  1522:     if ($dom_in_use ne '') {
                   1523:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1524:     }
                   1525:     if (ref($result) ne 'HASH') {
                   1526:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1527:         $dom_in_use = &host_domain($lonhost_in_use);
                   1528:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1529:         if (ref($result) ne 'HASH') {
                   1530:             $result = \%spareid;
                   1531:         }
                   1532:     }
                   1533:     return $result;
                   1534: }
                   1535: 
                   1536: sub spares_for_offload  {
                   1537:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1538:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1539:     if (defined($cached)) {
                   1540:         return $result;
                   1541:     } else {
1.1126    raeburn  1542:         my $cachetime = 60*60*24;
                   1543:         my %domconfig =
                   1544:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1545:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1546:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1547:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1548:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1549:                 }
                   1550:             }
                   1551:         }
                   1552:     }
1.1126    raeburn  1553:     return;
1.1123    raeburn  1554: }
                   1555: 
1.1129    raeburn  1556: sub get_lonbalancer_config {
                   1557:     my ($servers) = @_;
                   1558:     my ($currbalancer,$currtargets);
                   1559:     if (ref($servers) eq 'HASH') {
                   1560:         foreach my $server (keys(%{$servers})) {
                   1561:             my %what = (
                   1562:                          spareid => 1,
                   1563:                          perlvar => 1,
                   1564:                        );
                   1565:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1566:             if ($result eq 'ok') {
                   1567:                 if (ref($returnhash) eq 'HASH') {
                   1568:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1569:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1570:                             $currbalancer = $server;
                   1571:                             $currtargets = {};
                   1572:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1573:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1574:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1575:                                 }
                   1576:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1577:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1578:                                 }
                   1579:                             }
                   1580:                             last;
                   1581:                         }
                   1582:                     }
                   1583:                 }
                   1584:             }
                   1585:         }
                   1586:     }
                   1587:     return ($currbalancer,$currtargets);
                   1588: }
                   1589: 
                   1590: sub check_loadbalancing {
1.1172.2.88  raeburn  1591:     my ($uname,$udom,$caller) = @_;
1.1172.2.12  raeburn  1592:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1172.2.107  raeburn  1593:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
1.1129    raeburn  1594:     my $lonhost = $perlvar{'lonHostID'};
1.1172.2.4  raeburn  1595:     my @hosts = &current_machine_ids();
1.1129    raeburn  1596:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1597:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1598:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1599:     my $serverhomedom = &host_domain($lonhost);
1.1172.2.75  raeburn  1600:     my $domneedscache; 
1.1129    raeburn  1601:     my $cachetime = 60*60*24;
                   1602: 
                   1603:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1604:         $dom_in_use = $udom;
                   1605:         $homeintdom = 1;
                   1606:     } else {
                   1607:         $dom_in_use = $serverhomedom;
                   1608:     }
                   1609:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1610:     unless (defined($cached)) {
                   1611:         my %domconfig =
                   1612:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1613:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1614:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1172.2.75  raeburn  1615:         } else {
                   1616:             $domneedscache = $dom_in_use;
1.1129    raeburn  1617:         }
                   1618:     }
                   1619:     if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1620:         ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1621:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1622:         if ($is_balancer) {
                   1623:             if (ref($currrules) eq 'HASH') {
                   1624:                 if ($homeintdom) {
                   1625:                     if ($uname ne '') {
                   1626:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1627:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1628:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1629:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1630:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1631:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1632:                             }
                   1633:                         }
                   1634:                         if ($rule_in_effect eq '') {
                   1635:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1636:                             if ($userenv{'inststatus'} ne '') {
                   1637:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1638:                                 my ($othertitle,$usertypes,$types) =
                   1639:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1640:                                 if (ref($types) eq 'ARRAY') {
                   1641:                                     foreach my $type (@{$types}) {
                   1642:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1643:                                             if (exists($currrules->{$type})) {
                   1644:                                                 $rule_in_effect = $currrules->{$type};
                   1645:                                             }
                   1646:                                         }
                   1647:                                     }
                   1648:                                 }
                   1649:                             } else {
                   1650:                                 if (exists($currrules->{'default'})) {
                   1651:                                     $rule_in_effect = $currrules->{'default'};
                   1652:                                 }
                   1653:                             }
                   1654:                         }
                   1655:                     } else {
                   1656:                         if (exists($currrules->{'default'})) {
                   1657:                             $rule_in_effect = $currrules->{'default'};
                   1658:                         }
                   1659:                     }
                   1660:                 } else {
                   1661:                     if ($currrules->{'_LC_external'} ne '') {
                   1662:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1663:                     }
                   1664:                 }
                   1665:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1666:                                                        $uname,$udom);
                   1667:             }
                   1668:         }
                   1669:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1172.2.35  raeburn  1670:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1671:         unless (defined($cached)) {
                   1672:             my %domconfig =
                   1673:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1674:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1172.2.75  raeburn  1675:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1676:             } else {
                   1677:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1678:             }
                   1679:         }
                   1680:         if (ref($result) eq 'HASH') {
1.1172.2.107  raeburn  1681:             ($is_balancer,$currtargets,$currrules,$setcookie) =
1.1172.2.12  raeburn  1682:                 &check_balancer_result($result,@hosts);
                   1683:             if ($is_balancer) {
1.1129    raeburn  1684:                 if (ref($currrules) eq 'HASH') {
                   1685:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1686:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1687:                     }
                   1688:                 }
                   1689:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1690:                                                        $uname,$udom);
                   1691:             }
                   1692:         } else {
                   1693:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1694:                 $is_balancer = 1;
                   1695:                 $offloadto = &this_host_spares($dom_in_use);
                   1696:             }
1.1172.2.75  raeburn  1697:             unless (defined($cached)) {
                   1698:                 $domneedscache = $serverhomedom;
                   1699:             }
1.1129    raeburn  1700:         }
                   1701:     } else {
                   1702:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1703:             $is_balancer = 1;
                   1704:             $offloadto = &this_host_spares($dom_in_use);
                   1705:         }
1.1172.2.75  raeburn  1706:         unless (defined($cached)) {
                   1707:             $domneedscache = $serverhomedom;
                   1708:         }
                   1709:     }
                   1710:     if ($domneedscache) {
                   1711:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1712:     }
1.1172.2.130  raeburn  1713:     if (($is_balancer) && ($caller ne 'switchserver')) {
1.1172.2.5  raeburn  1714:         my $lowest_load = 30000;
                   1715:         if (ref($offloadto) eq 'HASH') {
                   1716:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1717:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1718:                     ($otherserver,$lowest_load) =
                   1719:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1720:                 }
1.1129    raeburn  1721:             }
1.1172.2.5  raeburn  1722:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1723: 
1.1172.2.5  raeburn  1724:             if (!$found_server) {
                   1725:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1726:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1727:                         ($otherserver,$lowest_load) =
                   1728:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1729:                     }
                   1730:                 }
                   1731:             }
                   1732:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1733:             if (@{$offloadto} == 1) {
                   1734:                 $otherserver = $offloadto->[0];
                   1735:             } elsif (@{$offloadto} > 1) {
                   1736:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1737:                     ($otherserver,$lowest_load) =
                   1738:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1739:                 }
                   1740:             }
                   1741:         }
1.1172.2.88  raeburn  1742:         unless ($caller eq 'login') {
                   1743:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1744:                 $is_balancer = 0;
                   1745:                 if ($uname ne '' && $udom ne '') {
                   1746:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1747:                         &appenv({'user.loadbalexempt'     => $lonhost,
                   1748:                                  'user.loadbalcheck.time' => time});
                   1749:                     }
1.1172.2.5  raeburn  1750:                 }
1.1129    raeburn  1751:             }
                   1752:         }
1.1172.2.130  raeburn  1753:     }
                   1754:     if (($is_balancer) && (!$homeintdom)) {
                   1755:         undef($setcookie);
1.1129    raeburn  1756:     }
1.1172.2.107  raeburn  1757:     return ($is_balancer,$otherserver,$setcookie);
1.1129    raeburn  1758: }
                   1759: 
1.1172.2.12  raeburn  1760: sub check_balancer_result {
                   1761:     my ($result,@hosts) = @_;
1.1172.2.107  raeburn  1762:     my ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1763:     if (ref($result) eq 'HASH') {
                   1764:         if ($result->{'lonhost'} ne '') {
                   1765:             my $currbalancer = $result->{'lonhost'};
                   1766:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1767:                 $is_balancer = 1;
                   1768:                 $currtargets = $result->{'targets'};
                   1769:                 $currrules = $result->{'rules'};
                   1770:             }
                   1771:         } else {
                   1772:             foreach my $key (keys(%{$result})) {
                   1773:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1774:                     (ref($result->{$key}) eq 'HASH')) {
                   1775:                     $is_balancer = 1;
                   1776:                     $currrules = $result->{$key}{'rules'};
                   1777:                     $currtargets = $result->{$key}{'targets'};
1.1172.2.107  raeburn  1778:                     $setcookie = $result->{$key}{'cookie'};
1.1172.2.12  raeburn  1779:                     last;
                   1780:                 }
                   1781:             }
                   1782:         }
                   1783:     }
1.1172.2.107  raeburn  1784:     return ($is_balancer,$currtargets,$currrules,$setcookie);
1.1172.2.12  raeburn  1785: }
                   1786: 
1.1129    raeburn  1787: sub get_loadbalancer_targets {
                   1788:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1789:     my $offloadto;
1.1172.2.4  raeburn  1790:     if ($rule_in_effect eq 'none') {
                   1791:         return [$perlvar{'lonHostID'}];
                   1792:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1793:         $offloadto = $currtargets;
                   1794:     } else {
                   1795:         if ($rule_in_effect eq 'homeserver') {
                   1796:             my $homeserver = &homeserver($uname,$udom);
                   1797:             if ($homeserver ne 'no_host') {
                   1798:                 $offloadto = [$homeserver];
                   1799:             }
                   1800:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1801:             my %domconfig =
                   1802:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1803:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1804:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1805:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1806:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1807:                     }
                   1808:                 }
                   1809:             } else {
1.1172.2.7  raeburn  1810:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1811:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1812:                 if (&hostname($remotebalancer) ne '') {
                   1813:                     $offloadto = [$remotebalancer];
                   1814:                 }
                   1815:             }
                   1816:         } elsif (&hostname($rule_in_effect) ne '') {
                   1817:             $offloadto = [$rule_in_effect];
                   1818:         }
                   1819:     }
                   1820:     return $offloadto;
                   1821: }
                   1822: 
1.1127    raeburn  1823: sub internet_dom_servers {
                   1824:     my ($dom) = @_;
                   1825:     my (%uniqservers,%servers);
                   1826:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1827:     my @machinedoms = &machine_domains($primaryserver);
                   1828:     foreach my $mdom (@machinedoms) {
                   1829:         my %currservers = %servers;
                   1830:         my %server = &get_servers($mdom);
                   1831:         %servers = (%currservers,%server);
                   1832:     }
                   1833:     my %by_hostname;
                   1834:     foreach my $id (keys(%servers)) {
                   1835:         push(@{$by_hostname{$servers{$id}}},$id);
                   1836:     }
                   1837:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1838:         if (@{$by_hostname{$hostname}} > 1) {
                   1839:             my $match = 0;
                   1840:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1841:                 if (&host_domain($id) eq $dom) {
                   1842:                     $uniqservers{$id} = $hostname;
                   1843:                     $match = 1;
                   1844:                 }
                   1845:             }
                   1846:             unless ($match) {
                   1847:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1848:             }
                   1849:         } else {
                   1850:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1851:         }
                   1852:     }
                   1853:     return %uniqservers;
                   1854: }
                   1855: 
1.1       albertel 1856: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1857: 
1.599     albertel 1858: my %homecache;
1.1       albertel 1859: sub homeserver {
1.230     stredwic 1860:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1861:     my $index="$uname:$udom";
1.426     albertel 1862: 
1.599     albertel 1863:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1864: 
                   1865:     my %servers = &get_servers($udom,'library');
                   1866:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1867:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1868: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1869: 
                   1870: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1871: 	if ($answer eq 'found') {
                   1872: 	    delete($badServerCache{$tryserver}); 
                   1873: 	    return $homecache{$index}=$tryserver;
                   1874: 	} elsif ($answer eq 'no_host') {
                   1875: 	    $badServerCache{$tryserver}=1;
                   1876: 	}
1.1       albertel 1877:     }    
                   1878:     return 'no_host';
1.70      www      1879: }
                   1880: 
                   1881: # ------------------------------------- Find the usernames behind a list of IDs
                   1882: 
                   1883: sub idget {
                   1884:     my ($udom,@ids)=@_;
                   1885:     my %returnhash=();
                   1886:     
1.841     albertel 1887:     my %servers = &get_servers($udom,'library');
                   1888:     foreach my $tryserver (keys(%servers)) {
1.1172.2.73  raeburn  1889: 	my $idlist=join('&', map { &escape($_); } @ids);
1.841     albertel 1890: 	$idlist=~tr/A-Z/a-z/; 
                   1891: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1892: 	my @answer=();
                   1893: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1894: 	    @answer=split(/\&/,$reply);
                   1895: 	}                    ;
                   1896: 	my $i;
                   1897: 	for ($i=0;$i<=$#ids;$i++) {
                   1898: 	    if ($answer[$i]) {
1.1172.2.73  raeburn  1899: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.841     albertel 1900: 	    } 
                   1901: 	}
                   1902:     } 
1.70      www      1903:     return %returnhash;
                   1904: }
                   1905: 
                   1906: # ------------------------------------- Find the IDs behind a list of usernames
                   1907: 
                   1908: sub idrget {
                   1909:     my ($udom,@unames)=@_;
                   1910:     my %returnhash=();
1.800     albertel 1911:     foreach my $uname (@unames) {
                   1912:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1913:     }
1.70      www      1914:     return %returnhash;
                   1915: }
                   1916: 
                   1917: # ------------------------------- Store away a list of names and associated IDs
                   1918: 
                   1919: sub idput {
                   1920:     my ($udom,%ids)=@_;
                   1921:     my %servers=();
1.800     albertel 1922:     foreach my $uname (keys(%ids)) {
                   1923: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1924:         my $uhom=&homeserver($uname,$udom);
1.70      www      1925:         if ($uhom ne 'no_host') {
1.800     albertel 1926:             my $id=&escape($ids{$uname});
1.70      www      1927:             $id=~tr/A-Z/a-z/;
1.800     albertel 1928:             my $esc_unam=&escape($uname);
1.70      www      1929: 	    if ($servers{$uhom}) {
1.800     albertel 1930: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1931:             } else {
1.800     albertel 1932:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1933:             }
                   1934:         }
1.191     harris41 1935:     }
1.800     albertel 1936:     foreach my $server (keys(%servers)) {
                   1937:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1938:     }
1.344     www      1939: }
                   1940: 
1.1172.2.30  raeburn  1941: # ---------------------------------------- Delete unwanted IDs from ids.db file
                   1942: 
                   1943: sub iddel {
                   1944:     my ($udom,$idshashref,$uhome)=@_;
                   1945:     my %result=();
                   1946:     unless (ref($idshashref) eq 'HASH') {
                   1947:         return %result;
                   1948:     }
                   1949:     my %servers=();
                   1950:     while (my ($id,$uname) = each(%{$idshashref})) {
                   1951:         my $uhom;
                   1952:         if ($uhome) {
                   1953:             $uhom = $uhome;
                   1954:         } else {
                   1955:             $uhom=&homeserver($uname,$udom);
                   1956:         }
                   1957:         if ($uhom ne 'no_host') {
                   1958:             if ($servers{$uhom}) {
                   1959:                 $servers{$uhom}.='&'.&escape($id);
                   1960:             } else {
                   1961:                 $servers{$uhom}=&escape($id);
                   1962:             }
                   1963:         }
                   1964:     }
                   1965:     foreach my $server (keys(%servers)) {
                   1966:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1967:     }
                   1968:     return %result;
                   1969: }
                   1970: 
1.1023    raeburn  1971: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1972: sub dump_dom {
1.1165    droeschl 1973:     my ($namespace, $udom, $regexp) = @_;
                   1974: 
                   1975:     $udom ||= $env{'user.domain'};
                   1976: 
                   1977:     return () unless $udom;
                   1978: 
                   1979:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1980: }
                   1981: 
1.1023    raeburn  1982: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1983: 
                   1984: sub get_dom {
1.1172.2.146.  .1(raebu 1985:22):     my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
1.1172.2.57  raeburn  1986:     return if ($udom eq 'public');
1.806     raeburn  1987:     my $items='';
                   1988:     foreach my $item (@$storearr) {
                   1989:         $items.=&escape($item).'&';
                   1990:     }
                   1991:     $items=~s/\&$//;
1.860     raeburn  1992:     if (!$udom) {
                   1993:         $udom=$env{'user.domain'};
1.1172.2.57  raeburn  1994:         return if ($udom eq 'public');
1.860     raeburn  1995:         if (defined(&domain($udom,'primary'))) {
                   1996:             $uhome=&domain($udom,'primary');
                   1997:         } else {
1.874     albertel 1998:             undef($uhome);
1.860     raeburn  1999:         }
                   2000:     } else {
                   2001:         if (!$uhome) {
                   2002:             if (defined(&domain($udom,'primary'))) {
                   2003:                 $uhome=&domain($udom,'primary');
                   2004:             }
                   2005:         }
                   2006:     }
                   2007:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1172.2.139  raeburn  2008:         my $rep;
                   2009:         if (grep { $_ eq $uhome } &current_machine_ids()) {
                   2010:             # domain information is hosted on this machine
                   2011:             $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
1.1172.2.146.  .1(raebu 2012:22):         } else {
                   2013:22):             if ($encrypt) {
                   2014:22):                 $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   2015:22):             } else {
                   2016:22):                 $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   2017:22):             }
1.1172.2.139  raeburn  2018:         }
1.866     raeburn  2019:         my %returnhash;
1.875     albertel 2020:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  2021:             return %returnhash;
                   2022:         }
1.806     raeburn  2023:         my @pairs=split(/\&/,$rep);
                   2024:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2025:             return @pairs;
                   2026:         }
                   2027:         my $i=0;
                   2028:         foreach my $item (@$storearr) {
                   2029:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   2030:             $i++;
                   2031:         }
                   2032:         return %returnhash;
                   2033:     } else {
1.880     banghart 2034:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  2035:     }
                   2036: }
                   2037: 
                   2038: # -------------------------------------------- put items in domain db files 
                   2039: 
                   2040: sub put_dom {
1.1172.2.146.  .1(raebu 2041:22):     my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
1.860     raeburn  2042:     if (!$udom) {
                   2043:         $udom=$env{'user.domain'};
                   2044:         if (defined(&domain($udom,'primary'))) {
                   2045:             $uhome=&domain($udom,'primary');
                   2046:         } else {
1.874     albertel 2047:             undef($uhome);
1.860     raeburn  2048:         }
                   2049:     } else {
                   2050:         if (!$uhome) {
                   2051:             if (defined(&domain($udom,'primary'))) {
                   2052:                 $uhome=&domain($udom,'primary');
                   2053:             }
                   2054:         }
                   2055:     } 
                   2056:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  2057:         my $items='';
                   2058:         foreach my $item (keys(%$storehash)) {
                   2059:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   2060:         }
                   2061:         $items=~s/\&$//;
1.1172.2.146.  .1(raebu 2062:22):         if ($encrypt) {
                   2063:22):             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   2064:22):         } else {
                   2065:22):             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   2066:22):         }
1.806     raeburn  2067:     } else {
1.860     raeburn  2068:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  2069:     }
                   2070: }
                   2071: 
1.1023    raeburn  2072: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  2073: sub newput_dom {
1.1023    raeburn  2074:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  2075:     my $result;
                   2076:     if (!$udom) {
                   2077:         $udom=$env{'user.domain'};
                   2078:     }
1.1023    raeburn  2079:     if ($udom) {
                   2080:         my $uname = &get_domainconfiguser($udom);
                   2081:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2082:     }
                   2083:     return $result;
                   2084: }
                   2085: 
1.1023    raeburn  2086: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2087: sub del_dom {
1.1023    raeburn  2088:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2089:     if (ref($storearr) eq 'ARRAY') {
                   2090:         if (!$udom) {
                   2091:             $udom=$env{'user.domain'};
                   2092:         }
1.1023    raeburn  2093:         if ($udom) {
                   2094:             my $uname = &get_domainconfiguser($udom); 
                   2095:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2096:         }
                   2097:     }
                   2098: }
                   2099: 
1.1172.2.146.  .4(raebu 2100:22): sub store_dom {
                   2101:22):     my ($storehash,$id,$namespace,$dom,$home,$encrypt) = @_;
                   2102:22):     $$storehash{'ip'}=&get_requestor_ip();
                   2103:22):     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2104:22):     my $namevalue='';
                   2105:22):     foreach my $key (keys(%{$storehash})) {
                   2106:22):         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   2107:22):     }
                   2108:22):     $namevalue=~s/\&$//;
                   2109:22):     if (grep { $_ eq $home } current_machine_ids()) {
                   2110:22):         return LONCAPA::Lond::store_dom("storedom:$dom:$namespace:$id:$namevalue");
                   2111:22):     } else {
                   2112:22):         if ($namespace eq 'private') {
                   2113:22):             return 'refused';
                   2114:22):         } elsif ($encrypt) {
                   2115:22):             return reply("encrypt:storedom:$dom:$namespace:$id:$namevalue",$home);
                   2116:22):         } else {
                   2117:22):             return reply("storedom:$dom:$namespace:$id:$namevalue",$home);
                   2118:22):         }
                   2119:22):     }
                   2120:22): }
                   2121:22): 
                   2122:22): sub restore_dom {
                   2123:22):     my ($id,$namespace,$dom,$home,$encrypt) = @_;
                   2124:22):     my $answer;
                   2125:22):     if (grep { $_ eq $home } current_machine_ids()) {
                   2126:22):         $answer = LONCAPA::Lond::restore_dom("restoredom:$dom:$namespace:$id");
                   2127:22):     } elsif ($namespace ne 'private') {
                   2128:22):         if ($encrypt) {
                   2129:22):             $answer=&reply("encrypt:restoredom:$dom:$namespace:$id",$home);
                   2130:22):         } else {
                   2131:22):             $answer=&reply("restoredom:$dom:$namespace:$id",$home);
                   2132:22):         }
                   2133:22):     }
                   2134:22):     my %returnhash=();
                   2135:22):     unless (($answer eq '') || ($answer eq 'con_lost') || ($answer eq 'refused') ||
                   2136:22):             ($answer eq 'unknown_cmd') || ($answer eq 'rejected')) {
                   2137:22):         foreach my $line (split(/\&/,$answer)) {
                   2138:22):             my ($name,$value)=split(/\=/,$line);
                   2139:22):             $returnhash{&unescape($name)}=&thaw_unescape($value);
                   2140:22):         }
                   2141:22):         my $version;
                   2142:22):         for ($version=1;$version<=$returnhash{'version'};$version++) {
                   2143:22):             foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   2144:22):                 $returnhash{$item}=$returnhash{$version.':'.$item};
                   2145:22):             }
                   2146:22):         }
                   2147:22):     }
                   2148:22):     return %returnhash;
                   2149:22): }
                   2150:22): 
1.1023    raeburn  2151: # ----------------------------------construct domainconfig user for a domain 
                   2152: sub get_domainconfiguser {
                   2153:     my ($udom) = @_;
                   2154:     return $udom.'-domainconfig';
                   2155: }
                   2156: 
1.837     raeburn  2157: sub retrieve_inst_usertypes {
                   2158:     my ($udom) = @_;
                   2159:     my (%returnhash,@order);
1.989     raeburn  2160:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2161:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2162:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1172.2.44  raeburn  2163:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2164:     } else {
                   2165:         if (defined(&domain($udom,'primary'))) {
                   2166:             my $uhome=&domain($udom,'primary');
                   2167:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2168:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1172.2.44  raeburn  2169:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2170:                 return (\%returnhash,\@order);
                   2171:             }
                   2172:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2173:             my @pairs=split(/\&/,$hashitems);
                   2174:             foreach my $item (@pairs) {
                   2175:                 my ($key,$value)=split(/=/,$item,2);
                   2176:                 $key = &unescape($key);
                   2177:                 next if ($key =~ /^error: 2 /);
                   2178:                 $returnhash{$key}=&thaw_unescape($value);
                   2179:             }
                   2180:             my @esc_order = split(/\&/,$orderitems);
                   2181:             foreach my $item (@esc_order) {
                   2182:                 push(@order,&unescape($item));
                   2183:             }
                   2184:         } else {
1.1172.2.44  raeburn  2185:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2186:         }
1.1172.2.44  raeburn  2187:         return (\%returnhash,\@order);
1.837     raeburn  2188:     }
                   2189: }
                   2190: 
1.868     raeburn  2191: sub is_domainimage {
                   2192:     my ($url) = @_;
1.1172.2.142  raeburn  2193:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
1.868     raeburn  2194:         if (&domain($1) ne '') {
                   2195:             return '1';
                   2196:         }
                   2197:     }
                   2198:     return;
                   2199: }
                   2200: 
1.899     raeburn  2201: sub inst_directory_query {
                   2202:     my ($srch) = @_;
                   2203:     my $udom = $srch->{'srchdomain'};
                   2204:     my %results;
                   2205:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2206:     my $outcome;
1.899     raeburn  2207:     if ($homeserver ne '') {
1.1172.2.116  raeburn  2208:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2209:             if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2210:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1172.2.116  raeburn  2211:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
                   2212:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2213:                     (($major == 2) && ($minor < 11)) ||
                   2214:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
                   2215:                     return;
                   2216:                 }
                   2217:             }
                   2218:         }
1.904     albertel 2219: 	my $queryid=&reply("querysend:instdirsearch:".
                   2220: 			   &escape($srch->{'srchby'}).':'.
                   2221: 			   &escape($srch->{'srchterm'}).':'.
                   2222: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2223: 	my $host=&hostname($homeserver);
                   2224: 	if ($queryid !~/^\Q$host\E\_/) {
1.1172.2.96  raeburn  2225: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2226: 	    return;
                   2227: 	}
                   2228: 	my $response = &get_query_reply($queryid);
                   2229: 	my $maxtries = 5;
                   2230: 	my $tries = 1;
                   2231: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2232: 	    $response = &get_query_reply($queryid);
                   2233: 	    $tries ++;
                   2234: 	}
                   2235: 
                   2236:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2237:             if ($response eq 'unavailable') {
                   2238:                 $outcome = $response;
                   2239:             } else {
                   2240:                 $outcome = 'ok';
                   2241:                 my @matches = split(/\n/,$response);
                   2242:                 foreach my $match (@matches) {
                   2243:                     my ($key,$value) = split(/=/,$match);
                   2244:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2245:                 }
1.899     raeburn  2246:             }
                   2247:         }
                   2248:     }
1.909     raeburn  2249:     return ($outcome,%results);
1.899     raeburn  2250: }
                   2251: 
                   2252: sub usersearch {
                   2253:     my ($srch) = @_;
                   2254:     my $dom = $srch->{'srchdomain'};
                   2255:     my %results;
                   2256:     my %libserv = &all_library();
                   2257:     my $query = 'usersearch';
                   2258:     foreach my $tryserver (keys(%libserv)) {
                   2259:         if (&host_domain($tryserver) eq $dom) {
1.1172.2.116  raeburn  2260:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2261:                 if ($srch->{'srchby'} eq 'email') {
1.1172.2.117  raeburn  2262:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1172.2.119  raeburn  2263:                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
1.1172.2.116  raeburn  2264:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2265:                              (($major == 2) && ($minor < 11)) ||
                   2266:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
                   2267:                 }
                   2268:             }
1.899     raeburn  2269:             my $host=&hostname($tryserver);
                   2270:             my $queryid=
1.911     raeburn  2271:                 &reply("querysend:".&escape($query).':'.
                   2272:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2273:                        &escape($srch->{'srchtype'}).':'.
                   2274:                        &escape($srch->{'srchterm'}),$tryserver);
                   2275:             if ($queryid !~/^\Q$host\E\_/) {
                   2276:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2277:                 next;
1.899     raeburn  2278:             }
                   2279:             my $reply = &get_query_reply($queryid);
                   2280:             my $maxtries = 1;
                   2281:             my $tries = 1;
                   2282:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2283:                 $reply = &get_query_reply($queryid);
                   2284:                 $tries ++;
                   2285:             }
                   2286:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2287:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2288:             } else {
1.911     raeburn  2289:                 my @matches;
                   2290:                 if ($reply =~ /\n/) {
                   2291:                     @matches = split(/\n/,$reply);
                   2292:                 } else {
                   2293:                     @matches = split(/\&/,$reply);
                   2294:                 }
1.899     raeburn  2295:                 foreach my $match (@matches) {
                   2296:                     my ($uname,$udom,%userhash);
1.911     raeburn  2297:                     foreach my $entry (split(/:/,$match)) {
                   2298:                         my ($key,$value) =
                   2299:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2300:                         $userhash{$key} = $value;
                   2301:                         if ($key eq 'username') {
                   2302:                             $uname = $value;
                   2303:                         } elsif ($key eq 'domain') {
                   2304:                             $udom = $value;
1.911     raeburn  2305:                         }
1.899     raeburn  2306:                     }
                   2307:                     $results{$uname.':'.$udom} = \%userhash;
                   2308:                 }
                   2309:             }
                   2310:         }
                   2311:     }
                   2312:     return %results;
                   2313: }
                   2314: 
1.912     raeburn  2315: sub get_instuser {
                   2316:     my ($udom,$uname,$id) = @_;
                   2317:     my $homeserver = &domain($udom,'primary');
                   2318:     my ($outcome,%results);
                   2319:     if ($homeserver ne '') {
                   2320:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2321:                            &escape($id).':'.&escape($udom),$homeserver);
                   2322:         my $host=&hostname($homeserver);
                   2323:         if ($queryid !~/^\Q$host\E\_/) {
                   2324:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2325:             return;
                   2326:         }
                   2327:         my $response = &get_query_reply($queryid);
                   2328:         my $maxtries = 5;
                   2329:         my $tries = 1;
                   2330:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2331:             $response = &get_query_reply($queryid);
                   2332:             $tries ++;
                   2333:         }
                   2334:         if (!&error($response) && $response ne 'refused') {
                   2335:             if ($response eq 'unavailable') {
                   2336:                 $outcome = $response;
                   2337:             } else {
                   2338:                 $outcome = 'ok';
                   2339:                 my @matches = split(/\n/,$response);
                   2340:                 foreach my $match (@matches) {
                   2341:                     my ($key,$value) = split(/=/,$match);
                   2342:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2343:                 }
                   2344:             }
                   2345:         }
                   2346:     }
                   2347:     my %userinfo;
                   2348:     if (ref($results{$uname}) eq 'HASH') {
                   2349:         %userinfo = %{$results{$uname}};
                   2350:     } 
                   2351:     return ($outcome,%userinfo);
                   2352: }
                   2353: 
1.1172.2.69  raeburn  2354: sub get_multiple_instusers {
                   2355:     my ($udom,$users,$caller) = @_;
                   2356:     my ($outcome,$results);
                   2357:     if (ref($users) eq 'HASH') {
                   2358:         my $count = keys(%{$users});
                   2359:         my $requested = &freeze_escape($users);
                   2360:         my $homeserver = &domain($udom,'primary');
                   2361:         if ($homeserver ne '') {
                   2362:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2363:             my $host=&hostname($homeserver);
                   2364:             if ($queryid !~/^\Q$host\E\_/) {
                   2365:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2366:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2367:                 return ($outcome,$results);
                   2368:             }
                   2369:             my $response = &get_query_reply($queryid);
                   2370:             my $maxtries = 5;
                   2371:             if ($count > 100) {
                   2372:                 $maxtries = 1+int($count/20);
                   2373:             }
                   2374:             my $tries = 1;
                   2375:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2376:                 $response = &get_query_reply($queryid);
                   2377:                 $tries ++;
                   2378:             }
                   2379:             if ($response eq '') {
                   2380:                 $results = {};
                   2381:                 foreach my $key (keys(%{$users})) {
                   2382:                     my ($uname,$id);
                   2383:                     if ($caller eq 'id') {
                   2384:                         $id = $key;
                   2385:                     } else {
                   2386:                         $uname = $key;
                   2387:                     }
                   2388:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
                   2389:                     $outcome = $resp;
                   2390:                     if ($resp eq 'ok') {
                   2391:                         %{$results} = (%{$results}, %info);
                   2392:                     } else {
                   2393:                         last;
                   2394:                     }
                   2395:                 }
                   2396:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2397:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2398:                     $outcome = $response;
                   2399:                 } else {
                   2400:                     ($outcome,my $userdata) = split(/=/,$response,2);
                   2401:                     if ($outcome eq 'ok') {
                   2402:                         $results = &thaw_unescape($userdata);
                   2403:                     }
                   2404:                 }
                   2405:             }
                   2406:         }
                   2407:     }
                   2408:     return ($outcome,$results);
                   2409: }
                   2410: 
1.912     raeburn  2411: sub inst_rulecheck {
1.923     raeburn  2412:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2413:     my %returnhash;
                   2414:     if ($udom ne '') {
                   2415:         if (ref($rules) eq 'ARRAY') {
                   2416:             @{$rules} = map {&escape($_);} (@{$rules});
                   2417:             my $rulestr = join(':',@{$rules});
                   2418:             my $homeserver=&domain($udom,'primary');
                   2419:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2420:                 my $response;
                   2421:                 if ($item eq 'username') {                
                   2422:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2423:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2424:                                               $homeserver));
1.923     raeburn  2425:                 } elsif ($item eq 'id') {
                   2426:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2427:                                               ':'.&escape($id).':'.$rulestr,
                   2428:                                               $homeserver));
1.1172.2.146.  .5(raebu 2429:22):                 } elsif ($item eq 'unamemap') {
                   2430:22):                     $response=&unescape(&reply('instunamemapcheck:'.
                   2431:22):                                                &escape($udom).':'.&escape($uname).
                   2432:22):                                               ':'.$rulestr,$homeserver));
1.945     raeburn  2433:                 } elsif ($item eq 'selfcreate') {
                   2434:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2435:                                                &escape($udom).':'.&escape($uname).
                   2436:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2437:                 }
1.912     raeburn  2438:                 if ($response ne 'refused') {
                   2439:                     my @pairs=split(/\&/,$response);
                   2440:                     foreach my $item (@pairs) {
                   2441:                         my ($key,$value)=split(/=/,$item,2);
                   2442:                         $key = &unescape($key);
                   2443:                         next if ($key =~ /^error: 2 /);
                   2444:                         $returnhash{$key}=&thaw_unescape($value);
                   2445:                     }
                   2446:                 }
                   2447:             }
                   2448:         }
                   2449:     }
                   2450:     return %returnhash;
                   2451: }
                   2452: 
                   2453: sub inst_userrules {
1.923     raeburn  2454:     my ($udom,$check) = @_;
1.912     raeburn  2455:     my (%ruleshash,@ruleorder);
                   2456:     if ($udom ne '') {
                   2457:         my $homeserver=&domain($udom,'primary');
                   2458:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2459:             my $response;
                   2460:             if ($check eq 'id') {
                   2461:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2462:                                  $homeserver);
1.943     raeburn  2463:             } elsif ($check eq 'email') {
                   2464:                 $response=&reply('instemailrules:'.&escape($udom),
                   2465:                                  $homeserver);
1.1172.2.146.  .5(raebu 2466:22):             } elsif ($check eq 'unamemap') {
                   2467:22):                 $response=&reply('unamemaprules:'.&escape($udom),
                   2468:22):                                  $homeserver);
1.923     raeburn  2469:             } else {
                   2470:                 $response=&reply('instuserrules:'.&escape($udom),
                   2471:                                  $homeserver);
                   2472:             }
1.912     raeburn  2473:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2474:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2475:                 ($response ne 'no_such_host')) {
                   2476:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2477:                 my @pairs=split(/\&/,$hashitems);
                   2478:                 foreach my $item (@pairs) {
                   2479:                     my ($key,$value)=split(/=/,$item,2);
                   2480:                     $key = &unescape($key);
                   2481:                     next if ($key =~ /^error: 2 /);
                   2482:                     $ruleshash{$key}=&thaw_unescape($value);
                   2483:                 }
                   2484:                 my @esc_order = split(/\&/,$orderitems);
                   2485:                 foreach my $item (@esc_order) {
                   2486:                     push(@ruleorder,&unescape($item));
                   2487:                 }
                   2488:             }
                   2489:         }
                   2490:     }
                   2491:     return (\%ruleshash,\@ruleorder);
                   2492: }
                   2493: 
1.976     raeburn  2494: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2495: 
                   2496: sub get_domain_defaults {
1.1172.2.35  raeburn  2497:     my ($domain,$ignore_cache) = @_;
                   2498:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2499:     my $cachetime = 60*60*24;
1.1172.2.35  raeburn  2500:     unless ($ignore_cache) {
                   2501:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2502:         if (defined($cached)) {
                   2503:             if (ref($result) eq 'HASH') {
                   2504:                 return %{$result};
                   2505:             }
1.943     raeburn  2506:         }
                   2507:     }
                   2508:     my %domdefaults;
                   2509:     my %domconfig =
1.989     raeburn  2510:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2511:                                   'requestcourses','inststatus',
1.1172.2.9  raeburn  2512:                                   'coursedefaults','usersessions',
1.1172.2.46  raeburn  2513:                                   'requestauthor','selfenrollment',
1.1172.2.89  raeburn  2514:                                   'coursecategories','autoenroll',
1.1172.2.146.  .13(raeb 2515:-23):                                   'helpsettings','wafproxy','ltisec',
                   2516:-23):                                   'toolsec','domexttool','exttool'],
                   2517:-23):                                   $domain);
1.1172.2.41  raeburn  2518:     my @coursetypes = ('official','unofficial','community','textbook');
1.943     raeburn  2519:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2520:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2521:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2522:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2523:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2524:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2525:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1172.2.146.  .12(raeb 2526:-23):         $domdefaults{'portal_def_email'} = $domconfig{'defaults'}{'portal_def_email'};
                   2527:-23):         $domdefaults{'portal_def_web'} = $domconfig{'defaults'}{'portal_def_web'};
1.1172.2.91  raeburn  2528:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2529:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2530:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.1172.2.146.  .5(raebu 2531:22):         $domdefaults{'unamemap_rule'} = $domconfig{'defaults'}{'unamemap_rule'};
1.943     raeburn  2532:     } else {
                   2533:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2534:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2535:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2536:     }
1.976     raeburn  2537:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2538:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2539:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2540:         } else {
                   2541:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1172.2.29  raeburn  2542:         }
1.1172.2.6  raeburn  2543:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2544:         foreach my $item (@usertools) {
                   2545:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2546:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2547:             }
                   2548:         }
1.1172.2.29  raeburn  2549:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2550:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2551:         }
1.976     raeburn  2552:     }
1.985     raeburn  2553:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1172.2.37  raeburn  2554:         foreach my $item ('official','unofficial','community','textbook') {
1.985     raeburn  2555:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2556:         }
                   2557:     }
1.1172.2.9  raeburn  2558:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2559:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2560:     }
1.989     raeburn  2561:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1172.2.44  raeburn  2562:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2563:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2564:         }
                   2565:     }
1.1047    raeburn  2566:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1172.2.60  raeburn  2567:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
1.1172.2.144  raeburn  2568:         $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
1.1172.2.60  raeburn  2569:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2570:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2571:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2572:         }
1.1172.2.41  raeburn  2573:         foreach my $type (@coursetypes) {
                   2574:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2575:                 unless ($type eq 'community') {
                   2576:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2577:                 }
                   2578:             }
                   2579:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2580:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2581:             }
1.1172.2.146.  .14(raeb 2582:-23):             if (ref($domconfig{'coursedefaults'}{'coursequota'}) eq 'HASH') {
                   2583:-23):                 $domdefaults{$type.'coursequota'} = $domconfig{'coursedefaults'}{'coursequota'}{$type};
                   2584:-23):             }
1.1172.2.60  raeburn  2585:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2586:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2587:                     $domdefaults{$type.'postsubtimeout'} =
                   2588:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
                   2589:                 }
                   2590:             }
1.1172.2.146.  .13(raeb 2591:-23):             if (ref($domconfig{'coursedefaults'}{'domexttool'}) eq 'HASH') {
                   2592:-23):                 $domdefaults{$type.'domexttool'} = $domconfig{'coursedefaults'}{'domexttool'}{$type};
                   2593:-23):             } else {
                   2594:-23):                 $domdefaults{$type.'domexttool'} = 1;
                   2595:-23):             }
                   2596:-23):             if (ref($domconfig{'coursedefaults'}{'exttool'}) eq 'HASH') {
                   2597:-23):                 $domdefaults{$type.'exttool'} = $domconfig{'coursedefaults'}{'exttool'}{$type};
                   2598:-23):             } else {
                   2599:-23):                 $domdefaults{$type.'exttool'} = 0;
                   2600:-23):             }
1.1172.2.30  raeburn  2601:         }
1.1172.2.67  raeburn  2602:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2603:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2604:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2605:                 if (@clonecodes) {
                   2606:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2607:                 }
                   2608:             }
                   2609:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2610:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2611:         }
1.1172.2.103  raeburn  2612:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2613:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2614:         }
1.1172.2.146.  .3(raebu 2615:22):         if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
                   2616:22):             $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
                   2617:22):         }
1.1047    raeburn  2618:     }
1.1073    raeburn  2619:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2620:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2621:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2622:         }
                   2623:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2624:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2625:         }
1.1172.2.62  raeburn  2626:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2627:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2628:         }
1.1172.2.137  raeburn  2629:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1172.2.136  raeburn  2630:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
                   2631:         }
1.1073    raeburn  2632:     }
1.1172.2.41  raeburn  2633:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2634:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2635:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2636:                             'approval','limit');
                   2637:             foreach my $type (@coursetypes) {
                   2638:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2639:                     my @mgrdc = ();
                   2640:                     foreach my $item (@settings) {
                   2641:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2642:                             push(@mgrdc,$item);
                   2643:                         }
                   2644:                     }
                   2645:                     if (@mgrdc) {
                   2646:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2647:                     }
                   2648:                 }
                   2649:             }
                   2650:         }
                   2651:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2652:             foreach my $type (@coursetypes) {
                   2653:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2654:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2655:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2656:                     }
                   2657:                 }
                   2658:             }
                   2659:         }
                   2660:     }
1.1172.2.46  raeburn  2661:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2662:         $domdefaults{'catauth'} = 'std';
                   2663:         $domdefaults{'catunauth'} = 'std';
                   2664:         if ($domconfig{'coursecategories'}{'auth'}) {
                   2665:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2666:         }
                   2667:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2668:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2669:         }
                   2670:     }
1.1172.2.76  raeburn  2671:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2672:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
1.1172.2.146  raeburn  2673:         $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
1.1172.2.76  raeburn  2674:     }
1.1172.2.89  raeburn  2675:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2676:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2677:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2678:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2679:         }
                   2680:     }
1.1172.2.142  raeburn  2681:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   2682:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
                   2683:             if ($domconfig{'wafproxy'}{$item}) {
                   2684:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
                   2685:             }
                   2686:         }
                   2687:     }
1.1172.2.146.  .4(raebu 2688:22):     if (ref($domconfig{'ltisec'}) eq 'HASH') {
                   2689:22):         if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
                   2690:22):             $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
                   2691:22):             $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
                   2692:22):             $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
                   2693:22):         }
                   2694:22):         if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
                   2695:22):             if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
          .13(raeb 2696:-23):                 $domdefaults{'ltiprivhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
                   2697:-23):             }
                   2698:-23):         }
                   2699:-23):     }
                   2700:-23):     if (ref($domconfig{'toolsec'}) eq 'HASH') {
                   2701:-23):         if (ref($domconfig{'toolsec'}{'encrypt'}) eq 'HASH') {
                   2702:-23):             $domdefaults{'toolenc_crs'} = $domconfig{'toolsec'}{'encrypt'}{'crs'};
                   2703:-23):             $domdefaults{'toolenc_dom'} = $domconfig{'toolsec'}{'encrypt'}{'dom'};
                   2704:-23):         }
                   2705:-23):         if (ref($domconfig{'toolsec'}{'private'}) eq 'HASH') {
                   2706:-23):             if (ref($domconfig{'toolsec'}{'private'}{'keys'}) eq 'ARRAY') {
                   2707:-23):                 $domdefaults{'toolprivhosts'} = $domconfig{'toolsec'}{'private'}{'keys'};
          .4(raebu 2708:22):             }
                   2709:22):         }
                   2710:22):     }
1.1172.2.23  raeburn  2711:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2712:     return %domdefaults;
                   2713: }
                   2714: 
1.1172.2.106  raeburn  2715: sub get_dom_cats {
                   2716:     my ($dom) = @_;
                   2717:     return unless (&domain($dom));
                   2718:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2719:     unless (defined($cached)) {
                   2720:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2721:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2722:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2723:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2724:             } else {
                   2725:                 $cats = {};
                   2726:             }
                   2727:         } else {
                   2728:             $cats = {};
                   2729:         }
                   2730:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2731:     }
                   2732:     return $cats;
                   2733: }
                   2734: 
                   2735: sub get_dom_instcats {
                   2736:     my ($dom) = @_;
                   2737:     return unless (&domain($dom));
                   2738:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2739:     unless (defined($cached)) {
                   2740:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2741:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2742:         if ($totcodes > 0) {
                   2743:             my $caller = 'global';
                   2744:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2745:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2746:                 $instcats = {
1.1172.2.146.  .10(raeb 2747:-23):                                 totcodes => $totcodes,
1.1172.2.106  raeburn  2748:                                 codes => \%codes,
                   2749:                                 codetitles => \@codetitles,
                   2750:                                 cat_titles => \%cat_titles,
                   2751:                                 cat_order => \%cat_order,
                   2752:                             };
                   2753:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2754:             }
                   2755:         }
                   2756:     }
                   2757:     return $instcats;
                   2758: }
                   2759: 
                   2760: sub retrieve_instcodes {
                   2761:     my ($coursecodes,$dom) = @_;
                   2762:     my $totcodes;
                   2763:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2764:     foreach my $course (keys(%courses)) {
                   2765:         if (ref($courses{$course}) eq 'HASH') {
                   2766:             if ($courses{$course}{'inst_code'} ne '') {
                   2767:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2768:                 $totcodes ++;
                   2769:             }
                   2770:         }
                   2771:     }
                   2772:     return $totcodes;
                   2773: }
                   2774: 
1.1172.2.113  raeburn  2775: # --------------------------------------------- Get domain config for passwords
                   2776: 
                   2777: sub get_passwdconf {
                   2778:     my ($dom) = @_;
                   2779:     my (%passwdconf,$gotconf,$lookup);
                   2780:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2781:     if (defined($cached)) {
                   2782:         if (ref($result) eq 'HASH') {
                   2783:             %passwdconf = %{$result};
                   2784:             $gotconf = 1;
                   2785:         }
                   2786:     }
                   2787:     unless ($gotconf) {
                   2788:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2789:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2790:             %passwdconf = %{$domconfig{'passwords'}};
                   2791:         }
                   2792:         my $cachetime = 24*60*60;
                   2793:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2794:     }
                   2795:     return %passwdconf;
                   2796: }
                   2797: 
1.1172.2.146.  .1(raebu 2798:22): sub course_portal_url {
                   2799:22):     my ($cnum,$cdom,$r) = @_;
                   2800:22):     my $chome = &homeserver($cnum,$cdom);
                   2801:22):     my $hostname = &hostname($chome);
                   2802:22):     my $protocol = $protocol{$chome};
                   2803:22):     $protocol = 'http' if ($protocol ne 'https');
                   2804:22):     my %domdefaults = &get_domain_defaults($cdom);
                   2805:22):     my $firsturl;
                   2806:22):     if ($domdefaults{'portal_def'}) {
                   2807:22):         $firsturl = $domdefaults{'portal_def'};
                   2808:22):     } else {
                   2809:22):         my $alias = &Apache::lonnet::use_proxy_alias($r,$chome);
                   2810:22):         $hostname = $alias if ($alias ne '');
                   2811:22):         $firsturl = $protocol.'://'.$hostname;
                   2812:22):     }
                   2813:22):     return $firsturl;
                   2814:22): }
                   2815:22): 
          .12(raeb 2816:-23): sub url_prefix {
                   2817:-23):     my ($r,$dom,$home,$context) = @_;
                   2818:-23):     my $prefix;
                   2819:-23):     my %domdefs = &get_domain_defaults($dom);
                   2820:-23):     if ($domdefs{'portal_def'} && $domdefs{'portal_def_'.$context}) {
                   2821:-23):         if ($domdefs{'portal_def'} =~ m{^(https?://[^/]+)}) {
                   2822:-23):             $prefix = $1;
                   2823:-23):         }
                   2824:-23):     }
                   2825:-23):     if ($prefix eq '') {
                   2826:-23):         my $hostname = &hostname($home);
                   2827:-23):         my $protocol = $protocol{$home};
                   2828:-23):         $protocol = 'http' if ($protocol{$home} ne 'https');
                   2829:-23):         my $alias = &use_proxy_alias($r,$home);
                   2830:-23):         $hostname = $alias if ($alias ne '');
                   2831:-23):         $prefix = $protocol.'://'.$hostname;
                   2832:-23):     }
                   2833:-23):     return $prefix;
                   2834:-23): }
                   2835:-23): 
1.344     www      2836: # --------------------------------------------------- Assign a key to a student
                   2837: 
                   2838: sub assign_access_key {
1.364     www      2839: #
                   2840: # a valid key looks like uname:udom#comments
                   2841: # comments are being appended
                   2842: #
1.498     www      2843:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2844:     $kdom=
1.620     albertel 2845:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2846:     $knum=
1.620     albertel 2847:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2848:     $cdom=
1.620     albertel 2849:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2850:     $cnum=
1.620     albertel 2851:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2852:     $udom=$env{'user.name'} unless (defined($udom));
                   2853:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2854:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2855:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2856:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2857:                                                   # assigned to this person
                   2858:                                                   # - this should not happen,
1.345     www      2859:                                                   # unless something went wrong
                   2860:                                                   # the first time around
                   2861: # ready to assign
1.364     www      2862:         $logentry=$1.'; '.$logentry;
1.496     www      2863:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2864:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2865: # key now belongs to user
1.346     www      2866: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2867:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2868:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2869:                 return 'ok';
                   2870:             } else {
                   2871:                 return 
                   2872:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2873: 	    }
                   2874:         } else {
                   2875:             return 'error: Could not assign key, try again later.';
                   2876:         }
1.364     www      2877:     } elsif (!$existing{$ckey}) {
1.345     www      2878: # the key does not exist
                   2879: 	return 'error: The key does not exist';
                   2880:     } else {
                   2881: # the key is somebody else's
                   2882: 	return 'error: The key is already in use';
                   2883:     }
1.344     www      2884: }
                   2885: 
1.364     www      2886: # ------------------------------------------ put an additional comment on a key
                   2887: 
                   2888: sub comment_access_key {
                   2889: #
                   2890: # a valid key looks like uname:udom#comments
                   2891: # comments are being appended
                   2892: #
                   2893:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2894:     $cdom=
1.620     albertel 2895:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2896:     $cnum=
1.620     albertel 2897:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2898:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2899:     if ($existing{$ckey}) {
                   2900:         $existing{$ckey}.='; '.$logentry;
                   2901: # ready to assign
1.367     www      2902:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2903:                                                  $cdom,$cnum) eq 'ok') {
                   2904: 	    return 'ok';
                   2905:         } else {
                   2906: 	    return 'error: Count not store comment.';
                   2907:         }
                   2908:     } else {
                   2909: # the key does not exist
                   2910: 	return 'error: The key does not exist';
                   2911:     }
                   2912: }
                   2913: 
1.344     www      2914: # ------------------------------------------------------ Generate a set of keys
                   2915: 
                   2916: sub generate_access_keys {
1.364     www      2917:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2918:     $cdom=
1.620     albertel 2919:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2920:     $cnum=
1.620     albertel 2921:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2922:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2923:     unless (($cdom) && ($cnum)) { return 0; }
                   2924:     if ($number>10000) { return 0; }
                   2925:     sleep(2); # make sure don't get same seed twice
                   2926:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2927:     my $total=0;
                   2928:     for (my $i=1;$i<=$number;$i++) {
                   2929:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2930:                   sprintf("%lx",int(100000*rand)).'-'.
                   2931:                   sprintf("%lx",int(100000*rand));
                   2932:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2933:        $newkey=~s/0/h/g; # and also 0 and O
                   2934:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2935:        if ($existing{$newkey}) {
                   2936:            $i--;
                   2937:        } else {
1.364     www      2938: 	  if (&put('accesskeys',
                   2939:               { $newkey => '# generated '.localtime().
1.620     albertel 2940:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2941:                            '; '.$logentry },
                   2942: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2943:               $total++;
                   2944: 	  }
                   2945:        }
                   2946:     }
1.620     albertel 2947:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2948:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2949:     return $total;
                   2950: }
                   2951: 
                   2952: # ------------------------------------------------------- Validate an accesskey
                   2953: 
                   2954: sub validate_access_key {
                   2955:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2956:     $cdom=
1.620     albertel 2957:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2958:     $cnum=
1.620     albertel 2959:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2960:     $udom=$env{'user.domain'} unless (defined($udom));
                   2961:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2962:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2963:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2964: }
                   2965: 
                   2966: # ------------------------------------- Find the section of student in a course
1.652     albertel 2967: sub devalidate_getsection_cache {
                   2968:     my ($udom,$unam,$courseid)=@_;
                   2969:     my $hashid="$udom:$unam:$courseid";
                   2970:     &devalidate_cache_new('getsection',$hashid);
                   2971: }
1.298     matthew  2972: 
1.815     albertel 2973: sub courseid_to_courseurl {
                   2974:     my ($courseid) = @_;
                   2975:     #already url style courseid
                   2976:     return $courseid if ($courseid =~ m{^/});
                   2977: 
                   2978:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2979: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2980: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2981: 	return "/$cdom/$cnum";
                   2982:     }
                   2983: 
                   2984:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2985:     if (exists($courseinfo{'num'})) {
                   2986: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2987:     }
                   2988: 
                   2989:     return undef;
                   2990: }
                   2991: 
1.298     matthew  2992: sub getsection {
                   2993:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2994:     my $cachetime=1800;
1.551     albertel 2995: 
                   2996:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2997:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2998:     if (defined($cached)) { return $result; }
                   2999: 
1.298     matthew  3000:     my %Pending; 
                   3001:     my %Expired;
                   3002:     #
                   3003:     # Each role can either have not started yet (pending), be active, 
                   3004:     #    or have expired.
                   3005:     #
                   3006:     # If there is an active role, we are done.
                   3007:     #
                   3008:     # If there is more than one role which has not started yet, 
                   3009:     #     choose the one which will start sooner
                   3010:     # If there is one role which has not started yet, return it.
                   3011:     #
                   3012:     # If there is more than one expired role, choose the one which ended last.
                   3013:     # If there is a role which has expired, return it.
                   3014:     #
1.815     albertel 3015:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  3016:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  3017:     foreach my $key (keys(%roleshash)) {
1.479     albertel 3018:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  3019:         my $section=$1;
                   3020:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  3021:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  3022:         my $now=time;
1.548     albertel 3023:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  3024:             $Expired{$end}=$section;
                   3025:             next;
                   3026:         }
1.548     albertel 3027:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  3028:             $Pending{$start}=$section;
                   3029:             next;
                   3030:         }
1.599     albertel 3031:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  3032:     }
                   3033:     #
                   3034:     # Presumedly there will be few matching roles from the above
                   3035:     # loop and the sorting time will be negligible.
                   3036:     if (scalar(keys(%Pending))) {
                   3037:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 3038:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  3039:     } 
                   3040:     if (scalar(keys(%Expired))) {
                   3041:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   3042:         my $time = pop(@sorted);
1.599     albertel 3043:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  3044:     }
1.599     albertel 3045:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  3046: }
1.70      www      3047: 
1.599     albertel 3048: sub save_cache {
                   3049:     &purge_remembered();
1.722     albertel 3050:     #&Apache::loncommon::validate_page();
1.620     albertel 3051:     undef(%env);
1.780     albertel 3052:     undef($env_loaded);
1.599     albertel 3053: }
1.452     albertel 3054: 
1.599     albertel 3055: my $to_remember=-1;
                   3056: my %remembered;
                   3057: my %accessed;
                   3058: my $kicks=0;
                   3059: my $hits=0;
1.849     albertel 3060: sub make_key {
                   3061:     my ($name,$id) = @_;
1.872     albertel 3062:     if (length($id) > 65 
                   3063: 	&& length(&escape($id)) > 200) {
                   3064: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   3065:     }
1.849     albertel 3066:     return &escape($name.':'.$id);
                   3067: }
                   3068: 
1.599     albertel 3069: sub devalidate_cache_new {
                   3070:     my ($name,$id,$debug) = @_;
                   3071:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1172.2.81  raeburn  3072:     my $remembered_id=$name.':'.$id;
1.849     albertel 3073:     $id=&make_key($name,$id);
1.599     albertel 3074:     $memcache->delete($id);
1.1172.2.81  raeburn  3075:     delete($remembered{$remembered_id});
                   3076:     delete($accessed{$remembered_id});
1.599     albertel 3077: }
                   3078: 
                   3079: sub is_cached_new {
                   3080:     my ($name,$id,$debug) = @_;
1.1172.2.81  raeburn  3081:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
                   3082:                                      # keys in %remembered hash, which persists for
                   3083:                                      # duration of request (no restriction on key length).
                   3084:     if (exists($remembered{$remembered_id})) {
                   3085: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   3086: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3087: 	$hits++;
1.1172.2.81  raeburn  3088: 	return ($remembered{$remembered_id},1);
1.599     albertel 3089:     }
1.1172.2.81  raeburn  3090:     $id=&make_key($name,$id);
1.599     albertel 3091:     my $value = $memcache->get($id);
                   3092:     if (!(defined($value))) {
                   3093: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 3094: 	return (undef,undef);
1.416     albertel 3095:     }
1.599     albertel 3096:     if ($value eq '__undef__') {
                   3097: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   3098: 	$value=undef;
                   3099:     }
1.1172.2.81  raeburn  3100:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3101:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   3102:     return ($value,1);
                   3103: }
                   3104: 
                   3105: sub do_cache_new {
                   3106:     my ($name,$id,$value,$time,$debug) = @_;
1.1172.2.81  raeburn  3107:     my $remembered_id=$name.':'.$id;
1.849     albertel 3108:     $id=&make_key($name,$id);
1.599     albertel 3109:     my $setvalue=$value;
                   3110:     if (!defined($setvalue)) {
                   3111: 	$setvalue='__undef__';
                   3112:     }
1.623     albertel 3113:     if (!defined($time) ) {
                   3114: 	$time=600;
                   3115:     }
1.599     albertel 3116:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 3117:     my $result = $memcache->set($id,$setvalue,$time);
                   3118:     if (! $result) {
1.872     albertel 3119: 	&logthis("caching of id -> $id  failed");
1.910     albertel 3120: 	$memcache->disconnect_all();
1.872     albertel 3121:     }
1.600     albertel 3122:     # need to make a copy of $value
1.1172.2.81  raeburn  3123:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3124:     return $value;
                   3125: }
                   3126: 
                   3127: sub make_room {
1.1172.2.81  raeburn  3128:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 3129: 
1.1172.2.81  raeburn  3130:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 3131:                                     : $value;
1.599     albertel 3132:     if ($to_remember<0) { return; }
1.1172.2.81  raeburn  3133:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3134:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   3135:     my $to_kick;
                   3136:     my $max_time=0;
                   3137:     foreach my $other (keys(%accessed)) {
                   3138: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   3139: 	    $to_kick=$other;
                   3140: 	    $max_time=&tv_interval($accessed{$other});
                   3141: 	}
                   3142:     }
                   3143:     delete($remembered{$to_kick});
                   3144:     delete($accessed{$to_kick});
                   3145:     $kicks++;
                   3146:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 3147:     return;
                   3148: }
                   3149: 
1.599     albertel 3150: sub purge_remembered {
1.604     albertel 3151:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   3152:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 3153:     undef(%remembered);
                   3154:     undef(%accessed);
1.428     albertel 3155: }
1.70      www      3156: # ------------------------------------- Read an entry from a user's environment
                   3157: 
                   3158: sub userenvironment {
                   3159:     my ($udom,$unam,@what)=@_;
1.976     raeburn  3160:     my $items;
                   3161:     foreach my $item (@what) {
                   3162:         $items.=&escape($item).'&';
                   3163:     }
                   3164:     $items=~s/\&$//;
1.70      www      3165:     my %returnhash=();
1.1009    raeburn  3166:     my $uhome = &homeserver($unam,$udom);
                   3167:     unless ($uhome eq 'no_host') {
                   3168:         my @answer=split(/\&/, 
                   3169:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  3170:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   3171:             return %returnhash;
                   3172:         }
1.1009    raeburn  3173:         my $i;
                   3174:         for ($i=0;$i<=$#what;$i++) {
                   3175: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3176:         }
1.70      www      3177:     }
                   3178:     return %returnhash;
1.1       albertel 3179: }
                   3180: 
1.617     albertel 3181: # ---------------------------------------------------------- Get a studentphoto
                   3182: sub studentphoto {
                   3183:     my ($udom,$unam,$ext) = @_;
                   3184:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  3185:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3186:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3187:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3188:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3189:             } else {
                   3190:                 my ($result,$perm_reqd)=
1.707     albertel 3191: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3192:                 if ($result eq 'ok') {
                   3193:                     if (!($perm_reqd eq 'yes')) {
                   3194:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3195:                     }
                   3196:                 }
                   3197:             }
                   3198:         }
                   3199:     } else {
                   3200:         my ($result,$perm_reqd) = 
1.707     albertel 3201: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3202:         if ($result eq 'ok') {
                   3203:             if (!($perm_reqd eq 'yes')) {
                   3204:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3205:             }
                   3206:         }
                   3207:     }
                   3208:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3209: }
                   3210: 
                   3211: sub retrievestudentphoto {
                   3212:     my ($udom,$unam,$ext,$type) = @_;
                   3213:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   3214:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   3215:     if ($ret eq 'ok') {
                   3216:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3217:         if ($type eq 'thumbnail') {
                   3218:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3219:         }
                   3220:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   3221:         return $tokenurl;
                   3222:     } else {
                   3223:         if ($type eq 'thumbnail') {
                   3224:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3225:         } else { 
                   3226:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3227:         }
1.617     albertel 3228:     }
                   3229: }
                   3230: 
1.263     www      3231: # -------------------------------------------------------------------- New chat
                   3232: 
                   3233: sub chatsend {
1.724     raeburn  3234:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3235:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3236:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3237:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3238:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3239: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3240: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3241: }
                   3242: 
                   3243: # ------------------------------------------ Find current version of a resource
                   3244: 
                   3245: sub getversion {
                   3246:     my $fname=&clutter(shift);
1.1172.2.10  raeburn  3247:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3248:     return &currentversion(&filelocation('',$fname));
                   3249: }
                   3250: 
                   3251: sub currentversion {
                   3252:     my $fname=shift;
                   3253:     my $author=$fname;
                   3254:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3255:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3256:     my $home=&homeserver($uname,$udom);
1.292     www      3257:     if ($home eq 'no_host') { 
                   3258:         return -1; 
                   3259:     }
1.1112    www      3260:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3261:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3262: 	return -1;
                   3263:     }
1.1112    www      3264:     return $answer;
1.263     www      3265: }
                   3266: 
1.1111    www      3267: #
                   3268: # Return special version number of resource if set by override, empty otherwise
                   3269: #
                   3270: sub usedversion {
                   3271:     my $fname=shift;
                   3272:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3273:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3274:     if ($urlversion) { return $urlversion; }
                   3275:     return '';
                   3276: }
                   3277: 
1.1       albertel 3278: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3279: 
1.1       albertel 3280: sub subscribe {
                   3281:     my $fname=shift;
1.761     raeburn  3282:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3283:     $fname=~s/[\n\r]//g;
1.1       albertel 3284:     my $author=$fname;
                   3285:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3286:     my ($udom,$uname)=split(/\//,$author);
                   3287:     my $home=homeserver($uname,$udom);
1.335     albertel 3288:     if ($home eq 'no_host') {
                   3289:         return 'not_found';
1.1       albertel 3290:     }
                   3291:     my $answer=reply("sub:$fname",$home);
1.64      www      3292:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3293: 	$answer.=' by '.$home;
                   3294:     }
1.1       albertel 3295:     return $answer;
                   3296: }
                   3297:     
1.8       www      3298: # -------------------------------------------------------------- Replicate file
                   3299: 
                   3300: sub repcopy {
                   3301:     my $filename=shift;
1.23      www      3302:     $filename=~s/\/+/\//g;
1.1142    raeburn  3303:     my $londocroot = $perlvar{'lonDocRoot'};
                   3304:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3305:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3306:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3307: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3308: 	return &repcopy_userfile($filename);
                   3309:     }
1.532     albertel 3310:     $filename=~s/[\n\r]//g;
1.8       www      3311:     my $transname="$filename.in.transfer";
1.828     www      3312: # FIXME: this should flock
1.607     raeburn  3313:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3314:     my $remoteurl=subscribe($filename);
1.64      www      3315:     if ($remoteurl =~ /^con_lost by/) {
                   3316: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3317:            return 'unavailable';
1.8       www      3318:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3319: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3320: 	   return 'not_found';
1.64      www      3321:     } elsif ($remoteurl =~ /^rejected by/) {
                   3322: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3323:            return 'forbidden';
1.20      www      3324:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3325:            return 'ok';
1.8       www      3326:     } else {
1.290     www      3327:         my $author=$filename;
                   3328:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3329:         my ($udom,$uname)=split(/\//,$author);
                   3330:         my $home=homeserver($uname,$udom);
                   3331:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3332:            my @parts=split(/\//,$filename);
                   3333:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3334:            if ($path ne "$londocroot/res") {
1.8       www      3335:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3336: 	       return 'bad_request';
1.8       www      3337:            }
                   3338:            my $count;
                   3339:            for ($count=5;$count<$#parts;$count++) {
                   3340:                $path.="/$parts[$count]";
                   3341:                if ((-e $path)!=1) {
                   3342: 		   mkdir($path,0777);
                   3343:                }
                   3344:            }
                   3345:            my $ua=new LWP::UserAgent;
                   3346:            my $request=new HTTP::Request('GET',"$remoteurl");
                   3347:            my $response=$ua->request($request,$transname);
                   3348:            if ($response->is_error()) {
                   3349: 	       unlink($transname);
                   3350:                my $message=$response->status_line;
1.672     albertel 3351:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3352:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3353:                return 'unavailable';
1.8       www      3354:            } else {
1.16      www      3355: 	       if ($remoteurl!~/\.meta$/) {
                   3356:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   3357:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   3358:                   if ($mresponse->is_error()) {
                   3359: 		      unlink($filename.'.meta');
                   3360:                       &logthis(
1.672     albertel 3361:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3362:                   }
                   3363: 	       }
1.8       www      3364:                rename($transname,$filename);
1.607     raeburn  3365:                return 'ok';
1.8       www      3366:            }
1.290     www      3367:        }
1.8       www      3368:     }
1.330     www      3369: }
                   3370: 
1.1172.2.124  raeburn  3371: # ------------------------------------------------- Unsubscribe from a resource
                   3372: 
                   3373: sub unsubscribe {
                   3374:     my ($fname) = @_;
                   3375:     my $answer;
                   3376:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3377:     $fname=~s/[\n\r]//g;
                   3378:     my $author=$fname;
                   3379:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3380:     my ($udom,$uname)=split(/\//,$author);
                   3381:     my $home=homeserver($uname,$udom);
                   3382:     if ($home eq 'no_host') {
                   3383:         $answer = 'no_host';
                   3384:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3385:         $answer = 'home';
                   3386:     } else {
1.1172.2.125  raeburn  3387:         $answer = reply("unsub:$fname",$home);
1.1172.2.124  raeburn  3388:     }
                   3389:     return $answer;
                   3390: }
                   3391: 
1.330     www      3392: # ------------------------------------------------ Get server side include body
                   3393: sub ssi_body {
1.381     albertel 3394:     my ($filelink,%form)=@_;
1.606     matthew  3395:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3396:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3397:     }
1.953     www      3398:     my $output='';
                   3399:     my $response;
1.980     raeburn  3400:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3401:        ($output,$response)=&externalssi($filelink);
1.953     www      3402:     } else {
1.1004    droeschl 3403:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3404:        $filelink .= 'inhibitmenu=yes';
1.953     www      3405:        ($output,$response)=&ssi($filelink,%form);
                   3406:     }
1.778     albertel 3407:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3408:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3409:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3410:     if (wantarray) {
                   3411:         return ($output, $response);
                   3412:     } else {
                   3413:         return $output;
                   3414:     }
1.8       www      3415: }
                   3416: 
1.15      www      3417: # --------------------------------------------------------- Server Side Include
                   3418: 
1.782     albertel 3419: sub absolute_url {
1.1172.2.145  raeburn  3420:     my ($host_name,$unalias,$keep_proto) = @_;
1.782     albertel 3421:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3422:     if ($host_name eq '') {
                   3423: 	$host_name = $ENV{'SERVER_NAME'};
                   3424:     }
1.1172.2.145  raeburn  3425:     if ($unalias) {
                   3426:         my $alias = &get_proxy_alias();
                   3427:         if ($alias eq $host_name) {
                   3428:             my $lonhost = $perlvar{'lonHostID'};
                   3429:             my $hostname = &hostname($lonhost);
                   3430:             my $lcproto;
                   3431:             if (($keep_proto) || ($hostname eq '')) {
                   3432:                 $lcproto = $protocol;
                   3433:             } else {
                   3434:                 $lcproto = $protocol{$lonhost};
                   3435:                 $lcproto = 'http' if ($lcproto ne 'https');
                   3436:                 $lcproto .= '://';
                   3437:             }
                   3438:             unless ($hostname eq '') {
                   3439:                 return $lcproto.$hostname;
                   3440:             }
                   3441:         }
                   3442:     } 
1.782     albertel 3443:     return $protocol.$host_name;
                   3444: }
                   3445: 
1.942     foxr     3446: #
                   3447: #   Server side include.
                   3448: # Parameters:
                   3449: #  fn     Possibly encrypted resource name/id.
                   3450: #  form   Hash that describes how the rendering should be done
                   3451: #         and other things.
1.944     foxr     3452: # Returns:
1.950     raeburn  3453: #   Scalar context: The content of the response.
                   3454: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3455: #     
1.15      www      3456: sub ssi {
                   3457: 
1.944     foxr     3458:     my ($fn,%form)=@_;
1.1172.2.145  raeburn  3459:     my ($host,$request,$response);
                   3460:     $host = &absolute_url('',1);
1.711     albertel 3461: 
                   3462:     $form{'no_update_last_known'}=1;
1.895     albertel 3463:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3464:     if (%form) {
1.1172.2.145  raeburn  3465:       $request=new HTTP::Request('POST',$host.$fn);
1.1172.2.58  raeburn  3466:       $request->content(join('&',map {
                   3467:             my $name = escape($_);
                   3468:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
                   3469:             ? join("&$name=", map {escape($_) } @{$form{$_}})
                   3470:             : &escape($form{$_}) );
                   3471:         } keys(%form)));
1.23      www      3472:     } else {
1.1172.2.145  raeburn  3473:       $request=new HTTP::Request('GET',$host.$fn);
1.23      www      3474:     }
                   3475: 
1.15      www      3476:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1172.2.100  raeburn  3477: 
1.1172.2.101  raeburn  3478:     if (($env{'request.course.id'}) &&
                   3479:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3480:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3481:         ($form{'grade_symb'} ne '') &&
                   3482:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3483:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
1.1172.2.100  raeburn  3484:         if (LWP::UserAgent->VERSION >= 5.834) {
                   3485:             my $ua=new LWP::UserAgent;
                   3486:             $ua->local_address('127.0.0.1');
                   3487:             $response = $ua->request($request);
                   3488:         } else {
                   3489:             {
                   3490:                 require LWP::Protocol::http;
                   3491:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
                   3492:                 my $ua=new LWP::UserAgent;
                   3493:                 $response = $ua->request($request);
                   3494:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
                   3495:             }
                   3496:         }
                   3497:     } else {
                   3498:         my $ua=new LWP::UserAgent;
                   3499:         $response = $ua->request($request);
                   3500:     }
1.944     foxr     3501:     if (wantarray) {
1.1172.2.3  raeburn  3502: 	return ($response->content, $response);
1.944     foxr     3503:     } else {
1.1172.2.3  raeburn  3504: 	return $response->content;
1.942     foxr     3505:     }
1.324     www      3506: }
                   3507: 
                   3508: sub externalssi {
                   3509:     my ($url)=@_;
                   3510:     my $ua=new LWP::UserAgent;
                   3511:     my $request=new HTTP::Request('GET',$url);
                   3512:     my $response=$ua->request($request);
1.954     raeburn  3513:     if (wantarray) {
                   3514:         return ($response->content, $response);
                   3515:     } else {
                   3516:         return $response->content;
                   3517:     }
1.15      www      3518: }
1.254     www      3519: 
1.1172.2.98  raeburn  3520: # If the local copy of a replicated resource is outdated, trigger a
                   3521: # connection from the homeserver to flush the delayed queue. If no update
                   3522: # happens, remove local copies of outdated resource (and corresponding
                   3523: # metadata file).
                   3524: 
                   3525: sub remove_stale_resfile {
                   3526:     my ($url) = @_;
                   3527:     my $removed;
                   3528:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3529:         my $audom = $1;
                   3530:         my $auname = $2;
                   3531:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
                   3532:             my $homeserver = &homeserver($auname,$audom);
                   3533:             unless (($homeserver eq 'no_host') ||
                   3534:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3535:                 my $fname = &filelocation('',$url);
                   3536:                 if (-e $fname) {
                   3537:                     my $hostname = &hostname($homeserver);
                   3538:                     if ($hostname) {
1.1172.2.120  raeburn  3539:                         my $protocol = $protocol{$homeserver};
                   3540:                         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.98  raeburn  3541:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
1.1172.2.120  raeburn  3542:                         my $ua=new LWP::UserAgent;
                   3543:                         $ua->timeout(5);
1.1172.2.98  raeburn  3544:                         my $request=new HTTP::Request('HEAD',$uri);
                   3545:                         my $response=$ua->request($request);
                   3546:                         if ($response->is_success()) {
                   3547:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3548:                             my $locmodtime = (stat($fname))[9];
                   3549:                             if ($locmodtime < $remmodtime) {
                   3550:                                 my $stale;
                   3551:                                 my $answer = &reply('pong',$homeserver);
                   3552:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3553:                                     sleep(0.2);
                   3554:                                     $locmodtime = (stat($fname))[9];
                   3555:                                     if ($locmodtime < $remmodtime) {
                   3556:                                         my $posstransfer = $fname.'.in.transfer';
                   3557:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3558:                                             $removed = 1;
                   3559:                                         } else {
                   3560:                                             $stale = 1;
                   3561:                                         }
                   3562:                                     } else {
                   3563:                                         $removed = 1;
                   3564:                                     }
                   3565:                                 } else {
                   3566:                                     $stale = 1;
                   3567:                                 }
                   3568:                                 if ($stale) {
1.1172.2.124  raeburn  3569:                                     if (unlink($fname)) {
                   3570:                                         if ($uri!~/\.meta$/) {
                   3571:                                             if (-e $fname.'.meta') {
                   3572:                                                 unlink($fname.'.meta');
                   3573:                                             }
                   3574:                                         }
                   3575:                                         my $unsubresult = &unsubscribe($fname);
                   3576:                                         unless ($unsubresult eq 'ok') {
                   3577:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3578:                                         }
                   3579:                                         $removed = 1;
1.1172.2.98  raeburn  3580:                                     }
                   3581:                                 }
                   3582:                             }
                   3583:                         }
                   3584:                     }
                   3585:                 }
                   3586:             }
                   3587:         }
                   3588:     }
                   3589:     return $removed;
                   3590: }
                   3591: 
1.492     albertel 3592: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3593: 
                   3594: sub allowuploaded {
                   3595:     my ($srcurl,$url)=@_;
                   3596:     $url=&clutter(&declutter($url));
                   3597:     my $dir=$url;
                   3598:     $dir=~s/\/[^\/]+$//;
                   3599:     my %httpref=();
                   3600:     my $httpurl=&hreflocation('',$url);
                   3601:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3602:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3603: }
1.477     raeburn  3604: 
1.1172.2.13  raeburn  3605: #
                   3606: # Determine if the current user should be able to edit a particular resource,
                   3607: # when viewing in course context.
                   3608: # (a) When viewing resource used to determine if "Edit" item is included in
                   3609: #     Functions.
                   3610: # (b) When displaying folder contents in course editor, used to determine if
                   3611: #     "Edit" link will be displayed alongside resource.
                   3612: #
                   3613: #  input: six args -- filename (decluttered), course number, course domain,
                   3614: #                   url, symb (if registered) and group (if this is a group
                   3615: #                   item -- e.g., bulletin board, group page etc.).
                   3616: #  output: array of five scalars --
                   3617: #          $cfile -- url for file editing if editable on current server
                   3618: #          $home -- homeserver of resource (i.e., for author if published,
                   3619: #                                           or course if uploaded.).
                   3620: #          $switchserver --  1 if server switch will be needed.
                   3621: #          $forceedit -- 1 if icon/link should be to go to edit mode
                   3622: #          $forceview -- 1 if icon/link should be to go to view mode
                   3623: #
                   3624: 
                   3625: sub can_edit_resource {
                   3626:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3627:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3628: #
                   3629: # For aboutme pages user can only edit his/her own.
                   3630: #
                   3631:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
                   3632:         my ($sdom,$sname) = ($1,$2);
                   3633:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3634:             $home = $env{'user.home'};
                   3635:             $cfile = $resurl;
                   3636:             if ($env{'form.forceedit'}) {
                   3637:                 $forceview = 1;
                   3638:             } else {
                   3639:                 $forceedit = 1;
                   3640:             }
                   3641:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3642:         } else {
                   3643:             return;
                   3644:         }
                   3645:     }
                   3646: 
                   3647:     if ($env{'request.course.id'}) {
                   3648:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3649:         if ($group ne '') {
                   3650: # if this is a group homepage or group bulletin board, check group privs
                   3651:             my $allowed = 0;
                   3652:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3653:                 if ((&allowed('mdg',$env{'request.course.id'}.
                   3654:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3655:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3656:                     $allowed = 1;
                   3657:                 }
                   3658:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3659:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3660:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3661:                     $allowed = 1;
                   3662:                 }
                   3663:             }
                   3664:             if ($allowed) {
                   3665:                 $home=&homeserver($cnum,$cdom);
                   3666:                 if ($env{'form.forceedit'}) {
                   3667:                     $forceview = 1;
                   3668:                 } else {
                   3669:                     $forceedit = 1;
                   3670:                 }
                   3671:                 $cfile = $resurl;
                   3672:             } else {
                   3673:                 return;
                   3674:             }
                   3675:         } else {
1.1172.2.15  raeburn  3676:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3677:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3678:                     return;
                   3679:                 }
                   3680:             } elsif (!$crsedit) {
1.1172.2.13  raeburn  3681: #
                   3682: # No edit allowed where CC has switched to student role.
                   3683: #
                   3684:                 return;
                   3685:             }
                   3686:         }
                   3687:     }
                   3688: 
                   3689:     if ($file ne '') {
                   3690:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
                   3691:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3692:                 $uploaded = 1;
                   3693:                 $incourse = 1;
                   3694:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3695:                     $cfile = &hreflocation('',$file);
                   3696:                     if ($env{'form.forceedit'}) {
                   3697:                         $forceview = 1;
                   3698:                     } else {
                   3699:                         $forceedit = 1;
                   3700:                     }
                   3701:                 }
                   3702:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3703:                 $incourse = 1;
                   3704:                 if ($env{'form.forceedit'}) {
                   3705:                     $forceview = 1;
                   3706:                 } else {
                   3707:                     $forceedit = 1;
                   3708:                 }
                   3709:                 $cfile = $resurl;
                   3710:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
                   3711:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3712:                     $incourse = 1;
                   3713:                     if ($env{'form.forceedit'}) {
                   3714:                         $forceview = 1;
                   3715:                     } else {
                   3716:                         $forceedit = 1;
                   3717:                     }
                   3718:                     $cfile = $resurl;
                   3719:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
                   3720:                     $incourse = 1;
                   3721:                     $cfile = $resurl.'/smpedit';
                   3722:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
                   3723:                     $incourse = 1;
                   3724:                     if ($env{'form.forceedit'}) {
                   3725:                         $forceview = 1;
                   3726:                     } else {
                   3727:                         $forceedit = 1;
                   3728:                     }
                   3729:                     $cfile = $resurl;
1.1172.2.122  raeburn  3730:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3731:                     my ($map,$id,$res) = &decode_symb($symb);
                   3732:                     if ($map =~ /\.page$/) {
                   3733:                         $incourse = 1;
                   3734:                         if ($env{'form.forceedit'}) {
                   3735:                             $forceview = 1;
                   3736:                             $cfile = $map;
                   3737:                         } else {
                   3738:                             $forceedit = 1;
                   3739:                             $cfile =  '/adm/wrapper'.$resurl;
                   3740:                         }
                   3741:                     }
1.1172.2.146.  .1(raebu 3742:22):                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3743:22):                     $incourse = 1;
                   3744:22):                     if ($env{'form.forceedit'}) {
                   3745:22):                         $forceview = 1;
                   3746:22):                     } else {
                   3747:22):                         $forceedit = 1;
                   3748:22):                     }
                   3749:22):                     $cfile = $resurl;
1.1172.2.15  raeburn  3750:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3751:                     $incourse = 1;
                   3752:                     if ($env{'form.forceedit'}) {
                   3753:                         $forceview = 1;
                   3754:                     } else {
                   3755:                         $forceedit = 1;
                   3756:                     }
                   3757:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3758:                 }
                   3759:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3760:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3761:                 if (&is_on_map($template)) {
                   3762:                     $incourse = 1;
                   3763:                     $forceview = 1;
                   3764:                     $cfile = $template;
                   3765:                 }
                   3766:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1172.2.118  raeburn  3767:                 $incourse = 1;
                   3768:                 if ($env{'form.forceedit'}) {
                   3769:                     $forceview = 1;
                   3770:                 } else {
                   3771:                     $forceedit = 1;
                   3772:                 }
                   3773:                 $cfile = $resurl;
1.1172.2.146.  .1(raebu 3774:22):             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3775:22):                 $incourse = 1;
                   3776:22):                 if ($env{'form.forceedit'}) {
                   3777:22):                     $forceview = 1;
                   3778:22):                 } else {
                   3779:22):                     $forceedit = 1;
                   3780:22):                 }
                   3781:22):                 $cfile = $resurl;
1.1172.2.13  raeburn  3782:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3783:                 $incourse = 1;
                   3784:                 $forceview = 1;
                   3785:                 if ($symb) {
                   3786:                     my ($map,$id,$res)=&decode_symb($symb);
                   3787:                     $env{'request.symb'} = $symb;
                   3788:                     $cfile = &clutter($res);
                   3789:                 } else {
                   3790:                     $cfile = $env{'form.suppurl'};
1.1172.2.146.  .1(raebu 3791:22):                     my $escfile = &unescape($cfile);
                   3792:22):                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   3793:22):                         $cfile = '/adm/wrapper'.$escfile;
                   3794:22):                     } else {
                   3795:22):                         $escfile =~ s{^http://}{};
                   3796:22):                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3797:22):                     }
1.1172.2.13  raeburn  3798:                 }
1.1172.2.31  raeburn  3799:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3800:                 if ($env{'form.forceedit'}) {
                   3801:                     $forceview = 1;
                   3802:                 } else {
                   3803:                     $forceedit = 1;
                   3804:                 }
                   3805:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1172.2.13  raeburn  3806:             }
                   3807:         }
                   3808:         if ($uploaded || $incourse) {
                   3809:             $home=&homeserver($cnum,$cdom);
1.1172.2.14  raeburn  3810:         } elsif ($file !~ m{/$}) {
1.1172.2.13  raeburn  3811:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3812:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3813:             # Check that the user has permission to edit this resource
                   3814:             my $setpriv = 1;
                   3815:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3816:             if (defined($cfudom)) {
                   3817:                 $home=&homeserver($cfuname,$cfudom);
                   3818:                 $cfile=$file;
                   3819:             }
                   3820:         }
                   3821:         if (($cfile ne '') && (!$incourse || $uploaded) &&
                   3822:             (($home ne '') && ($home ne 'no_host'))) {
                   3823:             my @ids=&current_machine_ids();
                   3824:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3825:                 $switchserver=1;
                   3826:             }
                   3827:         }
                   3828:     }
                   3829:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3830: }
                   3831: 
                   3832: sub is_course_upload {
                   3833:     my ($file,$cnum,$cdom) = @_;
                   3834:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3835:     $uploadpath =~ s{^\/}{};
                   3836:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3837:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
                   3838:         return 1;
                   3839:     }
                   3840:     return;
                   3841: }
                   3842: 
                   3843: sub in_course {
                   3844:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3845:     if ($hideprivileged) {
                   3846:         my $skipuser;
1.1172.2.23  raeburn  3847:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3848:         my @possdoms = ($cdom);
                   3849:         if ($coursehash{'checkforpriv'}) {
                   3850:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   3851:         }
                   3852:         if (&privileged($uname,$udom,\@possdoms)) {
1.1172.2.13  raeburn  3853:             $skipuser = 1;
                   3854:             if ($coursehash{'nothideprivileged'}) {
                   3855:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3856:                     my $user;
                   3857:                     if ($item =~ /:/) {
                   3858:                         $user = $item;
                   3859:                     } else {
                   3860:                         $user = join(':',split(/[\@]/,$item));
                   3861:                     }
                   3862:                     if ($user eq $uname.':'.$udom) {
                   3863:                         undef($skipuser);
                   3864:                         last;
                   3865:                     }
                   3866:                 }
                   3867:             }
                   3868:             if ($skipuser) {
                   3869:                 return 0;
                   3870:             }
                   3871:         }
                   3872:     }
                   3873:     $type ||= 'any';
                   3874:     if (!defined($cdom) || !defined($cnum)) {
                   3875:         my $cid  = $env{'request.course.id'};
                   3876:         $cdom = $env{'course.'.$cid.'.domain'};
                   3877:         $cnum = $env{'course.'.$cid.'.num'};
                   3878:     }
                   3879:     my $typesref;
                   3880:     if (($type eq 'any') || ($type eq 'all')) {
                   3881:         $typesref = ['active','previous','future'];
                   3882:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3883:         $typesref = [$type];
                   3884:     }
                   3885:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3886:                               $typesref,undef,[$cdom]);
                   3887:     my ($tmp) = keys(%roles);
                   3888:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3889:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3890:     if (@course_roles > 0) {
                   3891:         return 1;
                   3892:     }
                   3893:     return 0;
                   3894: }
                   3895: 
1.478     albertel 3896: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3897: # input: action, courseID, current domain, intended
1.637     raeburn  3898: #        path to file, source of file, instruction to parse file for objects,
                   3899: #        ref to hash for embedded objects,
                   3900: #        ref to hash for codebase of java objects.
1.1095    raeburn  3901: #        reference to scalar to accommodate mime type determined
                   3902: #          from File::MMagic if $parser = parse.
1.637     raeburn  3903: #
1.485     raeburn  3904: # output: url to file (if action was uploaddoc), 
                   3905: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3906: #
1.478     albertel 3907: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3908: # course.
1.477     raeburn  3909: #
1.478     albertel 3910: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3911: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3912: #          course's home server.
1.477     raeburn  3913: #
1.478     albertel 3914: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3915: #          be copied from $source (current location) to 
                   3916: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3917: #         and will then be copied to
                   3918: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3919: #         course's home server.
1.485     raeburn  3920: #
1.481     raeburn  3921: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3922: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3923: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3924: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3925: #         in course's home server.
1.637     raeburn  3926: #
1.477     raeburn  3927: 
                   3928: sub process_coursefile {
1.1095    raeburn  3929:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3930:         $mimetype)=@_;
1.477     raeburn  3931:     my $fetchresult;
1.638     albertel 3932:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3933:     if ($action eq 'propagate') {
1.638     albertel 3934:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3935: 			     $home);
1.481     raeburn  3936:     } else {
1.477     raeburn  3937:         my $fpath = '';
                   3938:         my $fname = $file;
1.478     albertel 3939:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3940:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3941:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3942:         if ($action eq 'copy') {
                   3943:             if ($source eq '') {
                   3944:                 $fetchresult = 'no source file';
                   3945:                 return $fetchresult;
                   3946:             } else {
                   3947:                 my $destination = $filepath.'/'.$fname;
                   3948:                 rename($source,$destination);
                   3949:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3950:                                  $home);
1.481     raeburn  3951:             }
                   3952:         } elsif ($action eq 'uploaddoc') {
1.1172.2.96  raeburn  3953:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3954:             print $fh $env{'form.'.$source};
1.481     raeburn  3955:             close($fh);
1.637     raeburn  3956:             if ($parser eq 'parse') {
1.1024    raeburn  3957:                 my $mm = new File::MMagic;
1.1095    raeburn  3958:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3959:                 if ($type eq 'text/html') {
1.1024    raeburn  3960:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3961:                     unless ($parse_result eq 'ok') {
                   3962:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3963:                     }
1.637     raeburn  3964:                 }
1.1095    raeburn  3965:                 if (ref($mimetype)) {
                   3966:                     $$mimetype = $type;
                   3967:                 } 
1.637     raeburn  3968:             }
1.477     raeburn  3969:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3970:                                  $home);
1.481     raeburn  3971:             if ($fetchresult eq 'ok') {
                   3972:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3973:             } else {
                   3974:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3975:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3976:                 return '/adm/notfound.html';
                   3977:             }
1.477     raeburn  3978:         }
                   3979:     }
1.485     raeburn  3980:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3981:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3982:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3983:     }
                   3984:     return $fetchresult;
                   3985: }
                   3986: 
1.637     raeburn  3987: sub build_filepath {
                   3988:     my ($fpath) = @_;
                   3989:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3990:     unless ($fpath eq '') {
                   3991:         my @parts=split('/',$fpath);
                   3992:         foreach my $part (@parts) {
                   3993:             $filepath.= '/'.$part;
                   3994:             if ((-e $filepath)!=1) {
                   3995:                 mkdir($filepath,0777);
                   3996:             }
                   3997:         }
                   3998:     }
                   3999:     return $filepath;
                   4000: }
                   4001: 
                   4002: sub store_edited_file {
1.638     albertel 4003:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  4004:     my $file = $primary_url;
                   4005:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   4006:     my $fpath = '';
                   4007:     my $fname = $file;
                   4008:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   4009:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   4010:     my $filepath = &build_filepath($fpath);
1.1172.2.96  raeburn  4011:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  4012:     print $fh $content;
                   4013:     close($fh);
1.638     albertel 4014:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  4015:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4016: 			  $home);
1.637     raeburn  4017:     if ($$fetchresult eq 'ok') {
                   4018:         return '/uploaded/'.$fpath.'/'.$fname;
                   4019:     } else {
1.638     albertel 4020:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   4021: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  4022:         return '/adm/notfound.html';
                   4023:     }
                   4024: }
                   4025: 
1.531     albertel 4026: sub clean_filename {
1.831     albertel 4027:     my ($fname,$args)=@_;
1.315     www      4028: # Replace Windows backslashes by forward slashes
1.257     www      4029:     $fname=~s/\\/\//g;
1.831     albertel 4030:     if (!$args->{'keep_path'}) {
                   4031:         # Get rid of everything but the actual filename
                   4032: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   4033:     }
1.315     www      4034: # Replace spaces by underscores
                   4035:     $fname=~s/\s+/\_/g;
1.1172.2.110  raeburn  4036: # Transliterate non-ascii text to ascii
                   4037:     my $lang = &Apache::lonlocal::current_language();
                   4038:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      4039: # Replace all other weird characters by nothing
1.831     albertel 4040:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 4041: # Replace all .\d. sequences with _\d. so they no longer look like version
                   4042: # numbers
                   4043:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1172.2.140  raeburn  4044: # Replace three or more adjacent underscores with one for consistency
                   4045: # with loncfile::filename_check() so complete url can be extracted by
                   4046: # lonnet::decode_symb()
                   4047:     $fname=~s/_{3,}/_/g;
1.531     albertel 4048:     return $fname;
                   4049: }
1.1172.2.110  raeburn  4050: 
1.1051    raeburn  4051: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   4052: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   4053: # image with the same aspect ratio as the original, but with dimensions which do 
                   4054: # not exceed $resizewidth and $resizeheight.
                   4055:  
1.984     neumanie 4056: sub resizeImage {
1.1051    raeburn  4057:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   4058:     my $ima = Image::Magick->new;
                   4059:     my $resized;
                   4060:     if (-e $img_path) {
                   4061:         $ima->Read($img_path);
                   4062:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   4063:             my $width = $ima->Get('width');
                   4064:             my $height = $ima->Get('height');
                   4065:             if ($width > $resizewidth) {
                   4066: 	        my $factor = $width/$resizewidth;
                   4067:                 my $newheight = $height/$factor;
                   4068:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   4069:                 $resized = 1;
                   4070:             }
                   4071:         }
                   4072:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   4073:             my $width = $ima->Get('width');
                   4074:             my $height = $ima->Get('height');
                   4075:             if ($height > $resizeheight) {
                   4076:                 my $factor = $height/$resizeheight;
                   4077:                 my $newwidth = $width/$factor;
                   4078:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   4079:                 $resized = 1;
                   4080:             }
                   4081:         }
                   4082:         if ($resized) {
                   4083:             $ima->Write($img_path);
                   4084:         }
                   4085:     }
                   4086:     return;
1.977     amueller 4087: }
                   4088: 
1.608     albertel 4089: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 4090: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  4091: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  4092: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1172.2.146.  .13(raeb 4093:-23): #                                    canceloverwrite, scantron, toollogo or ''. 
1.1090    raeburn  4094: #                   if 'coursedoc': upload to the current course
                   4095: #                   if 'existingfile': write file to tmp/overwrites directory 
                   4096: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   4097: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 4098: #        $subdir - directory in userfile to store the file into
1.1172.2.109  raeburn  4099: #        $parser - instruction to parse file for objects ($parser = parse) or
                   4100: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   4101: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
                   4102: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  4103: #        $allfiles - reference to hash for embedded objects
                   4104: #        $codebase - reference to hash for codebase of java objects
1.1172.2.146.  .13(raeb 4105:-23): #        $destuname - username for permanent storage of uploaded file
                   4106:-23): #        $destudom - domain for permanaent storage of uploaded file
1.860     raeburn  4107: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   4108: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  4109: #        $resizewidth - width (pixels) to which to resize uploaded image
                   4110: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  4111: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  4112: #                    from File::MMagic.
1.858     raeburn  4113: # 
1.686     albertel 4114: # output: url of file in userspace, or error: <message> 
                   4115: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 4116: 
1.531     albertel 4117: sub userfileupload {
1.1090    raeburn  4118:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  4119:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 4120:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 4121:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 4122:     $fname=&clean_filename($fname);
1.1090    raeburn  4123:     # See if there is anything left
1.257     www      4124:     unless ($fname) { return 'error: no uploaded file'; }
1.1172.2.110  raeburn  4125:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   4126:     if ($fname =~ /^\./) {
                   4127:         my ($s,$usec) = &gettimeofday();
                   4128:         while (length($usec) < 6) {
                   4129:             $usec = '0'.$usec;
                   4130:         }
                   4131:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   4132:     }
1.1090    raeburn  4133:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   4134:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   4135:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   4136:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  4137:         my $now = time;
1.1090    raeburn  4138:         my $filepath;
1.1095    raeburn  4139:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  4140:              $filepath = 'tmp/helprequests/'.$now;
                   4141:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   4142:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   4143:                          '_'.$env{'user.domain'}.'/pending';
                   4144:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   4145:             my ($docuname,$docudom);
1.1172.2.96  raeburn  4146:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  4147:                 $docudom = $destudom;
                   4148:             } else {
                   4149:                 $docudom = $env{'user.domain'};
                   4150:             }
1.1172.2.96  raeburn  4151:             if ($destuname =~ /^$match_username$/) { 
1.1090    raeburn  4152:                 $docuname = $destuname;
                   4153:             } else {
                   4154:                 $docuname = $env{'user.name'};
                   4155:             }
                   4156:             if (exists($env{'form.group'})) {
                   4157:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4158:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4159:             }
                   4160:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   4161:             if ($context eq 'canceloverwrite') {
                   4162:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   4163:                 if (-e  $tempfile) {
                   4164:                     my @info = stat($tempfile);
                   4165:                     if ($info[9] eq $env{'form.timestamp'}) {
                   4166:                         unlink($tempfile);
                   4167:                     }
                   4168:                 }
                   4169:                 return;
1.523     raeburn  4170:             }
                   4171:         }
1.1090    raeburn  4172:         # Create the directory if not present
1.741     raeburn  4173:         my @parts=split(/\//,$filepath);
                   4174:         my $fullpath = $perlvar{'lonDaemons'};
                   4175:         for (my $i=0;$i<@parts;$i++) {
                   4176:             $fullpath .= '/'.$parts[$i];
                   4177:             if ((-e $fullpath)!=1) {
                   4178:                 mkdir($fullpath,0777);
                   4179:             }
                   4180:         }
1.1172.2.96  raeburn  4181:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  4182:         print $fh $env{'form.'.$formname};
                   4183:         close($fh);
1.1090    raeburn  4184:         if ($context eq 'existingfile') {
                   4185:             my @info = stat($fullpath.'/'.$fname);
                   4186:             return ($fullpath.'/'.$fname,$info[9]);
                   4187:         } else {
                   4188:             return $fullpath.'/'.$fname;
                   4189:         }
1.523     raeburn  4190:     }
1.995     raeburn  4191:     if ($subdir eq 'scantron') {
                   4192:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  4193:     } else {
1.995     raeburn  4194:         $fname="$subdir/$fname";
                   4195:     }
1.1090    raeburn  4196:     if ($context eq 'coursedoc') {
1.638     albertel 4197: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4198: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  4199:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 4200:             return &finishuserfileupload($docuname,$docudom,
                   4201: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  4202: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  4203:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  4204:         } else {
1.1172.2.21  raeburn  4205:             if ($env{'form.folder'}) {
                   4206:                 $fname=$env{'form.folder'}.'/'.$fname;
                   4207:             }
1.638     albertel 4208:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   4209: 				       $fname,$formname,$parser,
1.1095    raeburn  4210: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  4211:         }
1.719     banghart 4212:     } elsif (defined($destuname)) {
                   4213:         my $docuname=$destuname;
                   4214:         my $docudom=$destudom;
1.860     raeburn  4215: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4216: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4217:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4218:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4219:     } else {
1.638     albertel 4220:         my $docuname=$env{'user.name'};
                   4221:         my $docudom=$env{'user.domain'};
1.1172.2.23  raeburn  4222:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  4223:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4224:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4225:         }
1.860     raeburn  4226: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4227: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4228:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4229:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4230:     }
1.271     www      4231: }
                   4232: 
                   4233: sub finishuserfileupload {
1.860     raeburn  4234:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  4235:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  4236:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      4237:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 4238:   
1.860     raeburn  4239:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 4240:     $file=$fname;
                   4241:     if ($fname=~m|/|) {
                   4242:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   4243: 	$path.=$fnamepath.'/';
                   4244:     }
1.259     www      4245:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      4246:     my $count;
                   4247:     for ($count=4;$count<=$#parts;$count++) {
                   4248:         $filepath.="/$parts[$count]";
                   4249:         if ((-e $filepath)!=1) {
                   4250: 	    mkdir($filepath,0777);
                   4251:         }
                   4252:     }
1.984     neumanie 4253: 
1.258     www      4254: # Save the file
                   4255:     {
1.1172.2.96  raeburn  4256: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4257: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4258: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4259: 	    return '/adm/notfound.html';
                   4260: 	}
1.1090    raeburn  4261:         if ($context eq 'overwrite') {
1.1117    foxr     4262:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4263:             my $target = $filepath.'/'.$file;
                   4264:             if (-e $source) {
                   4265:                 my @info = stat($source);
                   4266:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4267:                     unless (&File::Copy::move($source,$target)) {
                   4268:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4269:                         return "Moving from $source failed";
                   4270:                     }
                   4271:                 } else {
                   4272:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4273:                 }
                   4274:             } else {
                   4275:                 return "Temporary file: $source missing";
                   4276:             }
                   4277:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4278: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4279: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4280: 	    return '/adm/notfound.html';
                   4281: 	}
1.570     albertel 4282: 	close(FH);
1.1051    raeburn  4283:         if ($resizewidth && $resizeheight) {
                   4284:             my $mm = new File::MMagic;
                   4285:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4286:             if ($mime_type =~ m{^image/}) {
                   4287: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4288:             }  
1.977     amueller 4289: 	}
1.258     www      4290:     }
1.1152    raeburn  4291:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4292:         if (ref($mimetype)) {
                   4293:             if ($$mimetype eq '') {
                   4294:                 my $mm = new File::MMagic;
                   4295:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4296:                 $$mimetype = $type;
                   4297:             }
                   4298:         }
                   4299:     }
1.1172.2.109  raeburn  4300:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4301:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4302:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4303:                                                        $allfiles,$codebase);
                   4304:             unless ($parse_result eq 'ok') {
                   4305:                 &logthis('Failed to parse '.$filepath.$file.
                   4306: 	   	         ' for embedded media: '.$parse_result); 
                   4307:             }
1.637     raeburn  4308:         }
1.1172.2.109  raeburn  4309:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4310:         my $format = $env{'form.scantron_format'};
                   4311:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4312:     }
1.860     raeburn  4313:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4314:         my $input = $filepath.'/'.$file;
                   4315:         my $output = $filepath.'/'.'tn-'.$file;
1.1172.2.146.  .13(raeb 4316:-23):         my $makethumb;
1.860     raeburn  4317:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1172.2.146.  .13(raeb 4318:-23):         if ($context eq 'toollogo') {
                   4319:-23):             my ($fullwidth,$fullheight) = &check_dimensions($input);
                   4320:-23):             if ($fullwidth ne '' && $fullheight ne '') {
                   4321:-23):                 if ($fullwidth > $thumbwidth && $fullheight > $thumbheight) {
                   4322:-23):                     $makethumb = 1;
                   4323:-23):                 }
                   4324:-23):             }
                   4325:-23):         } else {
                   4326:-23):             $makethumb = 1;
                   4327:-23):         }
                   4328:-23):         if ($makethumb) {
                   4329:-23):             my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4330:-23):             system({$args[0]} @args);
                   4331:-23):             if (-e $filepath.'/'.'tn-'.$file) {
                   4332:-23):                 $fetchthumb  = 1;
                   4333:-23):             }
1.860     raeburn  4334:         }
                   4335:     }
1.858     raeburn  4336:  
1.259     www      4337: # Notify homeserver to grep it
                   4338: #
1.984     neumanie 4339:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4340:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4341:     if ($fetchresult eq 'ok') {
1.860     raeburn  4342:         if ($fetchthumb) {
                   4343:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4344:             if ($thumbresult ne 'ok') {
                   4345:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4346:                          $docuhome.': '.$thumbresult);
                   4347:             }
                   4348:         }
1.259     www      4349: #
1.258     www      4350: # Return the URL to it
1.494     albertel 4351:         return '/uploaded/'.$path.$file;
1.263     www      4352:     } else {
1.494     albertel 4353:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4354: 		 ': '.$fetchresult);
1.263     www      4355:         return '/adm/notfound.html';
1.858     raeburn  4356:     }
1.493     albertel 4357: }
                   4358: 
1.637     raeburn  4359: sub extract_embedded_items {
1.961     raeburn  4360:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4361:     my @state = ();
1.1164    raeburn  4362:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4363:     my %javafiles = (
                   4364:                       codebase => '',
                   4365:                       code => '',
                   4366:                       archive => ''
                   4367:                     );
                   4368:     my %mediafiles = (
                   4369:                       src => '',
                   4370:                       movie => '',
                   4371:                      );
1.648     raeburn  4372:     my $p;
                   4373:     if ($content) {
                   4374:         $p = HTML::LCParser->new($content);
                   4375:     } else {
1.961     raeburn  4376:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4377:     }
1.641     albertel 4378:     while (my $t=$p->get_token()) {
1.640     albertel 4379: 	if ($t->[0] eq 'S') {
                   4380: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4381: 	    push(@state, $tagname);
1.648     raeburn  4382:             if (lc($tagname) eq 'allow') {
                   4383:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4384:             }
1.640     albertel 4385: 	    if (lc($tagname) eq 'img') {
                   4386: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4387: 	    }
1.886     albertel 4388: 	    if (lc($tagname) eq 'a') {
1.1172.2.24  raeburn  4389:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
                   4390: 		    &add_filetype($allfiles,$attr->{'href'},'href');
                   4391:                 }
1.886     albertel 4392: 	    }
1.645     raeburn  4393:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4394:                 my $src;
1.645     raeburn  4395:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4396:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4397:                 } else {
1.1164    raeburn  4398:                     if ($attr->{'src'} ne '') {
                   4399:                         $src = $attr->{'src'};
                   4400:                         &add_filetype($allfiles,$src,'src');
                   4401:                     }
                   4402:                 }
                   4403:                 my $text = $p->get_trimmed_text();
                   4404:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4405:                     my @swfargs = split(/,/,$1);
                   4406:                     foreach my $item (@swfargs) {
                   4407:                         $item =~ s/["']//g;
                   4408:                         $item =~ s/^\s+//;
                   4409:                         $item =~ s/\s+$//;
                   4410:                     }
                   4411:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4412:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4413:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4414:                         } else {
                   4415:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4416:                         }
                   4417:                     }
1.645     raeburn  4418:                 }
                   4419:             }
                   4420:             if (lc($tagname) eq 'link') {
                   4421:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4422:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4423:                 }
                   4424:             }
1.640     albertel 4425: 	    if (lc($tagname) eq 'object' ||
                   4426: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4427: 		foreach my $item (keys(%javafiles)) {
                   4428: 		    $javafiles{$item} = '';
                   4429: 		}
1.1164    raeburn  4430:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4431:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4432:                 }
1.640     albertel 4433: 	    }
                   4434: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4435: 		my $name = lc($attr->{'name'});
                   4436: 		foreach my $item (keys(%javafiles)) {
                   4437: 		    if ($name eq $item) {
                   4438: 			$javafiles{$item} = $attr->{'value'};
                   4439: 			last;
                   4440: 		    }
                   4441: 		}
1.1164    raeburn  4442:                 my $pathfrom;
1.640     albertel 4443: 		foreach my $item (keys(%mediafiles)) {
                   4444: 		    if ($name eq $item) {
1.1164    raeburn  4445:                         $pathfrom = $attr->{'value'};
                   4446:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4447: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4448: 			last;
                   4449: 		    }
                   4450: 		}
1.1164    raeburn  4451:                 if ($name eq 'flashvars') {
                   4452:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4453:                 }
                   4454:                 if ($pathfrom ne '') {
                   4455:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4456:                                          $pathfrom);
                   4457:                 }
1.640     albertel 4458: 	    }
                   4459: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4460: 		foreach my $item (keys(%javafiles)) {
                   4461: 		    if ($attr->{$item}) {
                   4462: 			$javafiles{$item} = $attr->{$item};
                   4463: 			last;
                   4464: 		    }
                   4465: 		}
                   4466: 		foreach my $item (keys(%mediafiles)) {
                   4467: 		    if ($attr->{$item}) {
                   4468: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4469: 			last;
                   4470: 		    }
                   4471: 		}
1.1164    raeburn  4472:                 if (lc($tagname) eq 'embed') {
                   4473:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4474:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4475:                                              $attr->{'src'});
                   4476:                     }
                   4477:                 }
1.640     albertel 4478: 	    }
1.1172.2.35  raeburn  4479:             if (lc($tagname) eq 'iframe') {
                   4480:                 my $src = $attr->{'src'} ;
                   4481:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4482:                     &add_filetype($allfiles,$src,'src');
                   4483:                 } elsif ($src =~ m{^/}) {
                   4484:                     if ($env{'request.course.id'}) {
                   4485:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4486:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4487:                         my $url = &hreflocation('',$fullpath);
                   4488:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4489:                             my $relpath = $1;
                   4490:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4491:                                 &add_filetype($allfiles,$1,'src');
                   4492:                             }
                   4493:                         }
                   4494:                     }
                   4495:                 }
                   4496:             }
1.1164    raeburn  4497:             if ($t->[4] =~ m{/>$}) {
1.1172.2.35  raeburn  4498:                 pop(@state);
1.1164    raeburn  4499:             }
1.640     albertel 4500: 	} elsif ($t->[0] eq 'E') {
                   4501: 	    my ($tagname) = ($t->[1]);
                   4502: 	    if ($javafiles{'codebase'} ne '') {
                   4503: 		$javafiles{'codebase'} .= '/';
                   4504: 	    }  
                   4505: 	    if (lc($tagname) eq 'applet' ||
                   4506: 		lc($tagname) eq 'object' ||
                   4507: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4508: 		) {
                   4509: 		foreach my $item (keys(%javafiles)) {
                   4510: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4511: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4512: 			&add_filetype($allfiles,$file,$item);
                   4513: 		    }
                   4514: 		}
                   4515: 	    } 
                   4516: 	    pop @state;
                   4517: 	}
                   4518:     }
1.1164    raeburn  4519:     foreach my $id (sort(keys(%flashvars))) {
                   4520:         if ($shockwave{$id} ne '') {
                   4521:             my @pairs = split(/\&/,$flashvars{$id});
                   4522:             foreach my $pair (@pairs) {
                   4523:                 my ($key,$value) = split(/\=/,$pair);
                   4524:                 if ($key eq 'thumb') {
                   4525:                     &add_filetype($allfiles,$value,$key);
                   4526:                 } elsif ($key eq 'content') {
                   4527:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4528:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4529:                     if ($ext ne '') {
                   4530:                         &add_filetype($allfiles,$path.$value,$ext);
                   4531:                     }
                   4532:                 }
                   4533:             }
                   4534:         }
                   4535:     }
1.637     raeburn  4536:     return 'ok';
                   4537: }
                   4538: 
1.639     albertel 4539: sub add_filetype {
                   4540:     my ($allfiles,$file,$type)=@_;
                   4541:     if (exists($allfiles->{$file})) {
                   4542: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4543: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4544: 	}
                   4545:     } else {
                   4546: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4547:     }
                   4548: }
                   4549: 
1.1164    raeburn  4550: sub embedded_dependency {
                   4551:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4552:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4553:         if (($identifier ne '') &&
                   4554:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4555:             ($pathfrom ne '')) {
                   4556:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4557:             foreach my $dep (@{$related->{$identifier}}) {
                   4558:                 &add_filetype($allfiles,$path.$dep,'object');
                   4559:             }
                   4560:         }
                   4561:     }
                   4562:     return;
                   4563: }
                   4564: 
1.1172.2.146.  .13(raeb 4565:-23): sub check_dimensions {
                   4566:-23):     my ($inputfile) = @_;
                   4567:-23):     my ($fullwidth,$fullheight);
                   4568:-23):     if (($inputfile =~ m|^[/\w.\-]+$|) && (-e $inputfile)) {
                   4569:-23):         my $mm = new File::MMagic;
                   4570:-23):         my $mime_type = $mm->checktype_filename($inputfile);
                   4571:-23):         if ($mime_type =~ m{^image/}) {
                   4572:-23):             if (open(PIPE,"identify $inputfile 2>&1 |")) {
                   4573:-23):                 my $imageinfo = <PIPE>;
                   4574:-23):                 if (!close(PIPE)) {
                   4575:-23):                     &Apache::lonnet::logthis("Failed to close PIPE opened to retrieve image information for $inputfile");
                   4576:-23):                 }
                   4577:-23):                 chomp($imageinfo);
                   4578:-23):                 my ($fullsize) =
                   4579:-23):                     ($imageinfo =~ /^\Q$inputfile\E\s+\w+\s+(\d+x\d+)/);
                   4580:-23):                 if ($fullsize) {
                   4581:-23):                     ($fullwidth,$fullheight) = split(/x/,$fullsize);
                   4582:-23):                 }
                   4583:-23):             }
                   4584:-23):         }
                   4585:-23):     }
                   4586:-23):     return ($fullwidth,$fullheight);
                   4587:-23): }
                   4588:-23): 
1.1172.2.109  raeburn  4589: sub bubblesheet_converter {
                   4590:     my ($cdom,$fullpath,$config,$format) = @_;
                   4591:     if ((&domain($cdom) ne '') &&
                   4592:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
                   4593:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
                   4594:         my (%csvcols,%csvoptions);
                   4595:         if (ref($config->{'fields'}) eq 'HASH') {
                   4596:             %csvcols = %{$config->{'fields'}};
                   4597:         }
                   4598:         if (ref($config->{'options'}) eq 'HASH') {
                   4599:             %csvoptions = %{$config->{'options'}};
                   4600:         }
                   4601:         my %csvbynum = reverse(%csvcols);
                   4602:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4603:         if (keys(%scantronconf)) {
                   4604:             my %bynum = (
                   4605:                           $scantronconf{CODEstart} => 'CODEstart',
                   4606:                           $scantronconf{IDstart}   => 'IDstart',
                   4607:                           $scantronconf{PaperID}   => 'PaperID',
                   4608:                           $scantronconf{FirstName} => 'FirstName',
                   4609:                           $scantronconf{LastName}  => 'LastName',
                   4610:                           $scantronconf{Qstart}    => 'Qstart',
                   4611:                         );
                   4612:             my @ordered;
                   4613:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
                   4614:                 push(@ordered,$bynum{$item});
                   4615:             }
                   4616:             my %mapstart = (
                   4617:                               CODEstart => 'CODE',
                   4618:                               IDstart   => 'ID',
                   4619:                               PaperID   => 'PaperID',
                   4620:                               FirstName => 'FirstName',
                   4621:                               LastName  => 'LastName',
                   4622:                               Qstart    => 'FirstQuestion',
                   4623:                            );
                   4624:             my %maplength = (
                   4625:                               CODEstart => 'CODElength',
                   4626:                               IDstart   => 'IDlength',
                   4627:                               PaperID   => 'PaperIDlength',
                   4628:                               FirstName => 'FirstNamelength',
                   4629:                               LastName  => 'LastNamelength',
                   4630:             );
                   4631:             if (open(my $fh,'<',$fullpath)) {
                   4632:                 my $output;
                   4633:                 my %lettdig = &letter_to_digits();
                   4634:                 my %diglett = reverse(%lettdig);
                   4635:                 my $numletts = scalar(keys(%lettdig));
                   4636:                 my $num = 0;
                   4637:                 while (my $line=<$fh>) {
                   4638:                     $num ++;
                   4639:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
                   4640:                     $line =~ s{[\r\n]+$}{};
                   4641:                     my %found;
1.1172.2.143  raeburn  4642:                     my @values = split(/,/,$line,-1);
1.1172.2.109  raeburn  4643:                     my ($qstart,$record);
                   4644:                     for (my $i=0; $i<@values; $i++) {
                   4645:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4646:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4647:                             if ($values[$i] eq '') {
                   4648:                                 $values[$i] = $scantronconf{'Qoff'};
                   4649:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4650:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4651:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4652:                                 }
                   4653:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4654:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4655:                                     $values[$i] = $diglett{$values[$i]};
                   4656:                                 }
                   4657:                             } else {
                   4658:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4659:                                     my $digit;
                   4660:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4661:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4662:                                         if ($values[$i] eq 'J') {
                   4663:                                             $digit += $numletts;
                   4664:                                         }
                   4665:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4666:                                         $digit = $values[$i]-1;
                   4667:                                         if ($values[$i] eq '0') {
                   4668:                                             $digit += $numletts;
                   4669:                                         }
                   4670:                                     }
                   4671:                                     my $qval='';
                   4672:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4673:                                         if ($j == $digit) {
                   4674:                                             $qval .= $scantronconf{'Qon'};
                   4675:                                         } else {
                   4676:                                             $qval .= $scantronconf{'Qoff'};
                   4677:                                         }
                   4678:                                     }
                   4679:                                     $values[$i] = $qval;
                   4680:                                 }
                   4681:                             }
                   4682:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4683:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4684:                             }
                   4685:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4686:                             if ($numblank > 0) {
                   4687:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4688:                             }
                   4689:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4690:                                 $qstart = $i;
                   4691:                                 $found{$csvbynum{$i}} = $values[$i];
                   4692:                             } else {
                   4693:                                 $found{'FirstQuestion'} .= $values[$i];
                   4694:                             }
                   4695:                         } elsif (exists($csvbynum{$i})) {
                   4696:                             if ($csvoptions{'rem'}) {
                   4697:                                 $values[$i] =~ s/^\s+//;
                   4698:                             }
                   4699:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
                   4700:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4701:                                     $values[$i] = '0'.$values[$i];
                   4702:                                 }
                   4703:                             }
                   4704:                             $found{$csvbynum{$i}} = $values[$i];
                   4705:                         }
                   4706:                     }
                   4707:                     foreach my $item (@ordered) {
                   4708:                         my $currlength = 1+length($record);
                   4709:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4710:                         if ($numspaces > 0) {
                   4711:                             $record .= (' ' x $numspaces);
                   4712:                         }
                   4713:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4714:                             unless ($item eq 'Qstart') {
                   4715:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4716:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4717:                                 }
                   4718:                             }
                   4719:                             $record .= $found{$mapstart{$item}};
                   4720:                         }
                   4721:                     }
                   4722:                     $output .= "$record\n";
                   4723:                 }
                   4724:                 close($fh);
                   4725:                 if ($output) {
                   4726:                     if (open(my $fh,'>',$fullpath)) {
                   4727:                         print $fh $output;
                   4728:                         close($fh);
                   4729:                     }
                   4730:                 }
                   4731:             }
                   4732:         }
                   4733:         return;
                   4734:     }
                   4735: }
                   4736: 
                   4737: sub letter_to_digits {
                   4738:     my %lettdig = (
                   4739:                     A => 1,
                   4740:                     B => 2,
                   4741:                     C => 3,
                   4742:                     D => 4,
                   4743:                     E => 5,
                   4744:                     F => 6,
                   4745:                     G => 7,
                   4746:                     H => 8,
                   4747:                     I => 9,
                   4748:                     J => 0,
                   4749:                   );
                   4750:     return %lettdig;
                   4751: }
                   4752: 
                   4753: sub get_scantron_config {
                   4754:     my ($which,$cdom) = @_;
                   4755:     my @lines = &get_scantronformat_file($cdom);
                   4756:     my %config;
                   4757:     #FIXME probably should move to XML it has already gotten a bit much now
                   4758:     foreach my $line (@lines) {
                   4759:         my ($name,$descrip)=split(/:/,$line);
                   4760:         if ($name ne $which ) { next; }
                   4761:         chomp($line);
                   4762:         my @config=split(/:/,$line);
                   4763:         $config{'name'}=$config[0];
                   4764:         $config{'description'}=$config[1];
                   4765:         $config{'CODElocation'}=$config[2];
                   4766:         $config{'CODEstart'}=$config[3];
                   4767:         $config{'CODElength'}=$config[4];
                   4768:         $config{'IDstart'}=$config[5];
                   4769:         $config{'IDlength'}=$config[6];
                   4770:         $config{'Qstart'}=$config[7];
                   4771:         $config{'Qlength'}=$config[8];
                   4772:         $config{'Qoff'}=$config[9];
                   4773:         $config{'Qon'}=$config[10];
                   4774:         $config{'PaperID'}=$config[11];
                   4775:         $config{'PaperIDlength'}=$config[12];
                   4776:         $config{'FirstName'}=$config[13];
                   4777:         $config{'FirstNamelength'}=$config[14];
                   4778:         $config{'LastName'}=$config[15];
                   4779:         $config{'LastNamelength'}=$config[16];
                   4780:         $config{'BubblesPerRow'}=$config[17];
                   4781:         last;
                   4782:     }
                   4783:     return %config;
                   4784: }
                   4785: 
                   4786: sub get_scantronformat_file {
                   4787:     my ($cdom) = @_;
                   4788:     if ($cdom eq '') {
                   4789:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4790:     }
                   4791:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4792:     my $gottab = 0;
                   4793:     my @lines;
                   4794:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4795:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4796:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4797:             if ($formatfile ne '-1') {
                   4798:                 @lines = split("\n",$formatfile,-1);
                   4799:                 $gottab = 1;
                   4800:             }
                   4801:         }
                   4802:     }
                   4803:     if (!$gottab) {
                   4804:         my $confname = $cdom.'-domainconfig';
                   4805:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4806:         my $formatfile = &getfile($default);
                   4807:         if ($formatfile ne '-1') {
                   4808:             @lines = split("\n",$formatfile,-1);
                   4809:             $gottab = 1;
                   4810:         }
                   4811:     }
                   4812:     if (!$gottab) {
                   4813:         my @domains = &current_machine_domains();
                   4814:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4815:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4816:                 @lines = <$fh>;
                   4817:                 close($fh);
                   4818:             }
                   4819:         } else {
                   4820:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4821:                 @lines = <$fh>;
                   4822:                 close($fh);
                   4823:             }
                   4824:         }
1.1172.2.146.  .8(raebu 4825:23):         chomp(@lines);
1.1172.2.109  raeburn  4826:     }
                   4827:     return @lines;
                   4828: }
                   4829: 
1.493     albertel 4830: sub removeuploadedurl {
1.984     neumanie 4831:     my ($url)=@_;	
                   4832:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4833:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4834: }
                   4835: 
                   4836: sub removeuserfile {
                   4837:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4838:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4839:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4840:     if ($result eq 'ok') {	
1.798     raeburn  4841:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4842:             my $metafile = $fname.'.meta';
                   4843:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4844: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4845:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4846:             my $sqlresult = 
1.823     albertel 4847:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4848:                                         'portfolio_metadata',$group,
                   4849:                                         'delete');
1.798     raeburn  4850:         }
                   4851:     }
                   4852:     return $result;
1.257     www      4853: }
1.15      www      4854: 
1.530     albertel 4855: sub mkdiruserfile {
                   4856:     my ($docuname,$docudom,$dir)=@_;
                   4857:     my $home=&homeserver($docuname,$docudom);
                   4858:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4859: }
                   4860: 
1.531     albertel 4861: sub renameuserfile {
                   4862:     my ($docuname,$docudom,$old,$new)=@_;
                   4863:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4864:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4865:                         &escape("$old").':'.&escape("$new"),$home);
                   4866:     if ($result eq 'ok') {
                   4867:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4868:             my $oldmeta = $old.'.meta';
                   4869:             my $newmeta = $new.'.meta';
                   4870:             my $metaresult = 
                   4871:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4872: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4873:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4874:             my $sqlresult = 
1.823     albertel 4875:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4876:                                         'portfolio_metadata',$group,
                   4877:                                         'delete');
1.798     raeburn  4878:         }
                   4879:     }
                   4880:     return $result;
1.531     albertel 4881: }
                   4882: 
1.14      www      4883: # ------------------------------------------------------------------------- Log
                   4884: 
                   4885: sub log {
                   4886:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4887:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4888: }
                   4889: 
                   4890: # ------------------------------------------------------------------ Course Log
1.352     www      4891: #
                   4892: # This routine flushes several buffers of non-mission-critical nature
                   4893: #
1.157     www      4894: 
                   4895: sub flushcourselogs {
1.352     www      4896:     &logthis('Flushing log buffers');
                   4897: #
                   4898: # course logs
                   4899: # This is a log of all transactions in a course, which can be used
                   4900: # for data mining purposes
                   4901: #
                   4902: # It also collects the courseid database, which lists last transaction
                   4903: # times and course titles for all courseids
                   4904: #
                   4905:     my %courseidbuffer=();
1.921     raeburn  4906:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4907:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4908: 		          &escape($courselogs{$crsid}),
                   4909: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4910: 	    delete $courselogs{$crsid};
                   4911:         } else {
                   4912:             &logthis('Failed to flush log buffer for '.$crsid);
                   4913:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4914:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4915:                         " exceeded maximum size, deleting.</font>");
                   4916:                delete $courselogs{$crsid};
                   4917:             }
1.352     www      4918:         }
1.920     raeburn  4919:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4920:             'description' => $coursedescrbuf{$crsid},
                   4921:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4922:             'type'        => $coursetypebuf{$crsid},
                   4923:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4924:         };
1.191     harris41 4925:     }
1.352     www      4926: #
                   4927: # Write course id database (reverse lookup) to homeserver of courses 
                   4928: # Is used in pickcourse
                   4929: #
1.840     albertel 4930:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4931:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4932:                                     $courseidbuffer{$crs_home},
                   4933:                                     $crs_home,'timeonly');
1.352     www      4934:     }
                   4935: #
                   4936: # File accesses
                   4937: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4938: #
1.449     matthew  4939:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4940:         if ($entry =~ /___count$/) {
                   4941:             my ($dom,$name);
1.807     albertel 4942:             ($dom,$name,undef)=
1.811     albertel 4943: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4944:             if (! defined($dom) || $dom eq '' || 
                   4945:                 ! defined($name) || $name eq '') {
1.620     albertel 4946:                 my $cid = $env{'request.course.id'};
1.1172.2.142  raeburn  4947: #
                   4948: # FIXME 11/29/2021
                   4949: # Typo in rev. 1.458 (2003/12/09)??
                   4950: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
                   4951: #
1.1172.2.146.  .13(raeb 4952:-23): # While these remain as $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
1.1172.2.142  raeburn  4953: # $dom and $name will always be null, so the &inc() call will default to storing this data
                   4954: # in a nohist_accesscount.db file for the user rather than the course.
                   4955: #
                   4956: # That said there is a lot of noise in the data being stored.
                   4957: # So counts for prtspool/  and adm/ etc. are recorded.
                   4958: #
                   4959: # A review of which items ending '___count' are written to %accesshash should likely be
                   4960: # made before deciding whether to set these to 'course.' instead of 'request.'
                   4961: #
                   4962: # Under the current scheme each user receives a nohist_accesscount.db file listing
                   4963: # accesses for things which are not published resources, regardless of course, and
                   4964: # there is not a nohist_accesscount.db file in a course, which might log accesses from
                   4965: # anyone in the course for things which are not published resources.
                   4966: #
                   4967: # For an author, nohist_accesscount.db ends up having records for other items
                   4968: # mixed up with the legitimate access counts for the author's published resources.
                   4969: #
1.620     albertel 4970:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4971:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4972:             }
1.450     matthew  4973:             my $value = $accesshash{$entry};
                   4974:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4975:             my %temphash=($url => $value);
1.449     matthew  4976:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4977:             if ($result eq 'ok') {
                   4978:                 delete $accesshash{$entry};
                   4979:             }
                   4980:         } else {
1.811     albertel 4981:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4982:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4983:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4984:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4985:                 delete $accesshash{$entry};
                   4986:             }
1.185     www      4987:         }
1.191     harris41 4988:     }
1.352     www      4989: #
                   4990: # Roles
                   4991: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4992: #
1.800     albertel 4993:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4994:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4995: 	    split(/\:/,$entry);
                   4996:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4997:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4998:                 $rudom,$runame) eq 'ok') {
                   4999: 	    delete $userrolehash{$entry};
                   5000:         }
                   5001:     }
1.662     raeburn  5002: #
1.1172.2.90  raeburn  5003: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  5004: #
                   5005:     my %domrolebuffer = ();
1.1000    raeburn  5006:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 5007:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  5008:         if ($domrolebuffer{$rudom}) {
                   5009:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   5010:                       '='.&escape($domainrolehash{$entry});
                   5011:         } else {
                   5012:             $domrolebuffer{$rudom}.=&escape($entry).
                   5013:                       '='.&escape($domainrolehash{$entry});
                   5014:         }
                   5015:         delete $domainrolehash{$entry};
                   5016:     }
                   5017:     foreach my $dom (keys(%domrolebuffer)) {
1.1172.2.82  raeburn  5018:         my %servers;
                   5019:         if (defined(&domain($dom,'primary'))) {
                   5020:             my $primary=&domain($dom,'primary');
                   5021:             my $hostname=&hostname($primary);
                   5022:             $servers{$primary} = $hostname;
                   5023:         } else {
                   5024:             %servers = &get_servers($dom,'library');
                   5025:         }
1.841     albertel 5026: 	foreach my $tryserver (keys(%servers)) {
1.1172.2.82  raeburn  5027: 	    if (&reply('domroleput:'.$dom.':'.
                   5028: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   5029: 	        last;
                   5030: 	    } else {
1.841     albertel 5031: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   5032: 	    }
1.662     raeburn  5033:         }
                   5034:     }
1.186     www      5035:     $dumpcount++;
1.157     www      5036: }
                   5037: 
                   5038: sub courselog {
                   5039:     my $what=shift;
1.158     www      5040:     $what=time.':'.$what;
1.620     albertel 5041:     unless ($env{'request.course.id'}) { return ''; }
                   5042:     $coursedombuf{$env{'request.course.id'}}=
                   5043:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5044:     $coursenumbuf{$env{'request.course.id'}}=
                   5045:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   5046:     $coursehombuf{$env{'request.course.id'}}=
                   5047:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   5048:     $coursedescrbuf{$env{'request.course.id'}}=
                   5049:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   5050:     $courseinstcodebuf{$env{'request.course.id'}}=
                   5051:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   5052:     $courseownerbuf{$env{'request.course.id'}}=
                   5053:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  5054:     $coursetypebuf{$env{'request.course.id'}}=
                   5055:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 5056:     if (defined $courselogs{$env{'request.course.id'}}) {
                   5057: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      5058:     } else {
1.620     albertel 5059: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      5060:     }
1.620     albertel 5061:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      5062: 	&flushcourselogs();
                   5063:     }
1.158     www      5064: }
                   5065: 
                   5066: sub courseacclog {
                   5067:     my $fnsymb=shift;
1.620     albertel 5068:     unless ($env{'request.course.id'}) { return ''; }
                   5069:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      5070:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      5071:         $what.=':POST';
1.583     matthew  5072:         # FIXME: Probably ought to escape things....
1.800     albertel 5073: 	foreach my $key (keys(%env)) {
                   5074:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  5075:                 my $formitem = $1;
                   5076:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   5077:                     $what.=':'.$formitem.'='.$env{$key};
                   5078:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1172.2.131  raeburn  5079:                     if ($formitem eq 'proctorpassword') {
1.1172.2.132  raeburn  5080:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1172.2.131  raeburn  5081:                     } else {
                   5082:                         $what.=':'.$formitem.'='.$env{$key};
                   5083:                     }
1.975     raeburn  5084:                 }
1.158     www      5085:             }
1.191     harris41 5086:         }
1.583     matthew  5087:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   5088:         # FIXME: We should not be depending on a form parameter that someone
                   5089:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 5090:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  5091:             $what.= ':POST';
                   5092:             # FIXME: Probably ought to escape things....
                   5093:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   5094:                                  'crsdiscuss') {
1.620     albertel 5095:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  5096:             }
                   5097:         }
1.158     www      5098:     }
                   5099:     &courselog($what);
1.149     www      5100: }
                   5101: 
1.185     www      5102: sub countacc {
                   5103:     my $url=&declutter(shift);
1.458     matthew  5104:     return if (! defined($url) || $url eq '');
1.620     albertel 5105:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      5106: #
                   5107: # Mark that this url was used in this course
                   5108: #
1.620     albertel 5109:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      5110: #
                   5111: # Increase the access count for this resource in this child process
                   5112: #
1.281     www      5113:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  5114:     $accesshash{$key}++;
1.185     www      5115: }
1.349     www      5116: 
1.361     www      5117: sub linklog {
                   5118:     my ($from,$to)=@_;
                   5119:     $from=&declutter($from);
                   5120:     $to=&declutter($to);
                   5121:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   5122:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   5123: }
1.1160    www      5124: 
                   5125: sub statslog {
                   5126:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   5127:     if ($users<2) { return; }
                   5128:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   5129:             'course'       => $env{'request.course.id'},
                   5130:             'sections'     => '"all"',
                   5131:             'num_students' => $users,
                   5132:             'part'         => $part,
                   5133:             'symb'         => $symb,
                   5134:             'mean_tries'   => $av_attempts,
                   5135:             'deg_of_diff'  => $degdiff});
                   5136:     foreach my $key (keys(%dynstore)) {
                   5137:         $accesshash{$key}=$dynstore{$key};
                   5138:     }
                   5139: }
1.361     www      5140:   
1.349     www      5141: sub userrolelog {
                   5142:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 5143:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      5144:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5145:        $userrolehash
                   5146:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      5147:                     =$tend.':'.$tstart;
1.662     raeburn  5148:     }
1.1169    droeschl 5149:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 5150:        $userrolehash
                   5151:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   5152:                     =$tend.':'.$tstart;
                   5153:     }
1.1172.2.90  raeburn  5154:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  5155:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5156:        $domainrolehash
                   5157:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   5158:                     = $tend.':'.$tstart;
                   5159:     }
1.351     www      5160: }
                   5161: 
1.957     raeburn  5162: sub courserolelog {
                   5163:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1172.2.9  raeburn  5164:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   5165:         my $cdom = $1;
                   5166:         my $cnum = $2;
                   5167:         my $sec = $3;
                   5168:         my $namespace = 'rolelog';
                   5169:         my %storehash = (
                   5170:                            role    => $trole,
                   5171:                            start   => $tstart,
                   5172:                            end     => $tend,
                   5173:                            selfenroll => $selfenroll,
                   5174:                            context    => $context,
                   5175:                         );
                   5176:         if ($trole eq 'gr') {
                   5177:             $namespace = 'groupslog';
                   5178:             $storehash{'group'} = $sec;
                   5179:         } else {
                   5180:             $storehash{'section'} = $sec;
1.1172.2.146.  .16(raeb 5181:-23):             my ($curruserdomstr,$newuserdomstr);
                   5182:-23):             if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'})) {
                   5183:-23):                 $curruserdomstr = $env{'course.'.$env{'request.course.id'}.'.internal.userdomains'};
                   5184:-23):             } else {
                   5185:-23):                 my %courseinfo = &coursedescription($cdom.'/'.$cnum);
                   5186:-23):                 $curruserdomstr = $courseinfo{'internal.userdomains'};
                   5187:-23):             }
                   5188:-23):             if ($curruserdomstr ne '') {
                   5189:-23):                 my @udoms = split(/,/,$curruserdomstr);
                   5190:-23):                 unless (grep(/^\Q$domain\E/,@udoms)) {
                   5191:-23):                     push(@udoms,$domain);
                   5192:-23):                     $newuserdomstr = join(',',sort(@udoms));
                   5193:-23):                 }
                   5194:-23):             } else {
                   5195:-23):                 $newuserdomstr = $domain;
                   5196:-23):             }
                   5197:-23):             if ($newuserdomstr ne '') {
                   5198:-23):                 my $putresult = &put('environment',{ 'internal.userdomains' => $newuserdomstr },
                   5199:-23):                                      $cdom,$cnum);
                   5200:-23):                 if ($putresult eq 'ok') {
                   5201:-23):                     unless (($selfenroll) || ($context eq 'selfenroll')) {
                   5202:-23):                         if (($context eq 'createcourse') || ($context eq 'requestcourses') ||
                   5203:-23):                             ($context eq 'automated') || ($context eq 'domain')) {
                   5204:-23):                             $env{'course.'.$cdom.'_'.$cnum.'.internal.userdomains'} = $newuserdomstr;
                   5205:-23):                         } elsif ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   5206:-23):                             &appenv({'course.'.$cdom.'_'.$cnum.'.internal.userdomains' => $newuserdomstr});
                   5207:-23):                         }
                   5208:-23):                     }
                   5209:-23):                 }
                   5210:-23):             }
1.1172.2.9  raeburn  5211:         }
                   5212:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   5213:                    $domain,$cnum,$cdom);
                   5214:         if (($trole ne 'st') || ($sec ne '')) {
                   5215:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  5216:         }
                   5217:     }
                   5218:     return;
                   5219: }
                   5220: 
1.1172.2.9  raeburn  5221: sub domainrolelog {
                   5222:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5223:     if ($area =~ m{^/($match_domain)/$}) {
                   5224:         my $cdom = $1;
                   5225:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   5226:         my $namespace = 'rolelog';
                   5227:         my %storehash = (
                   5228:                            role    => $trole,
                   5229:                            start   => $tstart,
                   5230:                            end     => $tend,
                   5231:                            context => $context,
                   5232:                         );
                   5233:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   5234:                    $domain,$domconfiguser,$cdom);
                   5235:     }
                   5236:     return;
                   5237: 
                   5238: }
                   5239: 
                   5240: sub coauthorrolelog {
                   5241:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5242:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   5243:         my $audom = $1;
                   5244:         my $auname = $2;
                   5245:         my $namespace = 'rolelog';
                   5246:         my %storehash = (
                   5247:                            role    => $trole,
                   5248:                            start   => $tstart,
                   5249:                            end     => $tend,
                   5250:                            context => $context,
                   5251:                         );
                   5252:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   5253:                    $domain,$auname,$audom);
                   5254:     }
                   5255:     return;
                   5256: }
                   5257: 
1.351     www      5258: sub get_course_adv_roles {
1.948     raeburn  5259:     my ($cid,$codes) = @_;
1.620     albertel 5260:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      5261:     my %coursehash=&coursedescription($cid);
1.988     raeburn  5262:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      5263:     my %nothide=();
1.800     albertel 5264:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  5265:         if ($user !~ /:/) {
                   5266: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   5267:         } else {
                   5268:             $nothide{$user}=1;
                   5269:         }
1.470     www      5270:     }
1.1172.2.23  raeburn  5271:     my @possdoms = ($coursehash{'domain'});
                   5272:     if ($coursehash{'checkforpriv'}) {
                   5273:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   5274:     }
1.351     www      5275:     my %returnhash=();
                   5276:     my %dumphash=
                   5277:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   5278:     my $now=time;
1.997     raeburn  5279:     my %privileged;
1.1000    raeburn  5280:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 5281: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      5282:         if (($tstart) && ($tstart<0)) { next; }
                   5283:         if (($tend) && ($tend<$now)) { next; }
                   5284:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 5285:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 5286: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  5287:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  5288:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 5289: 	if ($role eq 'cr') { next; }
1.948     raeburn  5290:         if ($codes) {
                   5291:             if ($section) { $role .= ':'.$section; }
                   5292:             if ($returnhash{$role}) {
                   5293:                 $returnhash{$role}.=','.$username.':'.$domain;
                   5294:             } else {
                   5295:                 $returnhash{$role}=$username.':'.$domain;
                   5296:             }
1.351     www      5297:         } else {
1.988     raeburn  5298:             my $key=&plaintext($role,$crstype);
1.973     bisitz   5299:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  5300:             if ($returnhash{$key}) {
                   5301: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   5302:             } else {
                   5303:                 $returnhash{$key}=$username.':'.$domain;
                   5304:             }
1.351     www      5305:         }
1.948     raeburn  5306:     }
1.400     www      5307:     return %returnhash;
                   5308: }
                   5309: 
                   5310: sub get_my_roles {
1.937     raeburn  5311:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 5312:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   5313:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  5314:     my (%dumphash,%nothide);
1.1086    raeburn  5315:     if ($context eq 'userroles') {
1.1166    raeburn  5316:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  5317:     } else {
1.1172.2.23  raeburn  5318:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  5319:         if ($hidepriv) {
                   5320:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   5321:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   5322:                 if ($user !~ /:/) {
                   5323:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   5324:                 } else {
                   5325:                     $nothide{$user} = 1;
                   5326:                 }
                   5327:             }
                   5328:         }
1.858     raeburn  5329:     }
1.400     www      5330:     my %returnhash=();
                   5331:     my $now=time;
1.999     raeburn  5332:     my %privileged;
1.800     albertel 5333:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  5334:         my ($role,$tend,$tstart);
                   5335:         if ($context eq 'userroles') {
1.1149    raeburn  5336:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  5337: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   5338:         } else {
                   5339:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   5340:         }
1.400     www      5341:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  5342:         my $status = 'active';
1.939     raeburn  5343:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  5344:             $status = 'previous';
                   5345:         } 
                   5346:         if (($tstart) && ($now<$tstart)) {
                   5347:             $status = 'future';
                   5348:         }
                   5349:         if (ref($types) eq 'ARRAY') {
                   5350:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   5351:                 next;
                   5352:             } 
                   5353:         } else {
                   5354:             if ($status ne 'active') {
                   5355:                 next;
                   5356:             }
                   5357:         }
1.867     raeburn  5358:         my ($rolecode,$username,$domain,$section,$area);
                   5359:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  5360:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5361:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5362:         } else {
                   5363:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5364:         }
1.832     raeburn  5365:         if (ref($roledoms) eq 'ARRAY') {
                   5366:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5367:                 next;
                   5368:             }
                   5369:         }
                   5370:         if (ref($roles) eq 'ARRAY') {
                   5371:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5372:                 if ($role =~ /^cr\//) {
                   5373:                     if (!grep(/^cr$/,@{$roles})) {
                   5374:                         next;
                   5375:                     }
1.1104    raeburn  5376:                 } elsif ($role =~ /^gr\//) {
                   5377:                     if (!grep(/^gr$/,@{$roles})) {
                   5378:                         next;
                   5379:                     }
1.922     raeburn  5380:                 } else {
                   5381:                     next;
                   5382:                 }
1.832     raeburn  5383:             }
1.867     raeburn  5384:         }
1.937     raeburn  5385:         if ($hidepriv) {
1.1172.2.23  raeburn  5386:             my @privroles = ('dc','su');
1.999     raeburn  5387:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  5388:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5389:             } else {
1.1172.2.23  raeburn  5390:                 my $possdoms = [$domain];
                   5391:                 if (ref($roledoms) eq 'ARRAY') {
                   5392:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  5393:                 }
1.1172.2.23  raeburn  5394:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5395:                     if (!$nothide{$username.':'.$domain}) {
                   5396:                         next;
                   5397:                     }
                   5398:                 }
1.937     raeburn  5399:             }
                   5400:         }
1.933     raeburn  5401:         if ($withsec) {
                   5402:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5403:                 $tstart.':'.$tend;
                   5404:         } else {
                   5405:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5406:         }
1.832     raeburn  5407:     }
1.373     www      5408:     return %returnhash;
1.399     www      5409: }
                   5410: 
1.1172.2.89  raeburn  5411: sub get_all_adhocroles {
                   5412:     my ($dom) = @_;
                   5413:     my @roles_by_num = ();
                   5414:     my %domdefaults = &get_domain_defaults($dom);
                   5415:     my (%description,%access_in_dom,%access_info);
                   5416:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5417:         my $count = 0;
                   5418:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5419:         my %ordered;
                   5420:         foreach my $role (sort(keys(%domcurrent))) {
                   5421:             my ($order,$desc,$access_in_dom);
                   5422:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5423:                 $order = $domcurrent{$role}{'order'};
                   5424:                 $desc = $domcurrent{$role}{'desc'};
                   5425:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5426:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5427:             }
                   5428:             if ($order eq '') {
                   5429:                 $order = $count;
                   5430:             }
                   5431:             $ordered{$order} = $role;
                   5432:             if ($desc ne '') {
                   5433:                 $description{$role} = $desc;
                   5434:             } else {
                   5435:                 $description{$role}= $role;
                   5436:             }
                   5437:             $count++;
                   5438:         }
                   5439:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5440:             push(@roles_by_num,$ordered{$item});
                   5441:         }
                   5442:     }
                   5443:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5444: }
                   5445: 
                   5446: sub get_my_adhocroles {
                   5447:     my ($cid,$checkreg) = @_;
                   5448:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5449:     if ($env{'request.course.id'} eq $cid) {
                   5450:         $cdom = $env{'course.'.$cid.'.domain'};
                   5451:         $cnum = $env{'course.'.$cid.'.num'};
                   5452:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5453:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5454:         $cdom = $1;
                   5455:         $cnum = $2;
                   5456:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5457:                                      $cdom,$cnum);
                   5458:     }
                   5459:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5460:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5461:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5462:         if ($rosterhash{$user} ne '') {
                   5463:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5464:             return ([],{}) if ($type eq 'auto');
                   5465:         }
                   5466:     }
                   5467:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5468:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5469:             my $then=$env{'user.login.time'};
                   5470:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5471:             if (!$update) {
                   5472:                 $update = $then;
                   5473:             }
                   5474:             my @liveroles;
                   5475:             foreach my $role ('dh','da') {
                   5476:                 if ($env{"user.role.$role./$cdom/"}) {
                   5477:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5478:                     my $limit = $update;
                   5479:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5480:                         $limit = $then;
                   5481:                     }
                   5482:                     my $activerole = 1;
                   5483:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5484:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5485:                     if ($activerole) {
                   5486:                         push(@liveroles,$role);
                   5487:                     }
                   5488:                 }
                   5489:             }
                   5490:             if (@liveroles) {
1.1172.2.89  raeburn  5491:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5492:                     my ($accessref,$accessinfo,%access_in_dom);
                   5493:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5494:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5495:                         if (@{$roles_by_num}) {
                   5496:                             my %settings;
                   5497:                             if ($env{'request.course.id'} eq $cid) {
                   5498:                                 foreach my $envkey (keys(%env)) {
                   5499:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5500:                                         $settings{$1} = $env{$envkey};
                   5501:                                     }
                   5502:                                 }
                   5503:                             } else {
                   5504:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5505:                             }
                   5506:                             my %setincrs;
                   5507:                             if ($settings{'internal.adhocaccess'}) {
                   5508:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5509:                             }
                   5510:                             my @statuses;
                   5511:                             if ($env{'environment.inststatus'}) {
                   5512:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5513:                             }
                   5514:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5515:                             if (ref($accessref) eq 'HASH') {
                   5516:                                 %access_in_dom = %{$accessref};
                   5517:                             }
                   5518:                             foreach my $role (@{$roles_by_num}) {
                   5519:                                 my ($curraccess,@okstatus,@personnel);
                   5520:                                 if ($setincrs{$role}) {
                   5521:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5522:                                     if ($curraccess eq 'status') {
                   5523:                                         @okstatus = split(/\&/,$rest);
                   5524:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5525:                                         @personnel = split(/\&/,$rest);
                   5526:                                     }
                   5527:                                 } else {
                   5528:                                     $curraccess = $access_in_dom{$role};
                   5529:                                     if (ref($accessinfo) eq 'HASH') {
                   5530:                                         if ($curraccess eq 'status') {
                   5531:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5532:                                                 @okstatus = @{$accessinfo->{$role}};
                   5533:                                             }
                   5534:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5535:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5536:                                                 @personnel = @{$accessinfo->{$role}};
                   5537:                                             }
                   5538:                                         }
                   5539:                                     }
                   5540:                                 }
                   5541:                                 if ($curraccess eq 'none') {
                   5542:                                     next;
                   5543:                                 } elsif ($curraccess eq 'all') {
                   5544:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5545:                                 } elsif ($curraccess eq 'dh') {
                   5546:                                     if (grep(/^dh$/,@liveroles)) {
                   5547:                                         push(@possroles,$role);
                   5548:                                     } else {
                   5549:                                         next;
                   5550:                                     }
                   5551:                                 } elsif ($curraccess eq 'da') {
                   5552:                                     if (grep(/^da$/,@liveroles)) {
                   5553:                                         push(@possroles,$role);
                   5554:                                     } else {
                   5555:                                         next;
                   5556:                                     }
1.1172.2.89  raeburn  5557:                                 } elsif ($curraccess eq 'status') {
                   5558:                                     if (@okstatus) {
                   5559:                                         if (!@statuses) {
                   5560:                                             if (grep(/^default$/,@okstatus)) {
                   5561:                                                 push(@possroles,$role);
                   5562:                                             }
                   5563:                                         } else {
                   5564:                                             foreach my $status (@okstatus) {
                   5565:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5566:                                                     push(@possroles,$role);
                   5567:                                                     last;
                   5568:                                                 }
                   5569:                                             }
                   5570:                                         }
                   5571:                                     }
                   5572:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5573:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5574:                                         if ($curraccess eq 'exc') {
                   5575:                                             push(@possroles,$role);
                   5576:                                         }
                   5577:                                     } elsif ($curraccess eq 'inc') {
                   5578:                                         push(@possroles,$role);
                   5579:                                     }
                   5580:                                 }
                   5581:                             }
                   5582:                         }
                   5583:                     }
                   5584:                 }
                   5585:             }
                   5586:         }
                   5587:     }
                   5588:     unless (ref($description) eq 'HASH') {
                   5589:         if (ref($roles_by_num) eq 'ARRAY') {
                   5590:             my %desc;
                   5591:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5592:             $description = \%desc;
                   5593:         } else {
                   5594:             $description = {};
                   5595:         }
                   5596:     }
                   5597:     return (\@possroles,$description);
                   5598: }
                   5599: 
1.399     www      5600: # ----------------------------------------------------- Frontpage Announcements
                   5601: #
                   5602: #
                   5603: 
                   5604: sub postannounce {
                   5605:     my ($server,$text)=@_;
1.844     albertel 5606:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5607:     unless ($text=~/\w/) { $text=''; }
                   5608:     return &reply('setannounce:'.&escape($text),$server);
                   5609: }
                   5610: 
                   5611: sub getannounce {
1.448     albertel 5612: 
1.1172.2.96  raeburn  5613:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5614: 	my $announcement='';
1.800     albertel 5615: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5616: 	close($fh);
1.399     www      5617: 	if ($announcement=~/\w/) { 
                   5618: 	    return 
                   5619:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5620:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5621: 	} else {
                   5622: 	    return '';
                   5623: 	}
                   5624:     } else {
                   5625: 	return '';
                   5626:     }
1.351     www      5627: }
1.353     www      5628: 
                   5629: # ---------------------------------------------------------- Course ID routines
                   5630: # Deal with domain's nohist_courseid.db files
                   5631: #
                   5632: 
                   5633: sub courseidput {
1.921     raeburn  5634:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5635:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5636:     my $outcome;
                   5637:     if ($caller eq 'timeonly') {
                   5638:         my $cids = '';
                   5639:         foreach my $item (keys(%$storehash)) {
                   5640:             $cids.=&escape($item).'&';
                   5641:         }
                   5642:         $cids=~s/\&$//;
                   5643:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5644:                           $coursehome);       
                   5645:     } else {
                   5646:         my $items = '';
                   5647:         foreach my $item (keys(%$storehash)) {
                   5648:             $items.= &escape($item).'='.
                   5649:                      &freeze_escape($$storehash{$item}).'&';
                   5650:         }
                   5651:         $items=~s/\&$//;
                   5652:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5653:                           $coursehome);
1.918     raeburn  5654:     }
                   5655:     if ($outcome eq 'unknown_cmd') {
                   5656:         my $what;
                   5657:         foreach my $cid (keys(%$storehash)) {
                   5658:             $what .= &escape($cid).'=';
1.921     raeburn  5659:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5660:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5661:             }
                   5662:             $what =~ s/\:$/&/;
                   5663:         }
                   5664:         $what =~ s/\&$//;  
                   5665:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5666:     } else {
                   5667:         return $outcome;
                   5668:     }
1.353     www      5669: }
                   5670: 
                   5671: sub courseiddump {
1.921     raeburn  5672:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5673:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5674:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5675:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5676:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5677:     my $as_hash = 1;
                   5678:     my %returnhash;
                   5679:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5680:     my %libserv = &all_library();
                   5681:     foreach my $tryserver (keys(%libserv)) {
                   5682:         if ( (  $hostidflag == 1 
                   5683: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5684: 	     || (!defined($hostidflag)) ) {
                   5685: 
1.918     raeburn  5686: 	    if (($domfilter eq '') ||
                   5687: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5688:                 my $rep;
                   5689:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5690:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5691:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5692:                                 &escape($descfilter), &escape($instcodefilter),
                   5693:                                 &escape($ownerfilter), &escape($coursefilter),
                   5694:                                 &escape($typefilter), &escape($regexp_ok),
                   5695:                                 $as_hash, &escape($selfenrollonly),
                   5696:                                 &escape($catfilter), $showhidden, $caller,
                   5697:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5698:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5699:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5700:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5701:                 } else {
                   5702:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5703:                              $sincefilter.':'.&escape($descfilter).':'.
                   5704:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5705:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5706:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5707:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5708:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5709:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5710:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5711:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5712:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5713:                 }
                   5714: 
1.918     raeburn  5715:                 my @pairs=split(/\&/,$rep);
                   5716:                 foreach my $item (@pairs) {
                   5717:                     my ($key,$value)=split(/\=/,$item,2);
                   5718:                     $key = &unescape($key);
                   5719:                     next if ($key =~ /^error: 2 /);
                   5720:                     my $result = &thaw_unescape($value);
                   5721:                     if (ref($result) eq 'HASH') {
                   5722:                         $returnhash{$key}=$result;
                   5723:                     } else {
1.921     raeburn  5724:                         my @responses = split(/:/,$value);
                   5725:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5726:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5727:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5728:                         }
1.1008    raeburn  5729:                     }
1.353     www      5730:                 }
                   5731:             }
                   5732:         }
                   5733:     }
                   5734:     return %returnhash;
                   5735: }
                   5736: 
1.1055    raeburn  5737: sub courselastaccess {
                   5738:     my ($cdom,$cnum,$hostidref) = @_;
                   5739:     my %returnhash;
                   5740:     if ($cdom && $cnum) {
                   5741:         my $chome = &homeserver($cnum,$cdom);
                   5742:         if ($chome ne 'no_host') {
                   5743:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5744:             &extract_lastaccess(\%returnhash,$rep);
                   5745:         }
                   5746:     } else {
                   5747:         if (!$cdom) { $cdom=''; }
                   5748:         my %libserv = &all_library();
                   5749:         foreach my $tryserver (keys(%libserv)) {
                   5750:             if (ref($hostidref) eq 'ARRAY') {
                   5751:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5752:             } 
                   5753:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5754:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5755:                 &extract_lastaccess(\%returnhash,$rep);
                   5756:             }
                   5757:         }
                   5758:     }
                   5759:     return %returnhash;
                   5760: }
                   5761: 
                   5762: sub extract_lastaccess {
                   5763:     my ($returnhash,$rep) = @_;
                   5764:     if (ref($returnhash) eq 'HASH') {
                   5765:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5766:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5767:                  $rep eq '') {
                   5768:             my @pairs=split(/\&/,$rep);
                   5769:             foreach my $item (@pairs) {
                   5770:                 my ($key,$value)=split(/\=/,$item,2);
                   5771:                 $key = &unescape($key);
                   5772:                 next if ($key =~ /^error: 2 /);
                   5773:                 $returnhash->{$key} = &thaw_unescape($value);
                   5774:             }
                   5775:         }
                   5776:     }
                   5777:     return;
                   5778: }
                   5779: 
1.658     raeburn  5780: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5781: 
                   5782: sub dcmailput {
1.685     raeburn  5783:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5784:     my $status = &Apache::lonnet::critical(
1.740     www      5785:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5786:        &escape($message),$server);
1.662     raeburn  5787:     return $status;
                   5788: }
                   5789: 
1.658     raeburn  5790: sub dcmaildump {
                   5791:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5792:     my %returnhash=();
1.846     albertel 5793: 
                   5794:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5795:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5796:                                                          &escape($enddate).':';
                   5797: 	my @esc_senders=map { &escape($_)} @$senders;
                   5798: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5799: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5800:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5801:             if (($key) && ($value)) {
                   5802:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5803:             }
                   5804:         }
                   5805:     }
                   5806:     return %returnhash;
                   5807: }
1.662     raeburn  5808: # ---------------------------------------------------------- Domain roles
                   5809: 
                   5810: sub get_domain_roles {
                   5811:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5812:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5813:         $startdate = '.';
                   5814:     }
1.1018    raeburn  5815:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5816:         $enddate = '.';
                   5817:     }
1.922     raeburn  5818:     my $rolelist;
                   5819:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5820:         $rolelist = join('&',@{$roles});
1.922     raeburn  5821:     }
1.662     raeburn  5822:     my %personnel = ();
1.841     albertel 5823: 
                   5824:     my %servers = &get_servers($dom,'library');
                   5825:     foreach my $tryserver (keys(%servers)) {
                   5826: 	%{$personnel{$tryserver}}=();
                   5827: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5828: 					    &escape($startdate).':'.
                   5829: 					    &escape($enddate).':'.
                   5830: 					    &escape($rolelist), $tryserver))) {
                   5831: 	    my ($key,$value) = split(/\=/,$line,2);
                   5832: 	    if (($key) && ($value)) {
                   5833: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5834: 	    }
                   5835: 	}
1.662     raeburn  5836:     }
                   5837:     return %personnel;
                   5838: }
1.658     raeburn  5839: 
1.1172.2.89  raeburn  5840: sub get_active_domroles {
                   5841:     my ($dom,$roles) = @_;
                   5842:     return () unless (ref($roles) eq 'ARRAY');
                   5843:     my $now = time;
                   5844:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5845:     my %domroles;
                   5846:     foreach my $server (keys(%dompersonnel)) {
                   5847:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5848:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5849:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5850:         }
                   5851:     }
                   5852:     return %domroles;
                   5853: }
                   5854: 
1.1057    www      5855: # ----------------------------------------------------------- Interval timing 
1.149     www      5856: 
1.1153    www      5857: {
                   5858: # Caches needed for speedup of navmaps
                   5859: # We don't want to cache this for very long at all (5 seconds at most)
                   5860: # 
                   5861: # The user for whom we cache
                   5862: my $cachedkey='';
                   5863: # The cached times for this user
                   5864: my %cachedtimes=();
                   5865: # When this was last done
1.1172.2.66  raeburn  5866: my $cachedtime='';
1.1153    www      5867: 
                   5868: sub load_all_first_access {
1.1172.2.146.  .1(raebu 5869:22):     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5870:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.146.  .1(raebu 5871:22):         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5872:22):         (!$ignorecache)) {
1.1154    raeburn  5873:         return;
                   5874:     }
                   5875:     $cachedtime=time;
                   5876:     $cachedkey=$uname.':'.$udom;
                   5877:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5878: }
                   5879: 
1.504     albertel 5880: sub get_first_access {
1.1172.2.146.  .1(raebu 5881:22):     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5882:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5883:     if ($argsymb) { $symb=$argsymb; }
                   5884:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5885:     if ($argmap) { $map = $argmap; }
1.926     albertel 5886:     if ($type eq 'course') {
                   5887: 	$res='course';
                   5888:     } elsif ($type eq 'map') {
1.588     albertel 5889: 	$res=&symbread($map);
                   5890:     } else {
                   5891: 	$res=$symb;
                   5892:     }
1.1172.2.146.  .1(raebu 5893:22):     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5894:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5895: }
                   5896: 
                   5897: sub set_first_access {
1.1162    raeburn  5898:     my ($type,$interval)=@_;
1.790     albertel 5899:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5900:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5901:     if ($type eq 'course') {
                   5902: 	$res='course';
                   5903:     } elsif ($type eq 'map') {
1.588     albertel 5904: 	$res=&symbread($map);
                   5905:     } else {
                   5906: 	$res=$symb;
                   5907:     }
1.1153    www      5908:     $cachedkey='';
1.1162    raeburn  5909:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5910:     if ($firstaccess) {
                   5911:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5912:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5913:                  "in $courseid");
                   5914:         return 'already_set';
                   5915:     } else {
1.1162    raeburn  5916:         my $start = time;
                   5917: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5918:                           $udom,$uname);
                   5919:         if ($putres eq 'ok') {
                   5920:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5921:                  $udom,$uname); 
                   5922:             &appenv(
                   5923:                      {
                   5924:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5925:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5926:                      }
                   5927:                   );
1.1172.2.97  raeburn  5928:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5929:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5930:             }
1.1172.2.102  raeburn  5931:         } elsif ($putres ne 'refused') {
                   5932:             &logthis("Result: $putres when attempting to set first access time ".
                   5933:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5934:         }
                   5935:         return $putres;
1.505     albertel 5936:     }
                   5937:     return 'already_set';
1.504     albertel 5938: }
1.1153    www      5939: }
1.1172.2.32  raeburn  5940: 
                   5941: sub checkout {
                   5942:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5943:     my $now=time;
                   5944:     my $lonhost=$perlvar{'lonHostID'};
1.1172.2.134  raeburn  5945:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5946:     my $infostr=&escape(
                   5947:                  'CHECKOUTTOKEN&'.
                   5948:                  $tuname.'&'.
                   5949:                  $tudom.'&'.
                   5950:                  $tcrsid.'&'.
                   5951:                  $symb.'&'.
1.1172.2.134  raeburn  5952:                  $now.'&'.$ip);
1.1172.2.32  raeburn  5953:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5954:     if ($token=~/^error\:/) {
                   5955:         &logthis("<font color=\"blue\">WARNING: ".
                   5956:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5957:                  "</font>");
                   5958:         return '';
                   5959:     }
                   5960: 
                   5961:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5962:     $token=~tr/a-z/A-Z/;
                   5963: 
                   5964:     my %infohash=('resource.0.outtoken' => $token,
                   5965:                   'resource.0.checkouttime' => $now,
1.1172.2.134  raeburn  5966:                   'resource.0.outremote' => $ip);
1.1172.2.32  raeburn  5967: 
                   5968:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5969:        return '';
                   5970:     } else {
                   5971:         &logthis("<font color=\"blue\">WARNING: ".
                   5972:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5973:                  "</font>");
                   5974:     }
                   5975: 
                   5976:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5977:                          &escape('Checkout '.$infostr.' - '.
                   5978:                                                  $token)) ne 'ok') {
                   5979:         return '';
                   5980:     } else {
                   5981:         &logthis("<font color=\"blue\">WARNING: ".
                   5982:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5983:                  "</font>");
                   5984:     }
                   5985:     return $token;
                   5986: }
                   5987: 
                   5988: # ------------------------------------------------------------ Check in an item
                   5989: 
                   5990: sub checkin {
                   5991:     my $token=shift;
                   5992:     my $now=time;
                   5993:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5994:     $lonhost=~tr/A-Z/a-z/;
                   5995:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5996:     $dtoken=~s/\W/\_/g;
1.1172.2.134  raeburn  5997:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5998:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5999:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   6000: 
                   6001:     unless (($tuname) && ($tudom)) {
                   6002:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   6003:         return '';
                   6004:     }
                   6005: 
                   6006:     unless (&allowed('mgr',$tcrsid)) {
                   6007:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   6008:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   6009:         return '';
                   6010:     }
                   6011: 
                   6012:     my %infohash=('resource.0.intoken' => $token,
                   6013:                   'resource.0.checkintime' => $now,
1.1172.2.134  raeburn  6014:                   'resource.0.inremote' => $ip);
1.1172.2.32  raeburn  6015: 
                   6016:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   6017:        return '';
                   6018:     }
                   6019: 
                   6020:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   6021:                          &escape('Checkin - '.$token)) ne 'ok') {
                   6022:         return '';
                   6023:     }
                   6024: 
                   6025:     return ($symb,$tuname,$tudom,$tcrsid);
                   6026: }
                   6027: 
1.110     www      6028: # --------------------------------------------- Set Expire Date for Spreadsheet
                   6029: 
                   6030: sub expirespread {
                   6031:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 6032:     my $cid=$env{'request.course.id'}; 
1.110     www      6033:     if ($cid) {
                   6034:        my $now=time;
                   6035:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 6036:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   6037:                             $env{'course.'.$cid.'.num'}.
1.110     www      6038: 	        	    ':nohist_expirationdates:'.
                   6039:                             &escape($key).'='.$now,
1.620     albertel 6040:                             $env{'course.'.$cid.'.home'})
1.110     www      6041:     }
                   6042:     return 'ok';
1.14      www      6043: }
                   6044: 
1.109     www      6045: # ----------------------------------------------------- Devalidate Spreadsheets
                   6046: 
                   6047: sub devalidate {
1.325     www      6048:     my ($symb,$uname,$udom)=@_;
1.620     albertel 6049:     my $cid=$env{'request.course.id'}; 
1.109     www      6050:     if ($cid) {
1.391     matthew  6051:         # delete the stored spreadsheets for
                   6052:         # - the student level sheet of this user in course's homespace
                   6053:         # - the assessment level sheet for this resource 
                   6054:         #   for this user in user's homespace
1.553     albertel 6055: 	# - current conditional state info
1.325     www      6056: 	my $key=$uname.':'.$udom.':';
1.109     www      6057:         my $status=
1.299     matthew  6058: 	    &del('nohist_calculatedsheets',
1.391     matthew  6059: 		 [$key.'studentcalc:'],
1.620     albertel 6060: 		 $env{'course.'.$cid.'.domain'},
                   6061: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 6062: 		.' '.
                   6063: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  6064: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      6065:         unless ($status eq 'ok ok') {
                   6066:            &logthis('Could not devalidate spreadsheet '.
1.325     www      6067:                     $uname.' at '.$udom.' for '.
1.109     www      6068: 		    $symb.': '.$status);
1.133     albertel 6069:         }
1.553     albertel 6070: 	&delenv('user.state.'.$cid);
1.109     www      6071:     }
                   6072: }
                   6073: 
1.265     albertel 6074: sub get_scalar {
                   6075:     my ($string,$end) = @_;
                   6076:     my $value;
                   6077:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   6078: 	$value = $1;
                   6079:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   6080: 	$value = $1;
                   6081:     }
                   6082:     return &unescape($value);
                   6083: }
                   6084: 
                   6085: sub array2str {
                   6086:   my (@array) = @_;
                   6087:   my $result=&arrayref2str(\@array);
                   6088:   $result=~s/^__ARRAY_REF__//;
                   6089:   $result=~s/__END_ARRAY_REF__$//;
                   6090:   return $result;
                   6091: }
                   6092: 
1.204     albertel 6093: sub arrayref2str {
                   6094:   my ($arrayref) = @_;
1.265     albertel 6095:   my $result='__ARRAY_REF__';
1.204     albertel 6096:   foreach my $elem (@$arrayref) {
1.265     albertel 6097:     if(ref($elem) eq 'ARRAY') {
                   6098:       $result.=&arrayref2str($elem).'&';
                   6099:     } elsif(ref($elem) eq 'HASH') {
                   6100:       $result.=&hashref2str($elem).'&';
                   6101:     } elsif(ref($elem)) {
                   6102:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 6103:     } else {
                   6104:       $result.=&escape($elem).'&';
                   6105:     }
                   6106:   }
                   6107:   $result=~s/\&$//;
1.265     albertel 6108:   $result .= '__END_ARRAY_REF__';
1.204     albertel 6109:   return $result;
                   6110: }
                   6111: 
1.168     albertel 6112: sub hash2str {
1.204     albertel 6113:   my (%hash) = @_;
                   6114:   my $result=&hashref2str(\%hash);
1.265     albertel 6115:   $result=~s/^__HASH_REF__//;
                   6116:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 6117:   return $result;
                   6118: }
                   6119: 
                   6120: sub hashref2str {
                   6121:   my ($hashref)=@_;
1.265     albertel 6122:   my $result='__HASH_REF__';
1.800     albertel 6123:   foreach my $key (sort(keys(%$hashref))) {
                   6124:     if (ref($key) eq 'ARRAY') {
                   6125:       $result.=&arrayref2str($key).'=';
                   6126:     } elsif (ref($key) eq 'HASH') {
                   6127:       $result.=&hashref2str($key).'=';
                   6128:     } elsif (ref($key)) {
1.265     albertel 6129:       $result.='=';
1.800     albertel 6130:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 6131:     } else {
1.1132    raeburn  6132: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 6133:     }
                   6134: 
1.800     albertel 6135:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   6136:       $result.=&arrayref2str($hashref->{$key}).'&';
                   6137:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   6138:       $result.=&hashref2str($hashref->{$key}).'&';
                   6139:     } elsif(ref($hashref->{$key})) {
1.265     albertel 6140:        $result.='&';
1.800     albertel 6141:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 6142:     } else {
1.800     albertel 6143:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 6144:     }
                   6145:   }
1.168     albertel 6146:   $result=~s/\&$//;
1.265     albertel 6147:   $result .= '__END_HASH_REF__';
1.168     albertel 6148:   return $result;
                   6149: }
                   6150: 
                   6151: sub str2hash {
1.265     albertel 6152:     my ($string)=@_;
                   6153:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   6154:     return %$hash;
                   6155: }
                   6156: 
                   6157: sub str2hashref {
1.168     albertel 6158:   my ($string) = @_;
1.265     albertel 6159: 
                   6160:   my %hash;
                   6161: 
                   6162:   if($string !~ /^__HASH_REF__/) {
                   6163:       if (! ($string eq '' || !defined($string))) {
                   6164: 	  $hash{'error'}='Not hash reference';
                   6165:       }
                   6166:       return (\%hash, $string);
                   6167:   }
                   6168: 
                   6169:   $string =~ s/^__HASH_REF__//;
                   6170: 
                   6171:   while($string !~ /^__END_HASH_REF__/) {
                   6172:       #key
                   6173:       my $key='';
                   6174:       if($string =~ /^__HASH_REF__/) {
                   6175:           ($key, $string)=&str2hashref($string);
                   6176:           if(defined($key->{'error'})) {
                   6177:               $hash{'error'}='Bad data';
                   6178:               return (\%hash, $string);
                   6179:           }
                   6180:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6181:           ($key, $string)=&str2arrayref($string);
                   6182:           if($key->[0] eq 'Array reference error') {
                   6183:               $hash{'error'}='Bad data';
                   6184:               return (\%hash, $string);
                   6185:           }
                   6186:       } else {
                   6187:           $string =~ s/^(.*?)=//;
1.267     albertel 6188: 	  $key=&unescape($1);
1.265     albertel 6189:       }
                   6190:       $string =~ s/^=//;
                   6191: 
                   6192:       #value
                   6193:       my $value='';
                   6194:       if($string =~ /^__HASH_REF__/) {
                   6195:           ($value, $string)=&str2hashref($string);
                   6196:           if(defined($value->{'error'})) {
                   6197:               $hash{'error'}='Bad data';
                   6198:               return (\%hash, $string);
                   6199:           }
                   6200:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6201:           ($value, $string)=&str2arrayref($string);
                   6202:           if($value->[0] eq 'Array reference error') {
                   6203:               $hash{'error'}='Bad data';
                   6204:               return (\%hash, $string);
                   6205:           }
                   6206:       } else {
                   6207: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   6208:       }
                   6209:       $string =~ s/^&//;
                   6210: 
                   6211:       $hash{$key}=$value;
1.204     albertel 6212:   }
1.265     albertel 6213: 
                   6214:   $string =~ s/^__END_HASH_REF__//;
                   6215: 
                   6216:   return (\%hash, $string);
1.204     albertel 6217: }
                   6218: 
                   6219: sub str2array {
1.265     albertel 6220:     my ($string)=@_;
                   6221:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   6222:     return @$array;
                   6223: }
                   6224: 
                   6225: sub str2arrayref {
1.204     albertel 6226:   my ($string) = @_;
1.265     albertel 6227:   my @array;
                   6228: 
                   6229:   if($string !~ /^__ARRAY_REF__/) {
                   6230:       if (! ($string eq '' || !defined($string))) {
                   6231: 	  $array[0]='Array reference error';
                   6232:       }
                   6233:       return (\@array, $string);
                   6234:   }
                   6235: 
                   6236:   $string =~ s/^__ARRAY_REF__//;
                   6237: 
                   6238:   while($string !~ /^__END_ARRAY_REF__/) {
                   6239:       my $value='';
                   6240:       if($string =~ /^__HASH_REF__/) {
                   6241:           ($value, $string)=&str2hashref($string);
                   6242:           if(defined($value->{'error'})) {
                   6243:               $array[0] ='Array reference error';
                   6244:               return (\@array, $string);
                   6245:           }
                   6246:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6247:           ($value, $string)=&str2arrayref($string);
                   6248:           if($value->[0] eq 'Array reference error') {
                   6249:               $array[0] ='Array reference error';
                   6250:               return (\@array, $string);
                   6251:           }
                   6252:       } else {
                   6253: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   6254:       }
                   6255:       $string =~ s/^&//;
                   6256: 
                   6257:       push(@array, $value);
1.191     harris41 6258:   }
1.265     albertel 6259: 
                   6260:   $string =~ s/^__END_ARRAY_REF__//;
                   6261: 
                   6262:   return (\@array, $string);
1.168     albertel 6263: }
                   6264: 
1.167     albertel 6265: # -------------------------------------------------------------------Temp Store
                   6266: 
1.168     albertel 6267: sub tmpreset {
                   6268:   my ($symb,$namespace,$domain,$stuname) = @_;
                   6269:   if (!$symb) {
                   6270:     $symb=&symbread();
1.620     albertel 6271:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6272:   }
                   6273:   $symb=escape($symb);
                   6274: 
1.620     albertel 6275:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 6276:   $namespace=~s/\//\_/g;
                   6277:   $namespace=~s/\W//g;
                   6278: 
1.620     albertel 6279:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6280:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6281:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6282:       $stuname=&get_requestor_ip();
1.591     albertel 6283:   }
1.1117    foxr     6284:   my $path=LONCAPA::tempdir();
1.168     albertel 6285:   my %hash;
                   6286:   if (tie(%hash,'GDBM_File',
                   6287: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6288: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  6289:     foreach my $key (keys(%hash)) {
1.180     albertel 6290:       if ($key=~ /:$symb/) {
1.168     albertel 6291: 	delete($hash{$key});
                   6292:       }
                   6293:     }
                   6294:   }
                   6295: }
                   6296: 
1.167     albertel 6297: sub tmpstore {
1.168     albertel 6298:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   6299: 
                   6300:   if (!$symb) {
                   6301:     $symb=&symbread();
1.620     albertel 6302:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6303:   }
                   6304:   $symb=escape($symb);
                   6305: 
                   6306:   if (!$namespace) {
                   6307:     # I don't think we would ever want to store this for a course.
                   6308:     # it seems this will only be used if we don't have a course.
1.620     albertel 6309:     #$namespace=$env{'request.course.id'};
1.168     albertel 6310:     #if (!$namespace) {
1.620     albertel 6311:       $namespace=$env{'request.state'};
1.168     albertel 6312:     #}
                   6313:   }
                   6314:   $namespace=~s/\//\_/g;
                   6315:   $namespace=~s/\W//g;
1.620     albertel 6316:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6317:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6318:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6319:       $stuname=&get_requestor_ip();
1.591     albertel 6320:   }
1.168     albertel 6321:   my $now=time;
                   6322:   my %hash;
1.1117    foxr     6323:   my $path=LONCAPA::tempdir();
1.168     albertel 6324:   if (tie(%hash,'GDBM_File',
                   6325: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6326: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 6327:     $hash{"version:$symb"}++;
                   6328:     my $version=$hash{"version:$symb"};
                   6329:     my $allkeys=''; 
                   6330:     foreach my $key (keys(%$storehash)) {
                   6331:       $allkeys.=$key.':';
1.591     albertel 6332:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 6333:     }
                   6334:     $hash{"$version:$symb:timestamp"}=$now;
                   6335:     $allkeys.='timestamp';
                   6336:     $hash{"$version:keys:$symb"}=$allkeys;
                   6337:     if (untie(%hash)) {
                   6338:       return 'ok';
                   6339:     } else {
                   6340:       return "error:$!";
                   6341:     }
                   6342:   } else {
                   6343:     return "error:$!";
                   6344:   }
                   6345: }
1.167     albertel 6346: 
1.168     albertel 6347: # -----------------------------------------------------------------Temp Restore
1.167     albertel 6348: 
1.168     albertel 6349: sub tmprestore {
                   6350:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 6351: 
1.168     albertel 6352:   if (!$symb) {
                   6353:     $symb=&symbread();
1.620     albertel 6354:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6355:   }
                   6356:   $symb=escape($symb);
                   6357: 
1.620     albertel 6358:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 6359: 
1.620     albertel 6360:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6361:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6362:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6363:       $stuname=&get_requestor_ip();
1.591     albertel 6364:   }
1.168     albertel 6365:   my %returnhash;
                   6366:   $namespace=~s/\//\_/g;
                   6367:   $namespace=~s/\W//g;
                   6368:   my %hash;
1.1117    foxr     6369:   my $path=LONCAPA::tempdir();
1.168     albertel 6370:   if (tie(%hash,'GDBM_File',
                   6371: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6372: 	  &GDBM_READER(),0640)) {
1.168     albertel 6373:     my $version=$hash{"version:$symb"};
                   6374:     $returnhash{'version'}=$version;
                   6375:     my $scope;
                   6376:     for ($scope=1;$scope<=$version;$scope++) {
                   6377:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6378:       my @keys=split(/:/,$vkeys);
                   6379:       my $key;
                   6380:       $returnhash{"$scope:keys"}=$vkeys;
                   6381:       foreach $key (@keys) {
1.591     albertel 6382: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6383: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6384:       }
                   6385:     }
1.168     albertel 6386:     if (!(untie(%hash))) {
                   6387:       return "error:$!";
                   6388:     }
                   6389:   } else {
                   6390:     return "error:$!";
                   6391:   }
                   6392:   return %returnhash;
1.167     albertel 6393: }
                   6394: 
1.9       www      6395: # ----------------------------------------------------------------------- Store
                   6396: 
                   6397: sub store {
1.1172.2.64  raeburn  6398:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6399:     my $home='';
                   6400: 
1.168     albertel 6401:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6402: 
1.213     www      6403:     $symb=&symbclean($symb);
1.122     albertel 6404:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6405: 
1.620     albertel 6406:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6407:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6408: 
                   6409:     &devalidate($symb,$stuname,$domain);
1.109     www      6410: 
                   6411:     $symb=escape($symb);
1.187     www      6412:     if (!$namespace) { 
1.620     albertel 6413:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6414:           return ''; 
                   6415:        } 
                   6416:     }
1.620     albertel 6417:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6418: 
1.1172.2.138  raeburn  6419:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6420:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6421: 
1.12      www      6422:     my $namevalue='';
1.800     albertel 6423:     foreach my $key (keys(%$storehash)) {
                   6424:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6425:     }
1.12      www      6426:     $namevalue=~s/\&$//;
1.187     www      6427:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  6428:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6429: }
                   6430: 
1.47      www      6431: # -------------------------------------------------------------- Critical Store
                   6432: 
                   6433: sub cstore {
1.1172.2.64  raeburn  6434:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6435:     my $home='';
                   6436: 
1.168     albertel 6437:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6438: 
1.213     www      6439:     $symb=&symbclean($symb);
1.122     albertel 6440:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6441: 
1.620     albertel 6442:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6443:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6444: 
                   6445:     &devalidate($symb,$stuname,$domain);
1.109     www      6446: 
                   6447:     $symb=escape($symb);
1.187     www      6448:     if (!$namespace) { 
1.620     albertel 6449:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6450:           return ''; 
                   6451:        } 
                   6452:     }
1.620     albertel 6453:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6454: 
1.1172.2.138  raeburn  6455:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6456:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6457: 
1.47      www      6458:     my $namevalue='';
1.800     albertel 6459:     foreach my $key (keys(%$storehash)) {
                   6460:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6461:     }
1.47      www      6462:     $namevalue=~s/\&$//;
1.187     www      6463:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6464:     return critical
1.1172.2.64  raeburn  6465:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6466: }
                   6467: 
1.9       www      6468: # --------------------------------------------------------------------- Restore
                   6469: 
                   6470: sub restore {
1.124     www      6471:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6472:     my $home='';
                   6473: 
1.168     albertel 6474:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6475: 
1.122     albertel 6476:     if (!$symb) {
1.1172.2.26  raeburn  6477:         return if ($namespace eq 'courserequests');
                   6478:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6479:     } else {
1.1172.2.26  raeburn  6480:         unless ($namespace eq 'courserequests') {
                   6481:             $symb=&escape(&symbclean($symb));
                   6482:         }
1.122     albertel 6483:     }
1.188     www      6484:     if (!$namespace) { 
1.620     albertel 6485:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6486:           return ''; 
                   6487:        } 
                   6488:     }
1.620     albertel 6489:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6490:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6491:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6492:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6493: 
1.12      www      6494:     my %returnhash=();
1.800     albertel 6495:     foreach my $line (split(/\&/,$answer)) {
                   6496: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6497:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6498:     }
1.75      www      6499:     my $version;
                   6500:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6501:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6502:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6503:        }
1.75      www      6504:     }
1.13      www      6505:     return %returnhash;
1.34      www      6506: }
                   6507: 
                   6508: # ---------------------------------------------------------- Course Description
1.1118    foxr     6509: #
                   6510: #  
1.34      www      6511: 
                   6512: sub coursedescription {
1.731     albertel 6513:     my ($courseid,$args)=@_;
1.34      www      6514:     $courseid=~s/^\///;
1.49      www      6515:     $courseid=~s/\_/\//g;
1.34      www      6516:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6517:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6518:     my $normalid=$cdomain.'_'.$cnum;
                   6519:     # need to always cache even if we get errors otherwise we keep 
                   6520:     # trying and trying and trying to get the course description.
                   6521:     my %envhash=();
                   6522:     my %returnhash=();
1.731     albertel 6523:     
                   6524:     my $expiretime=600;
                   6525:     if ($env{'request.course.id'} eq $normalid) {
                   6526: 	$expiretime=120;
                   6527:     }
                   6528: 
                   6529:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6530:     if (!$args->{'freshen_cache'}
                   6531: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6532: 	foreach my $key (keys(%env)) {
                   6533: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6534: 	    my ($setting) = $1;
                   6535: 	    $returnhash{$setting} = $env{$key};
                   6536: 	}
                   6537: 	return %returnhash;
                   6538:     }
                   6539: 
1.1118    foxr     6540:     # get the data again
                   6541: 
1.731     albertel 6542:     if (!$args->{'one_time'}) {
                   6543: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6544:     }
1.811     albertel 6545: 
1.34      www      6546:     if ($chome ne 'no_host') {
1.302     albertel 6547:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6548:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6549: 	   my $username = $env{'user.name'}; # Defult username
                   6550: 	   if(defined $args->{'user'}) {
                   6551: 	       $username = $args->{'user'};
                   6552: 	   }
1.129     albertel 6553:            $returnhash{'home'}= $chome;
                   6554: 	   $returnhash{'domain'} = $cdomain;
                   6555: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6556:            if (!defined($returnhash{'type'})) {
                   6557:                $returnhash{'type'} = 'Course';
                   6558:            }
1.130     albertel 6559:            while (my ($name,$value) = each %returnhash) {
1.53      www      6560:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6561:            }
1.270     www      6562:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6563:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6564: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6565:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6566:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6567:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6568:        }
                   6569:     }
1.731     albertel 6570:     if (!$args->{'one_time'}) {
1.949     raeburn  6571: 	&appenv(\%envhash);
1.731     albertel 6572:     }
1.302     albertel 6573:     return %returnhash;
1.461     www      6574: }
                   6575: 
1.1080    raeburn  6576: sub update_released_required {
                   6577:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6578:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6579:         $cid = $env{'request.course.id'};
                   6580:         $cdom = $env{'course.'.$cid.'.domain'};
                   6581:         $cnum = $env{'course.'.$cid.'.num'};
                   6582:         $chome = $env{'course.'.$cid.'.home'};
                   6583:     }
                   6584:     if ($needsrelease) {
                   6585:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6586:         my $needsupdate;
                   6587:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6588:             $needsupdate = 1;
                   6589:         } else {
                   6590:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6591:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6592:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6593:                 $needsupdate = 1;
                   6594:             }
                   6595:         }
                   6596:         if ($needsupdate) {
                   6597:             my %needshash = (
                   6598:                              'internal.releaserequired' => $needsrelease,
                   6599:                             );
                   6600:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6601:             if ($putresult eq 'ok') {
                   6602:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6603:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6604:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6605:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6606:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6607:                 }
                   6608:             }
                   6609:         }
                   6610:     }
                   6611:     return;
                   6612: }
                   6613: 
1.461     www      6614: # -------------------------------------------------See if a user is privileged
                   6615: 
                   6616: sub privileged {
1.1172.2.23  raeburn  6617:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6618:     my $now = time;
1.1172.2.23  raeburn  6619:     my $roles;
                   6620:     if (ref($possroles) eq 'ARRAY') {
                   6621:         $roles = $possroles;
                   6622:     } else {
                   6623:         $roles = ['dc','su'];
                   6624:     }
                   6625:     if (ref($possdomains) eq 'ARRAY') {
                   6626:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6627:         foreach my $dom (@{$possdomains}) {
                   6628:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6629:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6630:                 foreach my $role (@{$roles}) {
                   6631:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6632:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6633:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6634:                             return 1 unless (($end && $end < $now) ||
                   6635:                                              ($start && $start > $now));
                   6636:                         }
                   6637:                     }
                   6638:                 }
                   6639:             }
                   6640:         }
                   6641:     } else {
                   6642:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6643:         my $now = time;
1.1170    droeschl 6644: 
1.1172.2.58  raeburn  6645:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6646:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6647:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6648:                 return 1 unless ($tend && $tend < $now)
                   6649:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6650:             }
1.1172.2.23  raeburn  6651:         }
                   6652:     }
1.461     www      6653:     return 0;
1.9       www      6654: }
1.1       albertel 6655: 
1.1172.2.23  raeburn  6656: sub privileged_by_domain {
                   6657:     my ($domains,$roles) = @_;
                   6658:     my %privileged = ();
                   6659:     my $cachetime = 60*60*24;
                   6660:     my $now = time;
                   6661:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6662:         return %privileged;
                   6663:     }
                   6664:     foreach my $dom (@{$domains}) {
                   6665:         next if (ref($privileged{$dom}) eq 'HASH');
                   6666:         my $needroles;
                   6667:         foreach my $role (@{$roles}) {
                   6668:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6669:             if (defined($cached)) {
                   6670:                 if (ref($result) eq 'HASH') {
                   6671:                     $privileged{$dom}{$role} = $result;
                   6672:                 }
                   6673:             } else {
                   6674:                 $needroles = 1;
                   6675:             }
                   6676:         }
                   6677:         if ($needroles) {
                   6678:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6679:             $privileged{$dom} = {};
                   6680:             foreach my $server (keys(%dompersonnel)) {
                   6681:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6682:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6683:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6684:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6685:                         next if ($end && $end < $now);
                   6686:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6687:                             $dompersonnel{$server}{$item};
                   6688:                     }
                   6689:                 }
                   6690:             }
                   6691:             if (ref($privileged{$dom}) eq 'HASH') {
                   6692:                 foreach my $role (@{$roles}) {
                   6693:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6694:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6695:                     } else {
                   6696:                         my %hash = ();
                   6697:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6698:                     }
                   6699:                 }
                   6700:             }
                   6701:         }
                   6702:     }
                   6703:     return %privileged;
                   6704: }
                   6705: 
1.103     harris41 6706: # -------------------------------------------------------- Get user privileges
1.11      www      6707: 
                   6708: sub rolesinit {
1.1169    droeschl 6709:     my ($domain, $username) = @_;
                   6710:     my %userroles = ('user.login.time' => time);
                   6711:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6712: 
                   6713:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6714:     # also, blocking can be triggered by an activating timer
                   6715:     # it's saved in the user's %env.
                   6716:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6717:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6718:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6719:         %timerintchk, %timerintenv);
                   6720: 
1.1162    raeburn  6721:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6722:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6723:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6724:     }
1.1169    droeschl 6725: 
1.1162    raeburn  6726:     foreach my $key (keys(%timerinterval)) {
                   6727:         my ($cid,$rest) = split(/\0/,$key);
                   6728:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6729:     }
1.1169    droeschl 6730: 
1.11      www      6731:     my %allroles=();
1.1162    raeburn  6732:     my %allgroups=();
1.11      www      6733: 
1.1172.2.58  raeburn  6734:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6735:         my $role = $rolesdump{$area};
                   6736:         $area =~ s/\_\w\w$//;
                   6737: 
                   6738:         my ($trole, $tend, $tstart, $group_privs);
                   6739: 
                   6740:         if ($role =~ /^cr/) {
                   6741:         # Custom role, defined by a user 
                   6742:         # e.g., user.role.cr/msu/smith/mynewrole
                   6743:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6744:                 $trole = $1;
                   6745:                 ($tend, $tstart) = split('_', $2);
                   6746:             } else {
                   6747:                 $trole = $role;
                   6748:             }
                   6749:         } elsif ($role =~ m|^gr/|) {
                   6750:         # Role of member in a group, defined within a course/community
                   6751:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6752:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6753:             next if $tstart eq '-1';
                   6754:             ($trole, $group_privs) = split(/\//, $trole);
                   6755:             $group_privs = &unescape($group_privs);
                   6756:         } else {
                   6757:         # Just a normal role, defined in roles.tab
                   6758:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6759:         }
                   6760: 
                   6761:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6762:                  $username);
                   6763:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6764: 
                   6765:         # role expired or not available yet?
                   6766:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6767:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6768: 
                   6769:         next if $area eq '' or $trole eq '';
                   6770: 
                   6771:         my $spec = "$trole.$area";
                   6772:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6773: 
                   6774:         if ($trole =~ /^cr\//) {
                   6775:         # Custom role, defined by a user
                   6776:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6777:         } elsif ($trole eq 'gr') {
                   6778:         # Role of a member in a group, defined within a course/community
                   6779:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6780:             next;
                   6781:         } else {
                   6782:         # Normal role, defined in roles.tab
                   6783:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6784:         }
                   6785: 
                   6786:         my $cid = $tdomain.'_'.$trest;
                   6787:         unless ($firstaccchk{$cid}) {
                   6788:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6789:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6790:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6791:                         $coursetimerstarts{$cid}{$item}; 
                   6792:                 }
                   6793:             }
                   6794:             $firstaccchk{$cid} = 1;
                   6795:         }
                   6796:         unless ($timerintchk{$cid}) {
                   6797:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6798:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6799:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6800:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6801:                 }
1.12      www      6802:             }
1.1169    droeschl 6803:             $timerintchk{$cid} = 1;
1.191     harris41 6804:         }
1.11      www      6805:     }
1.1169    droeschl 6806: 
1.1172.2.91  raeburn  6807:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6808:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6809:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6810:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6811: 
1.1162    raeburn  6812:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6813: }
                   6814: 
1.567     raeburn  6815: sub set_arearole {
1.1172.2.19  raeburn  6816:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6817:     unless ($nolog) {
1.567     raeburn  6818: # log the associated role with the area
1.1172.2.19  raeburn  6819:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6820:     }
1.743     albertel 6821:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6822: }
                   6823: 
                   6824: sub custom_roleprivs {
                   6825:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6826:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6827:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6828:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6829:         my ($rdummy,$roledef)=
                   6830:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6831:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6832:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6833:             if (defined($syspriv)) {
1.1043    raeburn  6834:                 if ($trest =~ /^$match_community$/) {
                   6835:                     $syspriv =~ s/bre\&S//; 
                   6836:                 }
1.567     raeburn  6837:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6838:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6839:             }
                   6840:             if ($tdomain ne '') {
                   6841:                 if (defined($dompriv)) {
                   6842:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6843:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6844:                 }
                   6845:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6846:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6847:                         my $rolename = $1;
                   6848:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6849:                     }
1.567     raeburn  6850:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6851:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6852:                 }
                   6853:             }
                   6854:         }
                   6855:     }
                   6856: }
                   6857: 
1.1172.2.89  raeburn  6858: sub course_adhocrole_privs {
                   6859:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6860:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6861:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6862:         my (%currprivs,%storeprivs);
                   6863:         foreach my $item (split(/:/,$coursepriv)) {
                   6864:             my ($priv,$restrict) = split(/\&/,$item);
                   6865:             $currprivs{$priv} = $restrict;
                   6866:         }
                   6867:         my (%possadd,%possremove,%full);
                   6868:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6869:             my ($priv,$restrict)=split(/\&/,$item);
                   6870:             $full{$priv} = $restrict;
                   6871:         }
                   6872:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
1.1172.2.146.  .6(raebu 6873:22):             next if ($item eq '');
                   6874:22):             my ($rule,$rest) = split(/=/,$item);
                   6875:22):             next unless (($rule eq 'off') || ($rule eq 'on'));
                   6876:22):             foreach my $priv (split(/:/,$rest)) {
                   6877:22):                 if ($priv ne '') {
                   6878:22):                     if ($rule eq 'off') {
                   6879:22):                         $possremove{$priv} = 1;
                   6880:22):                     } else {
                   6881:22):                         $possadd{$priv} = 1;
                   6882:22):                     }
                   6883:22):                 }
                   6884:22):             }
                   6885:22):         }
                   6886:22):         foreach my $priv (sort(keys(%full))) {
                   6887:22):             if (exists($currprivs{$priv})) {
                   6888:22):                 unless (exists($possremove{$priv})) {
                   6889:22):                     $storeprivs{$priv} = $currprivs{$priv};
                   6890:22):                 }
                   6891:22):             } elsif (exists($possadd{$priv})) {
                   6892:22):                 $storeprivs{$priv} = $full{$priv};
                   6893:22):             }
                   6894:22):         }
                   6895:22):         $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6896:22):     }
                   6897:22):     return $coursepriv;
1.1172.2.89  raeburn  6898: }
                   6899: 
1.678     raeburn  6900: sub group_roleprivs {
                   6901:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6902:     my $access = 1;
                   6903:     my $now = time;
                   6904:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6905:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6906:     if ($access) {
1.811     albertel 6907:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6908:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6909:     }
                   6910: }
1.567     raeburn  6911: 
                   6912: sub standard_roleprivs {
                   6913:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6914:     if (defined($pr{$trole.':s'})) {
                   6915:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6916:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6917:     }
                   6918:     if ($tdomain ne '') {
                   6919:         if (defined($pr{$trole.':d'})) {
                   6920:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6921:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6922:         }
                   6923:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6924:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6925:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6926:         }
                   6927:     }
                   6928: }
                   6929: 
                   6930: sub set_userprivs {
1.1064    raeburn  6931:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6932:     my $author=0;
                   6933:     my $adv=0;
1.1172.2.91  raeburn  6934:     my $rar=0;
1.678     raeburn  6935:     my %grouproles = ();
                   6936:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6937:         my @groupkeys; 
1.1000    raeburn  6938:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6939:             push(@groupkeys,$role);
                   6940:         }
                   6941:         if (ref($groups_roles) eq 'HASH') {
                   6942:             foreach my $key (keys(%{$groups_roles})) {
                   6943:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6944:                     push(@groupkeys,$key);
                   6945:                 }
                   6946:             }
                   6947:         }
                   6948:         if (@groupkeys > 0) {
                   6949:             foreach my $role (@groupkeys) {
                   6950:                 my ($trole,$area,$sec,$extendedarea);
                   6951:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6952:                     $trole = $1;
                   6953:                     $area = $2;
                   6954:                     $sec = $3;
                   6955:                     $extendedarea = $area.$sec;
                   6956:                     if (exists($$allgroups{$area})) {
                   6957:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6958:                             my $spec = $trole.'.'.$extendedarea;
                   6959:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6960:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6961:                         }
1.678     raeburn  6962:                     }
                   6963:                 }
                   6964:             }
                   6965:         }
                   6966:     }
1.800     albertel 6967:     foreach my $group (keys(%grouproles)) {
                   6968:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6969:     }
1.800     albertel 6970:     foreach my $role (keys(%{$allroles})) {
                   6971:         my %thesepriv;
1.941     raeburn  6972:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6973:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6974:             if ($item ne '') {
                   6975:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6976:                 if ($restrictions eq '') {
                   6977:                     $thesepriv{$privilege}='F';
                   6978:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6979:                     $thesepriv{$privilege}.=$restrictions;
                   6980:                 }
                   6981:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6982:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6983:             }
                   6984:         }
                   6985:         my $thesestr='';
1.1104    raeburn  6986:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6987: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6988: 	}
                   6989:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6990:     }
1.1172.2.91  raeburn  6991:     return ($author,$adv,$rar);
1.567     raeburn  6992: }
                   6993: 
1.994     raeburn  6994: sub role_status {
1.1104    raeburn  6995:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6996:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6997:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6998:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6999:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  7000:             $$where = '/'.$two;
1.994     raeburn  7001:             $$trolecode=$$role.'.'.$$where;
                   7002:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   7003:             $$tstatus='is';
1.1104    raeburn  7004:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  7005:                 $$tstatus='future';
1.1034    raeburn  7006:                 if ($$tstart<$now) {
                   7007:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  7008:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  7009:                             my (%allroles,%allgroups,$group_privs,
                   7010:                                 %groups_roles,@rolecodes);
1.1002    raeburn  7011:                             my %userroles = (
                   7012:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   7013:                             );
1.1064    raeburn  7014:                             @rolecodes = ('cm'); 
1.1002    raeburn  7015:                             my $spec=$$role.'.'.$$where;
                   7016:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   7017:                             if ($$role =~ /^cr\//) {
                   7018:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  7019:                                 push(@rolecodes,'cr');
1.1002    raeburn  7020:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  7021:                                 push(@rolecodes,$$role);
1.1002    raeburn  7022:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   7023:                                                     $env{'user.name'});
1.1064    raeburn  7024:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  7025:                                 (undef,my $group_privs) = split(/\//,$trole);
                   7026:                                 $group_privs = &unescape($group_privs);
                   7027:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  7028:                                 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  7029:                                 &get_groups_roles($tdomain,$trest,
                   7030:                                                   \%course_roles,\@rolecodes,
                   7031:                                                   \%groups_roles);
1.1002    raeburn  7032:                             } else {
1.1064    raeburn  7033:                                 push(@rolecodes,$$role);
1.1002    raeburn  7034:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   7035:                             }
1.1172.2.91  raeburn  7036:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   7037:                                                                    \%groups_roles);
1.1064    raeburn  7038:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  7039:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  7040:                         }
                   7041:                     }
1.1034    raeburn  7042:                     $$tstatus = 'is';
1.1002    raeburn  7043:                 }
1.994     raeburn  7044:             }
                   7045:             if ($$tend) {
1.1104    raeburn  7046:                 if ($$tend<$update) {
1.994     raeburn  7047:                     $$tstatus='expired';
                   7048:                 } elsif ($$tend<$now) {
                   7049:                     $$tstatus='will_not';
                   7050:                 }
                   7051:             }
                   7052:         }
                   7053:     }
                   7054: }
                   7055: 
1.1104    raeburn  7056: sub get_groups_roles {
                   7057:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   7058:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   7059:                   (ref($rolecodes) eq 'ARRAY') && 
                   7060:                   (ref($groups_roles) eq 'HASH')); 
                   7061:     if (keys(%{$cdom_courseroles}) > 0) {
                   7062:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   7063:         if ($cdom ne '' && $cnum ne '') {
                   7064:             foreach my $key (keys(%{$cdom_courseroles})) {
                   7065:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   7066:                     my $crsrole = $1;
                   7067:                     my $crssec = $2;
                   7068:                     if ($crsrole =~ /^cr/) {
                   7069:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   7070:                             push(@{$rolecodes},'cr');
                   7071:                         }
                   7072:                     } else {
                   7073:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   7074:                             push(@{$rolecodes},$crsrole);
                   7075:                         }
                   7076:                     }
                   7077:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   7078:                     if ($crssec ne '') {
                   7079:                         $rolekey .= "/$crssec";
                   7080:                     }
                   7081:                     $rolekey .= './';
                   7082:                     $groups_roles->{$rolekey} = $rolecodes;
                   7083:                 }
                   7084:             }
                   7085:         }
                   7086:     }
                   7087:     return;
                   7088: }
                   7089: 
                   7090: sub delete_env_groupprivs {
                   7091:     my ($where,$courseroles,$possroles) = @_;
                   7092:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   7093:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   7094:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   7095:         %{$courseroles->{$udom}} =
                   7096:             &get_my_roles('','','userroles',['active'],
                   7097:                           $possroles,[$udom],1);
                   7098:     }
                   7099:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   7100:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   7101:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   7102:             my $area = '/'.$cdom.'/'.$cnum;
                   7103:             my $privkey = "user.priv.$crsrole.$area";
                   7104:             if ($crssec ne '') {
                   7105:                 $privkey .= '/'.$crssec;
                   7106:             }
                   7107:             $privkey .= ".$area/$group";
                   7108:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   7109:         }
                   7110:     }
                   7111:     return;
                   7112: }
                   7113: 
1.994     raeburn  7114: sub check_adhoc_privs {
1.1172.2.86  raeburn  7115:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  7116:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  7117:     if ($sec) {
                   7118:         $cckey .= '/'.$sec;
                   7119:     }
1.1172.2.9  raeburn  7120:     my $setprivs;
1.994     raeburn  7121:     if ($env{$cckey}) {
                   7122:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  7123:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  7124:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  7125:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  7126:             $setprivs = 1;
1.994     raeburn  7127:         }
                   7128:     } else {
1.1172.2.87  raeburn  7129:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  7130:         $setprivs = 1;
1.994     raeburn  7131:     }
1.1172.2.9  raeburn  7132:     return $setprivs;
1.994     raeburn  7133: }
                   7134: 
                   7135: sub set_adhoc_privileges {
1.1172.2.84  raeburn  7136: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  7137:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  7138:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  7139:     if ($sec ne '') {
                   7140:         $area .= '/'.$sec;
                   7141:     }
1.994     raeburn  7142:     my $spec = $role.'.'.$area;
                   7143:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  7144:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  7145:     my %rolehash = ();
1.1172.2.89  raeburn  7146:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   7147:         my $rolename = $1;
1.1172.2.84  raeburn  7148:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  7149:         my %domdef = &get_domain_defaults($dcdom);
                   7150:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   7151:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   7152:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   7153:             }
                   7154:         }
1.1172.2.84  raeburn  7155:     } else {
                   7156:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   7157:     }
1.1172.2.91  raeburn  7158:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  7159:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  7160:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1172.2.146.  .1(raebu 7161:22):     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
                   7162:22):             ($caller eq 'tiny')) {
1.1088    raeburn  7163:         &appenv( {'request.role'        => $spec,
                   7164:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  7165:                   'request.course.sec'  => $sec, 
1.1088    raeburn  7166:                  }
                   7167:                );
                   7168:         my $tadv=0;
                   7169:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   7170:         &appenv({'request.role.adv'    => $tadv});
                   7171:     }
1.994     raeburn  7172: }
                   7173: 
1.12      www      7174: # --------------------------------------------------------------- get interface
                   7175: 
                   7176: sub get {
1.131     albertel 7177:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7178:    my $items='';
1.800     albertel 7179:    foreach my $item (@$storearr) {
                   7180:        $items.=&escape($item).'&';
1.191     harris41 7181:    }
1.12      www      7182:    $items=~s/\&$//;
1.620     albertel 7183:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7184:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 7185:    my $uhome=&homeserver($uname,$udomain);
                   7186: 
1.133     albertel 7187:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7188:    my @pairs=split(/\&/,$rep);
1.273     albertel 7189:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   7190:      return @pairs;
                   7191:    }
1.15      www      7192:    my %returnhash=();
1.42      www      7193:    my $i=0;
1.800     albertel 7194:    foreach my $item (@$storearr) {
                   7195:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7196:       $i++;
1.191     harris41 7197:    }
1.15      www      7198:    return %returnhash;
1.27      www      7199: }
                   7200: 
                   7201: # --------------------------------------------------------------- del interface
                   7202: 
                   7203: sub del {
1.133     albertel 7204:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      7205:    my $items='';
1.800     albertel 7206:    foreach my $item (@$storearr) {
                   7207:        $items.=&escape($item).'&';
1.191     harris41 7208:    }
1.984     neumanie 7209: 
1.27      www      7210:    $items=~s/\&$//;
1.620     albertel 7211:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7212:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7213:    my $uhome=&homeserver($uname,$udomain);
                   7214:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7215: }
                   7216: 
                   7217: # -------------------------------------------------------------- dump interface
                   7218: 
1.1172.2.22  raeburn  7219: sub unserialize {
                   7220:     my ($rep, $escapedkeys) = @_;
                   7221: 
                   7222:     return {} if $rep =~ /^error/;
                   7223: 
                   7224:     my %returnhash=();
                   7225:     foreach my $item (split(/\&/,$rep)) {
                   7226:         my ($key, $value) = split(/=/, $item, 2);
                   7227:         $key = unescape($key) unless $escapedkeys;
                   7228:         next if $key =~ /^error: 2 /;
                   7229:         $returnhash{$key} = &thaw_unescape($value);
                   7230:     }
                   7231:     return \%returnhash;
                   7232: }
                   7233: 
                   7234: # see Lond::dump_with_regexp
                   7235: # if $escapedkeys hash keys won't get unescaped.
1.15      www      7236: sub dump {
1.1172.2.146.  .1(raebu 7237:22):     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
1.755     albertel 7238:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7239:     if (!$uname) { $uname=$env{'user.name'}; }
                   7240:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 7241: 
1.1172.2.55  raeburn  7242:     if ($regexp) {
                   7243:         $regexp=&escape($regexp);
                   7244:     } else {
                   7245:         $regexp='.';
                   7246:     }
1.1172.2.22  raeburn  7247:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   7248:         # user is hosted on this machine
1.1172.2.55  raeburn  7249:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  7250:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  7251:         return %{&unserialize($reply, $escapedkeys)};
                   7252:     }
1.1172.2.146.  .1(raebu 7253:22):     my $rep;
                   7254:22):     if ($encrypt) {
                   7255:22):         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   7256:22):     } else {
                   7257:22):         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   7258:22):     }
1.755     albertel 7259:     my @pairs=split(/\&/,$rep);
                   7260:     my %returnhash=();
1.1098    foxr     7261:     if (!($rep =~ /^error/ )) {
                   7262: 	foreach my $item (@pairs) {
                   7263: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  7264:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     7265: 	    next if ($key =~ /^error: 2 /);
                   7266: 	    $returnhash{$key}=&thaw_unescape($value);
                   7267: 	}
1.755     albertel 7268:     }
                   7269:     return %returnhash;
1.407     www      7270: }
                   7271: 
1.1098    foxr     7272: 
1.717     albertel 7273: # --------------------------------------------------------- dumpstore interface
                   7274: 
                   7275: sub dumpstore {
                   7276:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  7277:    # same as dump but keys must be escaped. They may contain colon separated
                   7278:    # lists of values that may themself contain colons (e.g. symbs).
                   7279:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 7280: }
                   7281: 
1.407     www      7282: # -------------------------------------------------------------- keys interface
                   7283: 
                   7284: sub getkeys {
                   7285:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 7286:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7287:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      7288:    my $uhome=&homeserver($uname,$udomain);
                   7289:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   7290:    my @keyarray=();
1.800     albertel 7291:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  7292:       next if ($key =~ /^error: 2 /);
1.800     albertel 7293:       push(@keyarray,&unescape($key));
1.407     www      7294:    }
                   7295:    return @keyarray;
1.318     matthew  7296: }
                   7297: 
1.319     matthew  7298: # --------------------------------------------------------------- currentdump
                   7299: sub currentdump {
1.328     matthew  7300:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 7301:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   7302:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   7303:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  7304:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  7305:    my $rep;
                   7306: 
                   7307:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   7308:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   7309:                    $courseid)));
                   7310:    } else {
                   7311:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   7312:    }
                   7313: 
1.318     matthew  7314:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  7315:    #
1.318     matthew  7316:    my %returnhash=();
1.319     matthew  7317:    #
                   7318:    if ($rep eq "unknown_cmd") { 
                   7319:        # an old lond will not know currentdump
                   7320:        # Do a dump and make it look like a currentdump
1.822     albertel 7321:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  7322:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   7323:        my %hash = @tmp;
                   7324:        @tmp=();
1.424     matthew  7325:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  7326:    } else {
                   7327:        my @pairs=split(/\&/,$rep);
1.800     albertel 7328:        foreach my $pair (@pairs) {
                   7329:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  7330:            my ($symb,$param) = split(/:/,$key);
                   7331:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 7332:                                                         &thaw_unescape($value);
1.319     matthew  7333:        }
1.191     harris41 7334:    }
1.12      www      7335:    return %returnhash;
1.424     matthew  7336: }
                   7337: 
                   7338: sub convert_dump_to_currentdump{
                   7339:     my %hash = %{shift()};
                   7340:     my %returnhash;
                   7341:     # Code ripped from lond, essentially.  The only difference
                   7342:     # here is the unescaping done by lonnet::dump().  Conceivably
                   7343:     # we might run in to problems with parameter names =~ /^v\./
                   7344:     while (my ($key,$value) = each(%hash)) {
                   7345:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 7346: 	$symb  = &unescape($symb);
                   7347: 	$param = &unescape($param);
1.424     matthew  7348:         next if ($v eq 'version' || $symb eq 'keys');
                   7349:         next if (exists($returnhash{$symb}) &&
                   7350:                  exists($returnhash{$symb}->{$param}) &&
                   7351:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   7352:         $returnhash{$symb}->{$param}=$value;
                   7353:         $returnhash{$symb}->{'v.'.$param}=$v;
                   7354:     }
                   7355:     #
                   7356:     # Remove all of the keys in the hashes which keep track of
                   7357:     # the version of the parameter.
                   7358:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   7359:         # use a foreach because we are going to delete from the hash.
                   7360:         foreach my $key (keys(%$param_hash)) {
                   7361:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   7362:         }
                   7363:     }
                   7364:     return \%returnhash;
1.12      www      7365: }
                   7366: 
1.627     albertel 7367: # ------------------------------------------------------ critical inc interface
                   7368: 
                   7369: sub cinc {
                   7370:     return &inc(@_,'critical');
                   7371: }
                   7372: 
1.449     matthew  7373: # --------------------------------------------------------------- inc interface
                   7374: 
                   7375: sub inc {
1.627     albertel 7376:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7377:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7378:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7379:     my $uhome=&homeserver($uname,$udomain);
                   7380:     my $items='';
                   7381:     if (! ref($store)) {
                   7382:         # got a single value, so use that instead
                   7383:         $items = &escape($store).'=&';
                   7384:     } elsif (ref($store) eq 'SCALAR') {
                   7385:         $items = &escape($$store).'=&';        
                   7386:     } elsif (ref($store) eq 'ARRAY') {
                   7387:         $items = join('=&',map {&escape($_);} @{$store});
                   7388:     } elsif (ref($store) eq 'HASH') {
                   7389:         while (my($key,$value) = each(%{$store})) {
                   7390:             $items.= &escape($key).'='.&escape($value).'&';
                   7391:         }
                   7392:     }
                   7393:     $items=~s/\&$//;
1.627     albertel 7394:     if ($critical) {
                   7395: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7396:     } else {
                   7397: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7398:     }
1.449     matthew  7399: }
                   7400: 
1.12      www      7401: # --------------------------------------------------------------- put interface
                   7402: 
                   7403: sub put {
1.1172.2.146.  .1(raebu 7404:22):    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
1.620     albertel 7405:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7406:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7407:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7408:    my $items='';
1.800     albertel 7409:    foreach my $item (keys(%$storehash)) {
                   7410:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7411:    }
1.12      www      7412:    $items=~s/\&$//;
1.1172.2.146.  .1(raebu 7413:22):    if ($encrypt) {
                   7414:22):        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
                   7415:22):    } else {
                   7416:22):        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
                   7417:22):    }
1.47      www      7418: }
                   7419: 
1.631     albertel 7420: # ------------------------------------------------------------ newput interface
                   7421: 
                   7422: sub newput {
                   7423:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7424:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7425:    if (!$uname) { $uname=$env{'user.name'}; }
                   7426:    my $uhome=&homeserver($uname,$udomain);
                   7427:    my $items='';
                   7428:    foreach my $key (keys(%$storehash)) {
                   7429:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7430:    }
                   7431:    $items=~s/\&$//;
                   7432:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7433: }
                   7434: 
                   7435: # ---------------------------------------------------------  putstore interface
                   7436: 
1.524     raeburn  7437: sub putstore {
1.1172.2.59  raeburn  7438:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7439:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7440:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7441:    my $uhome=&homeserver($uname,$udomain);
                   7442:    my $items='';
1.715     albertel 7443:    foreach my $key (keys(%$storehash)) {
                   7444:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7445:    }
1.715     albertel 7446:    $items=~s/\&$//;
1.716     albertel 7447:    my $esc_symb=&escape($symb);
                   7448:    my $esc_v=&escape($version);
1.715     albertel 7449:    my $reply =
1.716     albertel 7450:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7451: 	      $uhome);
1.1172.2.59  raeburn  7452:    if (($tolog) && ($reply eq 'ok')) {
                   7453:        my $namevalue='';
                   7454:        foreach my $key (keys(%{$storehash})) {
                   7455:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7456:        }
1.1172.2.134  raeburn  7457:        my $ip = &get_requestor_ip();
1.1172.2.135  raeburn  7458:        $namevalue .= 'ip='.&escape($ip).
1.1172.2.59  raeburn  7459:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7460:                      '&version='.$esc_v.
                   7461:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7462:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7463:    }
1.715     albertel 7464:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7465:        # gfall back to way things use to be done
1.715     albertel 7466:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7467: 			    $uname);
1.524     raeburn  7468:    }
1.715     albertel 7469:    return $reply;
                   7470: }
                   7471: 
                   7472: sub old_putstore {
1.716     albertel 7473:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7474:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7475:     if (!$uname) { $uname=$env{'user.name'}; }
                   7476:     my $uhome=&homeserver($uname,$udomain);
                   7477:     my %newstorehash;
1.800     albertel 7478:     foreach my $item (keys(%$storehash)) {
                   7479: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7480: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7481:     }
                   7482:     my $items='';
                   7483:     my %allitems = ();
1.800     albertel 7484:     foreach my $item (keys(%newstorehash)) {
                   7485: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7486: 	    my $key = $1.':keys:'.$2;
                   7487: 	    $allitems{$key} .= $3.':';
                   7488: 	}
1.800     albertel 7489: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7490:     }
1.800     albertel 7491:     foreach my $item (keys(%allitems)) {
                   7492: 	$allitems{$item} =~ s/\:$//;
                   7493: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7494:     }
                   7495:     $items=~s/\&$//;
                   7496:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7497: }
                   7498: 
1.47      www      7499: # ------------------------------------------------------ critical put interface
                   7500: 
                   7501: sub cput {
1.134     albertel 7502:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7503:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7504:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7505:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7506:    my $items='';
1.800     albertel 7507:    foreach my $item (keys(%$storehash)) {
                   7508:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7509:    }
1.47      www      7510:    $items=~s/\&$//;
1.134     albertel 7511:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7512: }
                   7513: 
                   7514: # -------------------------------------------------------------- eget interface
                   7515: 
                   7516: sub eget {
1.133     albertel 7517:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7518:    my $items='';
1.800     albertel 7519:    foreach my $item (@$storearr) {
                   7520:        $items.=&escape($item).'&';
1.191     harris41 7521:    }
1.12      www      7522:    $items=~s/\&$//;
1.620     albertel 7523:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7524:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7525:    my $uhome=&homeserver($uname,$udomain);
                   7526:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7527:    my @pairs=split(/\&/,$rep);
                   7528:    my %returnhash=();
1.42      www      7529:    my $i=0;
1.800     albertel 7530:    foreach my $item (@$storearr) {
                   7531:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7532:       $i++;
1.191     harris41 7533:    }
1.12      www      7534:    return %returnhash;
                   7535: }
                   7536: 
1.667     albertel 7537: # ------------------------------------------------------------ tmpput interface
                   7538: sub tmpput {
1.802     raeburn  7539:     my ($storehash,$server,$context)=@_;
1.667     albertel 7540:     my $items='';
1.800     albertel 7541:     foreach my $item (keys(%$storehash)) {
                   7542: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7543:     }
                   7544:     $items=~s/\&$//;
1.802     raeburn  7545:     if (defined($context)) {
                   7546:         $items .= ':'.&escape($context);
                   7547:     }
1.667     albertel 7548:     return &reply("tmpput:$items",$server);
                   7549: }
                   7550: 
                   7551: # ------------------------------------------------------------ tmpget interface
                   7552: sub tmpget {
1.688     albertel 7553:     my ($token,$server)=@_;
                   7554:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7555:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7556:     my %returnhash;
1.1172.2.85  raeburn  7557:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7558:         return %returnhash;
                   7559:     }
1.667     albertel 7560:     foreach my $item (split(/\&/,$rep)) {
                   7561: 	my ($key,$value)=split(/=/,$item);
                   7562: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7563:     }
                   7564:     return %returnhash;
                   7565: }
                   7566: 
1.1113    raeburn  7567: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7568: sub tmpdel {
                   7569:     my ($token,$server)=@_;
                   7570:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7571:     return &reply("tmpdel:$token",$server);
                   7572: }
                   7573: 
1.1172.2.13  raeburn  7574: # ------------------------------------------------------------ get_timebased_id
                   7575: 
                   7576: sub get_timebased_id {
                   7577:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7578:         $maxtries) = @_;
                   7579:     my ($newid,$error,$dellock);
                   7580:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7581:         return ('','ok','invalid call to get suffix');
                   7582:     }
                   7583: 
                   7584: # set defaults for any optional args for which values were not supplied
                   7585:     if ($who eq '') {
                   7586:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7587:     }
                   7588:     if (!$locktries) {
                   7589:         $locktries = 3;
                   7590:     }
                   7591:     if (!$maxtries) {
                   7592:         $maxtries = 10;
                   7593:     }
                   7594: 
                   7595:     if (($cdom eq '') || ($cnum eq '')) {
                   7596:         if ($env{'request.course.id'}) {
                   7597:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7598:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7599:         }
                   7600:         if (($cdom eq '') || ($cnum eq '')) {
                   7601:             return ('','ok','call to get suffix not in course context');
                   7602:         }
                   7603:     }
                   7604: 
                   7605: # construct locking item
                   7606:     my $lockhash = {
                   7607:                       $prefix."\0".'locked_'.$keyid => $who,
                   7608:                    };
                   7609:     my $tries = 0;
                   7610: 
                   7611: # attempt to get lock on nohist_$namespace file
                   7612:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7613:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7614:         $tries ++;
                   7615:         sleep 1;
                   7616:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7617:     }
                   7618: 
                   7619: # attempt to get unique identifier, based on current timestamp
                   7620:     if ($gotlock eq 'ok') {
                   7621:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7622:         my $id = time;
                   7623:         $newid = $id;
1.1172.2.56  raeburn  7624:         if ($idtype eq 'addcode') {
                   7625:             $newid .= &sixnum_code();
                   7626:         }
1.1172.2.13  raeburn  7627:         my $idtries = 0;
                   7628:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7629:             if ($idtype eq 'concat') {
                   7630:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7631:             } elsif ($idtype eq 'addcode') {
                   7632:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7633:             } else {
                   7634:                 $newid ++;
                   7635:             }
                   7636:             $idtries ++;
                   7637:         }
                   7638:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7639:             my %new_item =  (
                   7640:                               $prefix."\0".$newid => $who,
                   7641:                             );
                   7642:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7643:                                                  $cdom,$cnum);
                   7644:             if ($putresult ne 'ok') {
                   7645:                 undef($newid);
                   7646:                 $error = 'error saving new item: '.$putresult;
                   7647:             }
                   7648:         } else {
1.1172.2.56  raeburn  7649:              undef($newid);
1.1172.2.13  raeburn  7650:              $error = ('error: no unique suffix available for the new item ');
                   7651:         }
                   7652: #  remove lock
                   7653:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7654:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7655:     } else {
                   7656:         $error = "error: could not obtain lockfile\n";
                   7657:         $dellock = 'ok';
1.1172.2.58  raeburn  7658:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7659:             $dellock = 'nolock';
                   7660:         }
1.1172.2.13  raeburn  7661:     }
                   7662:     return ($newid,$dellock,$error);
                   7663: }
                   7664: 
1.1172.2.56  raeburn  7665: sub sixnum_code {
                   7666:     my $code;
                   7667:     for (0..6) {
                   7668:         $code .= int( rand(9) );
                   7669:     }
                   7670:     return $code;
                   7671: }
                   7672: 
1.765     albertel 7673: # -------------------------------------------------- portfolio access checking
                   7674: 
                   7675: sub portfolio_access {
1.1172.2.77  raeburn  7676:     my ($requrl,$clientip) = @_;
1.765     albertel 7677:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7678:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7679:     if ($result) {
                   7680:         my %setters;
                   7681:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1172.2.142  raeburn  7682:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
                   7683:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
                   7684:             if (($startblock && $endblock) || ($by_ip))  {
1.814     raeburn  7685:                 return 'B';
                   7686:             }
                   7687:         } else {
1.1172.2.142  raeburn  7688:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdo) =
                   7689:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   7690:             if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  7691:                 return 'B';
                   7692:             }
                   7693:         }
                   7694:     }
1.765     albertel 7695:     if ($result eq 'ok') {
1.766     albertel 7696:        return 'F';
1.765     albertel 7697:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7698:        return 'A';
1.765     albertel 7699:     }
1.766     albertel 7700:     return '';
1.765     albertel 7701: }
                   7702: 
                   7703: sub get_portfolio_access {
1.1172.2.77  raeburn  7704:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7705: 
                   7706:     if (!ref($access_hash)) {
                   7707: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7708: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7709: 						   $file_name);
                   7710: 	$access_hash = $access_controls{$file_name};
                   7711:     }
                   7712: 
1.1172.2.77  raeburn  7713:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7714:     my $now = time;
                   7715:     if (ref($access_hash) eq 'HASH') {
                   7716:         foreach my $key (keys(%{$access_hash})) {
                   7717:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7718:             if ($start > $now) {
                   7719:                 next;
                   7720:             }
                   7721:             if ($end && $end<$now) {
                   7722:                 next;
                   7723:             }
                   7724:             if ($scope eq 'public') {
                   7725:                 $public = $key;
                   7726:                 last;
                   7727:             } elsif ($scope eq 'guest') {
                   7728:                 $guest = $key;
                   7729:             } elsif ($scope eq 'domains') {
                   7730:                 push(@domains,$key);
                   7731:             } elsif ($scope eq 'users') {
                   7732:                 push(@users,$key);
                   7733:             } elsif ($scope eq 'course') {
                   7734:                 push(@courses,$key);
                   7735:             } elsif ($scope eq 'group') {
                   7736:                 push(@groups,$key);
1.1172.2.77  raeburn  7737:             } elsif ($scope eq 'ip') {
                   7738:                 push(@ips,$key);
1.765     albertel 7739:             }
                   7740:         }
                   7741:         if ($public) {
                   7742:             return 'ok';
1.1172.2.77  raeburn  7743:         } elsif (@ips > 0) {
                   7744:             my $allowed;
                   7745:             foreach my $ipkey (@ips) {
                   7746:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7747:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7748:                         $allowed = 1;
                   7749:                         last;
                   7750:                     }
                   7751:                 }
                   7752:             }
                   7753:             if ($allowed) {
                   7754:                 return 'ok';
                   7755:             }
1.765     albertel 7756:         }
                   7757:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7758:             if ($guest) {
                   7759:                 return $guest;
                   7760:             }
                   7761:         } else {
                   7762:             if (@domains > 0) {
                   7763:                 foreach my $domkey (@domains) {
                   7764:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7765:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7766:                             return 'ok';
                   7767:                         }
                   7768:                     }
                   7769:                 }
                   7770:             }
                   7771:             if (@users > 0) {
                   7772:                 foreach my $userkey (@users) {
1.865     raeburn  7773:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7774:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7775:                             if (ref($item) eq 'HASH') {
                   7776:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7777:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7778:                                     return 'ok';
                   7779:                                 }
                   7780:                             }
                   7781:                         }
                   7782:                     } 
1.765     albertel 7783:                 }
                   7784:             }
                   7785:             my %roleshash;
                   7786:             my @courses_and_groups = @courses;
                   7787:             push(@courses_and_groups,@groups); 
                   7788:             if (@courses_and_groups > 0) {
                   7789:                 my (%allgroups,%allroles); 
                   7790:                 my ($start,$end,$role,$sec,$group);
                   7791:                 foreach my $envkey (%env) {
1.1060    raeburn  7792:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7793:                         my $cid = $2.'_'.$3; 
                   7794:                         if ($1 eq 'gr') {
                   7795:                             $group = $4;
                   7796:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7797:                         } else {
                   7798:                             if ($4 eq '') {
                   7799:                                 $sec = 'none';
                   7800:                             } else {
                   7801:                                 $sec = $4;
                   7802:                             }
                   7803:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7804:                         }
1.811     albertel 7805:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7806:                         my $cid = $2.'_'.$3;
                   7807:                         if ($4 eq '') {
                   7808:                             $sec = 'none';
                   7809:                         } else {
                   7810:                             $sec = $4;
                   7811:                         }
                   7812:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7813:                     }
                   7814:                 }
                   7815:                 if (keys(%allroles) == 0) {
                   7816:                     return;
                   7817:                 }
                   7818:                 foreach my $key (@courses_and_groups) {
                   7819:                     my %content = %{$$access_hash{$key}};
                   7820:                     my $cnum = $content{'number'};
                   7821:                     my $cdom = $content{'domain'};
                   7822:                     my $cid = $cdom.'_'.$cnum;
                   7823:                     if (!exists($allroles{$cid})) {
                   7824:                         next;
                   7825:                     }    
                   7826:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7827:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7828:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7829:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7830:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7831:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7832:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7833:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7834:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7835:                                         if (grep/^all$/,@sections) {
                   7836:                                             return 'ok';
                   7837:                                         } else {
                   7838:                                             if (grep/^$sec$/,@sections) {
                   7839:                                                 return 'ok';
                   7840:                                             }
                   7841:                                         }
                   7842:                                     }
                   7843:                                 }
                   7844:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7845:                                     if (grep/^none$/,@groups) {
                   7846:                                         return 'ok';
                   7847:                                     }
                   7848:                                 } else {
                   7849:                                     if (grep/^all$/,@groups) {
                   7850:                                         return 'ok';
                   7851:                                     } 
                   7852:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7853:                                         if (grep/^$group$/,@groups) {
                   7854:                                             return 'ok';
                   7855:                                         }
                   7856:                                     }
                   7857:                                 } 
                   7858:                             }
                   7859:                         }
                   7860:                     }
                   7861:                 }
                   7862:             }
                   7863:             if ($guest) {
                   7864:                 return $guest;
                   7865:             }
                   7866:         }
                   7867:     }
                   7868:     return;
                   7869: }
                   7870: 
                   7871: sub course_group_datechecker {
                   7872:     my ($dates,$now,$status) = @_;
                   7873:     my ($start,$end) = split(/\./,$dates);
                   7874:     if (!$start && !$end) {
                   7875:         return 'ok';
                   7876:     }
                   7877:     if (grep/^active$/,@{$status}) {
                   7878:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7879:             return 'ok';
                   7880:         }
                   7881:     }
                   7882:     if (grep/^previous$/,@{$status}) {
                   7883:         if ($end > $now ) {
                   7884:             return 'ok';
                   7885:         }
                   7886:     }
                   7887:     if (grep/^future$/,@{$status}) {
                   7888:         if ($start > $now) {
                   7889:             return 'ok';
                   7890:         }
                   7891:     }
                   7892:     return; 
                   7893: }
                   7894: 
                   7895: sub parse_portfolio_url {
                   7896:     my ($url) = @_;
                   7897: 
                   7898:     my ($type,$udom,$unum,$group,$file_name);
                   7899:     
1.823     albertel 7900:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7901: 	$type = 1;
                   7902:         $udom = $1;
                   7903:         $unum = $2;
                   7904:         $file_name = $3;
1.823     albertel 7905:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7906: 	$type = 2;
                   7907:         $udom = $1;
                   7908:         $unum = $2;
                   7909:         $group = $3;
                   7910:         $file_name = $3.'/'.$4;
                   7911:     }
                   7912:     if (wantarray) {
                   7913: 	return ($type,$udom,$unum,$file_name,$group);
                   7914:     }
                   7915:     return $type;
                   7916: }
                   7917: 
                   7918: sub is_portfolio_url {
                   7919:     my ($url) = @_;
                   7920:     return scalar(&parse_portfolio_url($url));
                   7921: }
                   7922: 
1.798     raeburn  7923: sub is_portfolio_file {
                   7924:     my ($file) = @_;
1.820     raeburn  7925:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7926:         return 1;
                   7927:     }
                   7928:     return;
                   7929: }
                   7930: 
1.1172.2.146.  .13(raeb 7931:-23): sub is_coursetool_logo {
                   7932:-23):     my ($uri) = @_;
                   7933:-23):     if ($env{'request.course.id'}) {
                   7934:-23):         my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   7935:-23):         if ($uri =~ m{^/*uploaded\Q$courseurl\E/toollogo/\d+/[^/]+$}) {
                   7936:-23):             return 1;
                   7937:-23):         }
                   7938:-23):     }
                   7939:-23):     return;
                   7940:-23): }
                   7941:-23): 
1.976     raeburn  7942: sub usertools_access {
1.1084    raeburn  7943:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7944:     my ($access,%tools);
                   7945:     if ($context eq '') {
                   7946:         $context = 'tools';
                   7947:     }
                   7948:     if ($context eq 'requestcourses') {
                   7949:         %tools = (
                   7950:                       official   => 1,
                   7951:                       unofficial => 1,
1.1006    raeburn  7952:                       community  => 1,
1.1172.2.37  raeburn  7953:                       textbook   => 1,
1.1172.2.146.  .13(raeb 7954:-23):                       lti        => 1,
1.985     raeburn  7955:                  );
1.1172.2.9  raeburn  7956:     } elsif ($context eq 'requestauthor') {
                   7957:         %tools = (
                   7958:                       requestauthor => 1,
                   7959:                  );
1.985     raeburn  7960:     } else {
                   7961:         %tools = (
                   7962:                       aboutme   => 1,
                   7963:                       blog      => 1,
1.1172.2.6  raeburn  7964:                       webdav    => 1,
1.985     raeburn  7965:                       portfolio => 1,
1.1172.2.146.  .6(raebu 7966:22):                       timezone  => 1,
1.985     raeburn  7967:                  );
                   7968:     }
1.976     raeburn  7969:     return if (!defined($tools{$tool}));
                   7970: 
1.1172.2.35  raeburn  7971:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7972:         $udom = $env{'user.domain'};
                   7973:         $uname = $env{'user.name'};
                   7974:     }
                   7975: 
1.978     raeburn  7976:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7977:         if ($action ne 'reload') {
1.985     raeburn  7978:             if ($context eq 'requestcourses') {
                   7979:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7980:             } elsif ($context eq 'requestauthor') {
                   7981:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7982:             } else {
                   7983:                 return $env{'environment.availabletools.'.$tool};
                   7984:             }
                   7985:         }
1.976     raeburn  7986:     }
                   7987: 
1.1172.2.9  raeburn  7988:     my ($toolstatus,$inststatus,$envkey);
                   7989:     if ($context eq 'requestauthor') {
                   7990:         $envkey = $context;
                   7991:     } else {
                   7992:         $envkey = $context.'.'.$tool;
                   7993:     }
1.976     raeburn  7994: 
1.985     raeburn  7995:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7996:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7997:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7998:         $inststatus = $env{'environment.inststatus'};
                   7999:     } else {
1.1084    raeburn  8000:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  8001:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  8002:             $inststatus = $userenvref->{'inststatus'};
                   8003:         } else {
1.1172.2.9  raeburn  8004:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   8005:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  8006:             $inststatus = $userenv{'inststatus'};
                   8007:         }
1.976     raeburn  8008:     }
                   8009: 
                   8010:     if ($toolstatus ne '') {
                   8011:         if ($toolstatus) {
                   8012:             $access = 1;
                   8013:         } else {
                   8014:             $access = 0;
                   8015:         }
                   8016:         return $access;
                   8017:     }
                   8018: 
1.1084    raeburn  8019:     my ($is_adv,%domdef);
                   8020:     if (ref($is_advref) eq 'HASH') {
                   8021:         $is_adv = $is_advref->{'is_adv'};
                   8022:     } else {
                   8023:         $is_adv = &is_advanced_user($udom,$uname);
                   8024:     }
                   8025:     if (ref($domdefref) eq 'HASH') {
                   8026:         %domdef = %{$domdefref};
                   8027:     } else {
                   8028:         %domdef = &get_domain_defaults($udom);
                   8029:     }
1.976     raeburn  8030:     if (ref($domdef{$tool}) eq 'HASH') {
                   8031:         if ($is_adv) {
                   8032:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   8033:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   8034:                     $access = 1;
                   8035:                 } else {
                   8036:                     $access = 0;
                   8037:                 }
                   8038:                 return $access;
                   8039:             }
                   8040:         }
                   8041:         if ($inststatus ne '') {
                   8042:             my ($hasaccess,$hasnoaccess);
                   8043:             foreach my $affiliation (split(/:/,$inststatus)) {
                   8044:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   8045:                     if ($domdef{$tool}{$affiliation}) {
                   8046:                         $hasaccess = 1;
                   8047:                     } else {
                   8048:                         $hasnoaccess = 1;
                   8049:                     }
                   8050:                 }
                   8051:             }
                   8052:             if ($hasaccess || $hasnoaccess) {
                   8053:                 if ($hasaccess) {
                   8054:                     $access = 1;
                   8055:                 } elsif ($hasnoaccess) {
                   8056:                     $access = 0; 
                   8057:                 }
                   8058:                 return $access;
                   8059:             }
                   8060:         } else {
                   8061:             if ($domdef{$tool}{'default'} ne '') {
                   8062:                 if ($domdef{$tool}{'default'}) {
                   8063:                     $access = 1;
                   8064:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   8065:                     $access = 0;
                   8066:                 }
                   8067:                 return $access;
                   8068:             }
                   8069:         }
                   8070:     } else {
1.1172.2.6  raeburn  8071:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  8072:             $access = 1;
                   8073:         } else {
                   8074:             $access = 0;
                   8075:         }
1.976     raeburn  8076:         return $access;
                   8077:     }
                   8078: }
                   8079: 
1.1050    raeburn  8080: sub is_course_owner {
                   8081:     my ($cdom,$cnum,$udom,$uname) = @_;
                   8082:     if (($udom eq '') || ($uname eq '')) {
                   8083:         $udom = $env{'user.domain'};
                   8084:         $uname = $env{'user.name'};
                   8085:     }
                   8086:     unless (($udom eq '') || ($uname eq '')) {
                   8087:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   8088:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   8089:                 return 1;
                   8090:             } else {
                   8091:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   8092:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   8093:                     return 1;
                   8094:                 }
                   8095:             }
                   8096:         }
                   8097:     }
                   8098:     return;
                   8099: }
                   8100: 
1.976     raeburn  8101: sub is_advanced_user {
                   8102:     my ($udom,$uname) = @_;
1.1085    raeburn  8103:     if ($udom ne '' && $uname ne '') {
                   8104:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  8105:             if (wantarray) {
                   8106:                 return ($env{'user.adv'},$env{'user.author'});
                   8107:             } else {
                   8108:                 return $env{'user.adv'};
                   8109:             }
1.1085    raeburn  8110:         }
                   8111:     }
1.976     raeburn  8112:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   8113:     my %allroles;
1.1128    raeburn  8114:     my ($is_adv,$is_author);
1.976     raeburn  8115:     foreach my $role (keys(%roleshash)) {
                   8116:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   8117:         my $area = '/'.$tdomain.'/'.$trest;
                   8118:         if ($sec ne '') {
                   8119:             $area .= '/'.$sec;
                   8120:         }
                   8121:         if (($area ne '') && ($trole ne '')) {
                   8122:             my $spec=$trole.'.'.$area;
                   8123:             if ($trole =~ /^cr\//) {
                   8124:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   8125:             } elsif ($trole ne 'gr') {
                   8126:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   8127:             }
1.1128    raeburn  8128:             if ($trole eq 'au') {
                   8129:                 $is_author = 1;
                   8130:             }
1.976     raeburn  8131:         }
                   8132:     }
                   8133:     foreach my $role (keys(%allroles)) {
                   8134:         last if ($is_adv);
                   8135:         foreach my $item (split(/:/,$allroles{$role})) {
                   8136:             if ($item ne '') {
                   8137:                 my ($privilege,$restrictions)=split(/&/,$item);
                   8138:                 if ($privilege eq 'adv') {
                   8139:                     $is_adv = 1;
                   8140:                     last;
                   8141:                 }
                   8142:             }
                   8143:         }
                   8144:     }
1.1128    raeburn  8145:     if (wantarray) {
                   8146:         return ($is_adv,$is_author);
                   8147:     }
1.976     raeburn  8148:     return $is_adv;
                   8149: }
1.798     raeburn  8150: 
1.1035    raeburn  8151: sub check_can_request {
1.1172.2.146.  .13(raeb 8152:-23):     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  8153:     my $canreq = 0;
1.1172.2.146.  .13(raeb 8154:-23):     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8155:-23):         $uname = $env{'user.name'};
                   8156:-23):         $udom = $env{'user.domain'};
                   8157:-23):     }
1.1035    raeburn  8158:     my ($types,$typename) = &Apache::loncommon::course_types();
                   8159:     my @options = ('approval','validate','autolimit');
                   8160:     my $optregex = join('|',@options);
                   8161:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   8162:         foreach my $type (@{$types}) {
1.1172.2.146.  .13(raeb 8163:-23):             if (&usertools_access($uname,$udom,$type,undef,
                   8164:-23):                                   'requestcourses')) {
1.1035    raeburn  8165:                 $canreq ++;
1.1036    raeburn  8166:                 if (ref($request_domains) eq 'HASH') {
1.1172.2.146.  .13(raeb 8167:-23):                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  8168:                 }
1.1172.2.146.  .13(raeb 8169:-23):                 if ($dom eq $udom) {
1.1035    raeburn  8170:                     $can_request->{$type} = 1;
                   8171:                 }
                   8172:             }
1.1172.2.146.  .13(raeb 8173:-23):             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   8174:-23):                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  8175:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   8176:                 if (@curr > 0) {
1.1036    raeburn  8177:                     foreach my $item (@curr) {
                   8178:                         if (ref($request_domains) eq 'HASH') {
                   8179:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   8180:                             if ($otherdom ne '') {
                   8181:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   8182:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   8183:                                         push(@{$request_domains->{$type}},$otherdom);
                   8184:                                     }
                   8185:                                 } else {
                   8186:                                     push(@{$request_domains->{$type}},$otherdom);
                   8187:                                 }
                   8188:                             }
                   8189:                         }
                   8190:                     }
1.1172.2.146.  .13(raeb 8191:-23):                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  8192:                         $canreq ++;
1.1035    raeburn  8193:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   8194:                             $can_request->{$type} = 1;
                   8195:                         }
                   8196:                     }
                   8197:                 }
                   8198:             }
                   8199:         }
                   8200:     }
                   8201:     return $canreq;
                   8202: }
                   8203: 
1.341     www      8204: # ---------------------------------------------- Custom access rule evaluation
                   8205: 
                   8206: sub customaccess {
                   8207:     my ($priv,$uri)=@_;
1.807     albertel 8208:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      8209:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 8210:     $udom = &LONCAPA::clean_domain($udom);
                   8211:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      8212:     my $access=0;
1.800     albertel 8213:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 8214: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   8215: 	if ($type eq 'user') {
                   8216: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 8217: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 8218: 		if ($tdom) {
                   8219: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   8220: 		}
1.896     albertel 8221: 		if ($tuname) {
                   8222: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 8223: 		}
                   8224: 		$access=($effect eq 'allow');
                   8225: 		last;
                   8226: 	    }
                   8227: 	} else {
                   8228: 	    if ($role) {
                   8229: 		if ($role ne $urole) { next; }
                   8230: 	    }
                   8231: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   8232: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   8233: 		if ($tdom) {
                   8234: 		    if ($tdom ne $udom) { next; }
                   8235: 		}
                   8236: 		if ($tcrs) {
                   8237: 		    if ($tcrs ne $ucrs) { next; }
                   8238: 		}
                   8239: 		if ($tsec) {
                   8240: 		    if ($tsec ne $usec) { next; }
                   8241: 		}
                   8242: 		$access=($effect eq 'allow');
                   8243: 		last;
                   8244: 	    }
                   8245: 	    if ($realm eq '' && $role eq '') {
                   8246: 		$access=($effect eq 'allow');
                   8247: 	    }
1.402     bowersj2 8248: 	}
1.341     www      8249:     }
                   8250:     return $access;
                   8251: }
                   8252: 
1.103     harris41 8253: # ------------------------------------------------- Check for a user privilege
1.12      www      8254: 
                   8255: sub allowed {
1.1172.2.146.  .1(raebu 8256:22):     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
1.705     albertel 8257:     my $ver_orguri=$uri;
1.439     www      8258:     $uri=&deversion($uri);
1.152     www      8259:     my $orguri=$uri;
1.52      www      8260:     $uri=&declutter($uri);
1.809     raeburn  8261: 
1.810     raeburn  8262:     if ($priv eq 'evb') {
1.1172.2.146.  .3(raebu 8263:22): # Evade communication block restrictions for specified role in a course or domain
1.810     raeburn  8264:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   8265:             return $1;
                   8266:         } else {
                   8267:             return;
                   8268:         }
                   8269:     }
                   8270: 
1.620     albertel 8271:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      8272: # Free bre access to adm and meta resources
1.1172.2.146.  .1(raebu 8273:22):     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
1.769     albertel 8274: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   8275: 	&& ($priv eq 'bre')) {
1.14      www      8276: 	return 'F';
1.159     www      8277:     }
                   8278: 
1.545     banghart 8279: # Free bre access to user's own portfolio contents
1.714     raeburn  8280:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  8281:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  8282: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  8283:         my %setters;
1.1172.2.142  raeburn  8284:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   8285:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   8286:         if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  8287:             return 'B';
                   8288:         } else {
                   8289:             return 'F';
                   8290:         }
1.545     banghart 8291:     }
                   8292: 
1.762     raeburn  8293: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  8294:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   8295:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   8296:         if (exists($env{'request.course.id'})) {
                   8297:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8298:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8299:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   8300:                 my $courseprivid=$env{'request.course.id'};
                   8301:                 $courseprivid=~s/\_/\//;
                   8302:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   8303:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   8304:                     return $1; 
1.762     raeburn  8305:                 } else {
                   8306:                     if ($env{'request.course.sec'}) {
                   8307:                         $courseprivid.='/'.$env{'request.course.sec'};
                   8308:                     }
                   8309:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   8310:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   8311:                         return $2;
                   8312:                     }
1.714     raeburn  8313:                 }
                   8314:             }
                   8315:         }
                   8316:     }
                   8317: 
1.159     www      8318: # Free bre to public access
                   8319: 
                   8320:     if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8321:22):         my $copyright;
                   8322:22):         unless ($uri =~ /ext\.tool/) {
                   8323:22):             $copyright=&metadata($uri,'copyright');
                   8324:22):         }
1.620     albertel 8325: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      8326:            return 'F'; 
                   8327:         }
1.238     www      8328:         if ($copyright eq 'priv') {
                   8329:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8330: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      8331: 		return '';
                   8332:             }
                   8333:         }
                   8334:         if ($copyright eq 'domain') {
                   8335:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8336: 	    unless (($env{'user.domain'} eq $1) ||
                   8337:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      8338: 		return '';
                   8339:             }
1.262     matthew  8340:         }
1.620     albertel 8341:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  8342:             # Library role, so allow browsing of resources in this domain.
                   8343:             return 'F';
1.238     www      8344:         }
1.341     www      8345:         if ($copyright eq 'custom') {
                   8346: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   8347:         }
1.14      www      8348:     }
1.264     matthew  8349:     # Domain coordinator is trying to create a course
1.620     albertel 8350:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  8351:         # uri is the requested domain in this case.
                   8352:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  8353:         # a role of dc for the domain in question.
1.620     albertel 8354:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  8355:     }
1.29      www      8356: 
1.52      www      8357:     my $thisallowed='';
                   8358:     my $statecond=0;
                   8359:     my $courseprivid='';
                   8360: 
1.1039    raeburn  8361:     my $ownaccess;
1.1043    raeburn  8362:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  8363:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   8364:         if ($uri eq '') {
                   8365:             $ownaccess = 1;
                   8366:         } else {
                   8367:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   8368:                 my $udom = $env{'user.domain'};
                   8369:                 my $uname = $env{'user.name'};
                   8370:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   8371:                     $ownaccess = 1;
1.1040    raeburn  8372:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  8373:                     unless ($uri =~ m{\.\./}) {
                   8374:                         $ownaccess = 1;
                   8375:                     }
                   8376:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   8377:                     my $now = time;
                   8378:                     if ($uri =~ m{^([^/]+)/?$}) {
                   8379:                         my $adom = $1;
                   8380:                         foreach my $key (keys(%env)) {
1.1042    raeburn  8381:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1172.2.142  raeburn  8382:                                 my ($start,$end) = split(/\./,$env{$key});
                   8383:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1039    raeburn  8384:                                     $ownaccess = 1;
                   8385:                                     last;
                   8386:                                 }
                   8387:                             }
                   8388:                         }
                   8389:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8390:                         my $adom = $1;
                   8391:                         my $aname = $2;
1.1042    raeburn  8392:                         foreach my $role ('ca','aa') { 
                   8393:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8394:                                 my ($start,$end) =
1.1172.2.142  raeburn  8395:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
                   8396:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1042    raeburn  8397:                                     $ownaccess = 1;
                   8398:                                     last;
                   8399:                                 }
1.1039    raeburn  8400:                             }
                   8401:                         }
                   8402:                     }
                   8403:                 }
                   8404:             }
                   8405:         }
                   8406:     }
                   8407: 
1.52      www      8408: # Course
                   8409: 
1.620     albertel 8410:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8411:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8412:             $thisallowed.=$1;
                   8413:         }
1.52      www      8414:     }
1.29      www      8415: 
1.52      www      8416: # Domain
                   8417: 
1.620     albertel 8418:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8419:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8420:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8421:             $thisallowed.=$1;
                   8422:         }
1.12      www      8423:     }
1.52      www      8424: 
1.1141    raeburn  8425: # User who is not author or co-author might still be able to edit
                   8426: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8427:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8428:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8429:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8430:             $thisallowed.=$1;
                   8431:         }
                   8432:     }
                   8433: 
1.52      www      8434: # Course: uri itself is a course
1.66      www      8435:     my $courseuri=$uri;
                   8436:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8437:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8438: 
1.620     albertel 8439:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8440:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  8441:         if ($priv eq 'mip') {
                   8442:             my $rem = $1;
                   8443:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8444:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8445:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8446:                 if ($cdom ne '') {
                   8447:                     my %passwdconf = &get_passwdconf($cdom);
                   8448:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8449:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8450:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8451:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8452:                                 unless (@inststatuses) {
                   8453:                                     @inststatuses = ('default');
                   8454:                                 }
                   8455:                                 foreach my $status (@inststatuses) {
                   8456:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8457:                                         $thisallowed.=$rem;
                   8458:                                     }
                   8459:                                 }
                   8460:                             }
                   8461:                         }
                   8462:                     }
                   8463:                 }
                   8464:             }
                   8465:         } else {
                   8466:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8467:                 $thisallowed.=$1;
                   8468:             }
1.1039    raeburn  8469:         }
1.12      www      8470:     }
1.29      www      8471: 
1.665     albertel 8472: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8473: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8474:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8475: 	$thisallowed='';
1.671     raeburn  8476:         my ($match)=&is_on_map($uri);
                   8477:         if ($match) {
                   8478:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8479:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  8480:                 my $value = $1;
1.1172.2.146.  .1(raebu 8481:22):                 my $deeplinkblock;
                   8482:22):                 unless ($nodeeplinkcheck) {
                   8483:22):                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8484:22):                 }
                   8485:22):                 if ($deeplinkblock) {
                   8486:22):                     $thisallowed='D';
                   8487:22):                 } elsif ($noblockcheck) {
1.1172.2.65  raeburn  8488:                     $thisallowed.=$value;
1.1162    raeburn  8489:                 } else {
1.1172.2.126  raeburn  8490:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8491:                     if (@blockers > 0) {
                   8492:                         $thisallowed = 'B';
                   8493:                     } else {
                   8494:                         $thisallowed.=$value;
                   8495:                     }
1.1162    raeburn  8496:                 }
1.671     raeburn  8497:             }
                   8498:         } else {
1.705     albertel 8499:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8500:             if ($refuri) {
                   8501:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8502:                     $thisallowed='F';
1.671     raeburn  8503:                 } else {
                   8504:                     $refuri=&declutter($refuri);
                   8505:                     my ($match) = &is_on_map($refuri);
                   8506:                     if ($match) {
1.1172.2.146.  .1(raebu 8507:22):                         my $deeplinkblock;
                   8508:22):                         unless ($nodeeplinkcheck) {
                   8509:22):                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8510:22):                         }
                   8511:22):                         if ($deeplinkblock) {
                   8512:22):                             $thisallowed='D';
                   8513:22):                         } elsif ($noblockcheck) {
1.1162    raeburn  8514:                             $thisallowed='F';
1.1172.2.65  raeburn  8515:                         } else {
1.1172.2.127  raeburn  8516:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8517:                             if (@blockers > 0) {
                   8518:                                 $thisallowed = 'B';
                   8519:                             } else {
                   8520:                                 $thisallowed='F';
                   8521:                             }
1.1162    raeburn  8522:                         }
1.671     raeburn  8523:                     }
1.669     raeburn  8524:                 }
1.671     raeburn  8525:             }
                   8526:         }
1.314     www      8527:     }
1.492     albertel 8528: 
1.766     albertel 8529:     if ($priv eq 'bre'
                   8530: 	&& $thisallowed ne 'F' 
                   8531: 	&& $thisallowed ne '2'
                   8532: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8533: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8534:     }
                   8535:     
1.52      www      8536: # Full access at system, domain or course-wide level? Exit.
1.29      www      8537:     if ($thisallowed=~/F/) {
                   8538: 	return 'F';
                   8539:     }
                   8540: 
1.52      www      8541: # If this is generating or modifying users, exit with special codes
1.29      www      8542: 
1.643     www      8543:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8544: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8545: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8546: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8547: 	    unless ($auname) { return $thisallowed; }
                   8548: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8549: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8550: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8551: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8552: 	}
1.52      www      8553: 	return $thisallowed;
                   8554:     }
                   8555: #
1.103     harris41 8556: # Gathered so far: system, domain and course wide privileges
1.52      www      8557: #
                   8558: # Course: See if uri or referer is an individual resource that is part of 
                   8559: # the course
                   8560: 
1.620     albertel 8561:     if ($env{'request.course.id'}) {
1.232     www      8562: 
1.1172.2.146.  .13(raeb 8563:-23):         if ($priv eq 'bre') {
                   8564:-23):             if (&is_coursetool_logo($uri)) {
                   8565:-23):                 return 'F';
                   8566:-23):             }
                   8567:-23):         }
                   8568:-23): 
1.1172.2.115  raeburn  8569: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8570: 
                   8571:         if ($priv eq 'mip') {
                   8572:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8573:                 return $thisallowed;
                   8574:             } else {
                   8575:                 return '';
                   8576:             }
                   8577:         }
                   8578: 
1.620     albertel 8579:        $courseprivid=$env{'request.course.id'};
                   8580:        if ($env{'request.course.sec'}) {
                   8581:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8582:        }
                   8583:        $courseprivid=~s/\_/\//;
                   8584:        my $checkreferer=1;
1.232     www      8585:        my ($match,$cond)=&is_on_map($uri);
                   8586:        if ($match) {
                   8587:            $statecond=$cond;
1.620     albertel 8588:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8589:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8590:                my $value = $1;
                   8591:                if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8592:22):                    my $deeplinkblock;
                   8593:22):                    unless ($nodeeplinkcheck) {
                   8594:22):                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8595:22):                    }
                   8596:22):                    if ($deeplinkblock) {
                   8597:22):                        $thisallowed = 'D';
                   8598:22):                    } elsif ($noblockcheck) {
1.1162    raeburn  8599:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8600:                    } else {
1.1172.2.126  raeburn  8601:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8602:                        if (@blockers > 0) {
                   8603:                            $thisallowed = 'B';
                   8604:                        } else {
                   8605:                            $thisallowed.=$value;
                   8606:                        }
1.1162    raeburn  8607:                    }
                   8608:                } else {
                   8609:                    $thisallowed.=$value;
                   8610:                }
1.52      www      8611:                $checkreferer=0;
                   8612:            }
1.29      www      8613:        }
1.1172.2.126  raeburn  8614: 
1.148     www      8615:        if ($checkreferer) {
1.620     albertel 8616: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8617:             unless ($refuri) {
1.800     albertel 8618:                 foreach my $key (keys(%env)) {
                   8619: 		    if ($key=~/^httpref\..*\*/) {
                   8620: 			my $pattern=$key;
1.156     www      8621:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8622:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8623:                         $pattern=~s/\//\\\//g;
1.152     www      8624:                         if ($orguri=~/$pattern/) {
1.800     albertel 8625: 			    $refuri=$env{$key};
1.148     www      8626:                         }
                   8627:                     }
1.191     harris41 8628:                 }
1.148     www      8629:             }
1.232     www      8630: 
1.148     www      8631:          if ($refuri) { 
1.152     www      8632: 	  $refuri=&declutter($refuri);
1.232     www      8633:           my ($match,$cond)=&is_on_map($refuri);
                   8634:             if ($match) {
                   8635:               my $refstatecond=$cond;
1.620     albertel 8636:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8637:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8638:                   my $value = $1;
                   8639:                   if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8640:22):                       my $deeplinkblock;
                   8641:22):                       unless ($nodeeplinkcheck) {
                   8642:22):                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8643:22):                       }
                   8644:22):                       if ($deeplinkblock) {
                   8645:22):                           $thisallowed = 'D';
                   8646:22):                       } elsif ($noblockcheck) {
1.1162    raeburn  8647:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8648:                       } else {
1.1172.2.127  raeburn  8649:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8650:                           if (@blockers > 0) {
                   8651:                               $thisallowed = 'B';
                   8652:                           } else {
                   8653:                               $thisallowed.=$value;
                   8654:                           }
1.1162    raeburn  8655:                       }
                   8656:                   } else {
                   8657:                       $thisallowed.=$value;
                   8658:                   }
1.53      www      8659:                   $uri=$refuri;
                   8660:                   $statecond=$refstatecond;
1.52      www      8661:               }
                   8662:           }
1.148     www      8663:         }
1.29      www      8664:        }
1.52      www      8665:    }
1.29      www      8666: 
1.52      www      8667: #
1.103     harris41 8668: # Gathered now: all privileges that could apply, and condition number
1.52      www      8669: # 
                   8670: #
                   8671: # Full or no access?
                   8672: #
1.29      www      8673: 
1.52      www      8674:     if ($thisallowed=~/F/) {
                   8675: 	return 'F';
                   8676:     }
1.29      www      8677: 
1.52      www      8678:     unless ($thisallowed) {
                   8679:         return '';
                   8680:     }
1.29      www      8681: 
1.52      www      8682: # Restrictions exist, deal with them
                   8683: #
                   8684: #   C:according to course preferences
                   8685: #   R:according to resource settings
                   8686: #   L:unless locked
                   8687: #   X:according to user session state
                   8688: #
                   8689: 
                   8690: # Possibly locked functionality, check all courses
1.1172.2.142  raeburn  8691: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54      www      8692: # Locks might take effect only after 10 minutes cache expiration for other
1.1172.2.142  raeburn  8693: # courses, and 2 minutes for current course, in which user has st or ta role
                   8694: # which is neither expired nor a future role (unless current course).
1.52      www      8695: 
1.1172.2.142  raeburn  8696:     my ($needlockcheck,$now,$crsonly);
1.52      www      8697:     if ($thisallowed=~/L/) {
1.1172.2.142  raeburn  8698:         $now = time;
                   8699:         if ($priv eq 'bre') {
                   8700:             if ($uri ne '') {
                   8701:                 if ($orguri =~ m{^/+res/}) {
                   8702:                     if ($uri =~ m{^lib/templates/}) {
                   8703:                         if ($env{'request.course.id'}) {
                   8704:                             $crsonly = 1;
                   8705:                             $needlockcheck = 1;
                   8706:                         }
                   8707:                     } else {
                   8708:                         $needlockcheck = 1;
                   8709:                     }
                   8710:                 } elsif ($env{'request.course.id'}) {
                   8711:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
                   8712:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
                   8713:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
                   8714:                         $crsonly = 1;
                   8715:                     }
                   8716:                     $needlockcheck = 1;
                   8717:                 }
                   8718:             }
                   8719:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
                   8720:             $needlockcheck = 1;
                   8721:         }
                   8722:     }
                   8723:     if ($needlockcheck) {
                   8724:         foreach my $envkey (keys(%env)) {
1.54      www      8725:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8726:                my $courseid=$2;
                   8727:                my $roleid=$1.'.'.$2;
1.92      www      8728:                $courseid=~s/^\///;
1.1172.2.142  raeburn  8729:                unless ($env{'request.role'} eq $roleid) {
                   8730:                    my ($start,$end) = split(/\./,$env{$envkey});
                   8731:                    next unless (($now >= $start) && (!$end || $end > $now));
                   8732:                }
1.54      www      8733:                my $expiretime=600;
1.620     albertel 8734:                if ($env{'request.role'} eq $roleid) {
1.54      www      8735: 		  $expiretime=120;
                   8736:                }
                   8737: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8738:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8739:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8740: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8741:                }
1.620     albertel 8742:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8743:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8744: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8745:                        &log($env{'user.domain'},$env{'user.name'},
                   8746:                             $env{'user.home'},
1.57      www      8747:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8748:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8749:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8750: 		       return '';
                   8751:                    }
                   8752:                }
1.620     albertel 8753:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8754:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1172.2.142  raeburn  8755: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620     albertel 8756:                        &log($env{'user.domain'},$env{'user.name'},
                   8757:                             $env{'user.home'},
1.57      www      8758:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8759:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8760:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8761: 		       return '';
                   8762:                    }
                   8763:                }
                   8764: 	   }
1.29      www      8765:        }
1.52      www      8766:     }
1.1172.2.126  raeburn  8767: 
1.52      www      8768: #
                   8769: # Rest of the restrictions depend on selected course
                   8770: #
                   8771: 
1.620     albertel 8772:     unless ($env{'request.course.id'}) {
1.766     albertel 8773: 	if ($thisallowed eq 'A') {
                   8774: 	    return 'A';
1.814     raeburn  8775:         } elsif ($thisallowed eq 'B') {
                   8776:             return 'B';
1.766     albertel 8777: 	} else {
                   8778: 	    return '1';
                   8779: 	}
1.52      www      8780:     }
1.29      www      8781: 
1.52      www      8782: #
                   8783: # Now user is definitely in a course
                   8784: #
1.53      www      8785: 
                   8786: 
                   8787: # Course preferences
                   8788: 
                   8789:    if ($thisallowed=~/C/) {
1.620     albertel 8790:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8791:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8792:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8793: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8794: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8795: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8796: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8797: 			$env{'request.course.id'});
                   8798: 	   }
1.237     www      8799:            return '';
                   8800:        }
                   8801: 
1.620     albertel 8802:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8803: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8804: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8805: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8806: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8807: 			$env{'request.course.id'});
                   8808: 	   }
1.54      www      8809:            return '';
                   8810:        }
1.53      www      8811:    }
                   8812: 
                   8813: # Resource preferences
                   8814: 
                   8815:    if ($thisallowed=~/R/) {
1.620     albertel 8816:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8817:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8818: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8819: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8820: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8821: 	   }
                   8822: 	   return '';
1.54      www      8823:        }
1.53      www      8824:    }
1.30      www      8825: 
1.1172.2.146.  .1(raebu 8826:22): # Restricted for deeplinked session?
                   8827:22): 
                   8828:22):     if ($env{'request.deeplink.login'}) {
                   8829:22):         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
                   8830:22):             if (!$symb) { $symb=&symbread($uri,1); }
                   8831:22):             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
                   8832:22):                 return '';
                   8833:22):             }
                   8834:22):         }
                   8835:22):     }
                   8836:22): 
1.246     www      8837: # Restricted by state or randomout?
1.30      www      8838: 
1.52      www      8839:    if ($thisallowed=~/X/) {
1.620     albertel 8840:       if ($env{'acc.randomout'}) {
1.579     albertel 8841: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8842:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8843:             return ''; 
                   8844:          }
1.247     www      8845:       }
                   8846:       if (&condval($statecond)) {
1.52      www      8847: 	 return '2';
                   8848:       } else {
                   8849:          return '';
                   8850:       }
                   8851:    }
1.30      www      8852: 
1.766     albertel 8853:     if ($thisallowed eq 'A') {
                   8854: 	return 'A';
1.814     raeburn  8855:     } elsif ($thisallowed eq 'B') {
                   8856:         return 'B';
1.1172.2.146.  .1(raebu 8857:22):     } elsif ($thisallowed eq 'D') {
                   8858:22):         return 'D';
1.766     albertel 8859:     }
1.52      www      8860:    return 'F';
1.232     www      8861: }
1.1162    raeburn  8862: 
1.1172.2.13  raeburn  8863: # ------------------------------------------- Check construction space access
                   8864: 
                   8865: sub constructaccess {
                   8866:     my ($url,$setpriv)=@_;
                   8867: 
                   8868: # We do not allow editing of previous versions of files
                   8869:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8870: 
                   8871: # Get username and domain from URL
                   8872:     my ($ownername,$ownerdomain,$ownerhome);
                   8873: 
                   8874:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8875:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8876: 
                   8877: # The URL does not really point to any authorspace, forget it
                   8878:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8879: 
                   8880: # Now we need to see if the user has access to the authorspace of
                   8881: # $ownername at $ownerdomain
                   8882: 
                   8883:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8884: # Real author for this?
                   8885:        $ownerhome = $env{'user.home'};
                   8886:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8887:           return ($ownername,$ownerdomain,$ownerhome);
                   8888:        }
                   8889:     } else {
                   8890: # Co-author for this?
                   8891:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8892:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8893:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8894:             return ($ownername,$ownerdomain,$ownerhome);
                   8895:         }
                   8896:     }
                   8897: 
                   8898: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8899: # we might as well leave
                   8900:    unless ($setpriv) { return ''; }
                   8901: 
                   8902: # Backdoor access?
                   8903:     my $allowed=&allowed('eco',$ownerdomain);
                   8904: # Nope
                   8905:     unless ($allowed) { return ''; }
                   8906: # Looks like we may have access, but could be locked by the owner of the construction space
                   8907:     if ($allowed eq 'U') {
                   8908:         my %blocked=&get('environment',['domcoord.author'],
                   8909:                          $ownerdomain,$ownername);
                   8910: # Is blocked by owner
                   8911:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8912:     }
                   8913:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8914: # Grant temporary access
                   8915:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8916:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8917:         if (!$update) { $update = $then; }
                   8918:         my $refresh=$env{'user.refresh.time'};
                   8919:         if (!$refresh) { $refresh = $update; }
                   8920:         my $now = time;
                   8921:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8922:                            $now,'ca','constructaccess');
                   8923:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8924:         return($ownername,$ownerdomain,$ownerhome);
                   8925:     }
                   8926: # No business here
                   8927:     return '';
                   8928: }
                   8929: 
1.1172.2.66  raeburn  8930: # ----------------------------------------------------------- Content Blocking
                   8931: 
                   8932: {
                   8933: # Caches for faster Course Contents display where content blocking
                   8934: # is in operation (i.e., interval param set) for timed quiz.
                   8935: #
                   8936: # User for whom data are being temporarily cached.
                   8937: my $cacheduser='';
1.1172.2.126  raeburn  8938: # Course for which data are being temporarily cached.
                   8939: my $cachedcid='';
1.1172.2.66  raeburn  8940: # Cached blockers for this user (a hash of blocking items).
                   8941: my %cachedblockers=();
                   8942: # When the data were last cached.
                   8943: my $cachedlast='';
                   8944: 
                   8945: sub load_all_blockers {
1.1172.2.128  raeburn  8946:     my ($uname,$udom)=@_;
1.1172.2.66  raeburn  8947:     if (($uname ne '') && ($udom ne '')) {
                   8948:         if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126  raeburn  8949:             ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128  raeburn  8950:             (abs($cachedlast-time)<5)) {
1.1172.2.66  raeburn  8951:             return;
                   8952:         }
                   8953:     }
                   8954:     $cachedlast=time;
                   8955:     $cacheduser=$uname.':'.$udom;
1.1172.2.126  raeburn  8956:     $cachedcid=$env{'request.course.id'};
1.1172.2.128  raeburn  8957:     %cachedblockers = &get_commblock_resources();
1.1172.2.126  raeburn  8958:     return;
1.1172.2.66  raeburn  8959: }
                   8960: 
1.1162    raeburn  8961: sub get_comm_blocks {
                   8962:     my ($cdom,$cnum) = @_;
                   8963:     if ($cdom eq '' || $cnum eq '') {
                   8964:         return unless ($env{'request.course.id'});
                   8965:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8966:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8967:     }
                   8968:     my %commblocks;
                   8969:     my $hashid=$cdom.'_'.$cnum;
                   8970:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8971:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8972:         %commblocks = %{$blocksref};
                   8973:     } else {
                   8974:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8975:         my $cachetime = 600;
                   8976:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8977:     }
                   8978:     return %commblocks;
                   8979: }
                   8980: 
1.1172.2.66  raeburn  8981: sub get_commblock_resources {
                   8982:     my ($blocks) = @_;
                   8983:     my %blockers = ();
                   8984:     return %blockers unless ($env{'request.course.id'});
1.1172.2.142  raeburn  8985:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8986:     if ($env{'request.course.sec'}) {
                   8987:         $courseurl .= '/'.$env{'request.course.sec'};
                   8988:     }
                   8989:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162    raeburn  8990:     my %commblocks;
                   8991:     if (ref($blocks) eq 'HASH') {
                   8992:         %commblocks = %{$blocks};
                   8993:     } else {
                   8994:         %commblocks = &get_comm_blocks();
                   8995:     }
1.1172.2.66  raeburn  8996:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8997:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8998:     return %blockers unless (ref($navmap));
                   8999:     my $now = time;
1.1162    raeburn  9000:     foreach my $block (keys(%commblocks)) {
                   9001:         if ($block =~ /^(\d+)____(\d+)$/) {
                   9002:             my ($start,$end) = ($1,$2);
                   9003:             if ($start <= $now && $end >= $now) {
                   9004:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   9005:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   9006:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  9007:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   9008:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  9009:                             }
                   9010:                         }
                   9011:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  9012:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   9013:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  9014:                             }
                   9015:                         }
                   9016:                     }
                   9017:                 }
                   9018:             }
                   9019:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   9020:             my $item = $1;
                   9021:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   9022:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.142  raeburn  9023:                     my (@interval,$mapname);
1.1172.2.66  raeburn  9024:                     my $type = 'map';
                   9025:                     if ($item eq 'course') {
                   9026:                         $type = 'course';
                   9027:                         @interval=&EXT("resource.0.interval");
                   9028:                     } else {
                   9029:                         if ($item =~ /___\d+___/) {
                   9030:                             $type = 'resource';
                   9031:                             @interval=&EXT("resource.0.interval",$item);
1.1162    raeburn  9032:                         } else {
1.1172.2.142  raeburn  9033:                             $mapname = &deversion($item);
                   9034:                             if (ref($navmap)) {
                   9035:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
                   9036:                                 @interval = ($timelimit,'map');
1.1162    raeburn  9037:                             }
                   9038:                         }
1.1172.2.66  raeburn  9039:                     }
1.1172.2.146.  .1(raebu 9040:22):                     if ($interval[0] =~ /^(\d+)/) {
                   9041:22):                         my $timelimit = $1;
1.1172.2.66  raeburn  9042:                         my $first_access;
                   9043:                         if ($type eq 'resource') {
                   9044:                             $first_access=&get_first_access($interval[1],$item);
                   9045:                         } elsif ($type eq 'map') {
                   9046:                             $first_access=&get_first_access($interval[1],undef,$item);
                   9047:                         } else {
                   9048:                             $first_access=&get_first_access($interval[1]);
                   9049:                         }
                   9050:                         if ($first_access) {
1.1172.2.146.  .1(raebu 9051:22):                             my $timesup = $first_access+$timelimit;
1.1172.2.66  raeburn  9052:                             if ($timesup > $now) {
                   9053:                                 my $activeblock;
1.1172.2.142  raeburn  9054:                                 if ($type eq 'resource') {
                   9055:                                     if (ref($navmap)) {
                   9056:                                         my $res = $navmap->getBySymb($item);
                   9057:                                         if ($res->answerable()) {
                   9058:                                             $activeblock = 1;
                   9059:                                         }
                   9060:                                     }
                   9061:                                 } elsif ($type eq 'map') {
                   9062:                                     my $mapsymb = &symbread($mapname,1);
                   9063:                                     if (($mapsymb) && (ref($navmap))) {
                   9064:                                         my $mapres = $navmap->getBySymb($mapsymb);
                   9065:                                         if (ref($mapres)) {
                   9066:                                             my $first = $mapres->map_start();
                   9067:                                             my $finish = $mapres->map_finish();
                   9068:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   9069:                                             if (ref($it)) {
                   9070:                                                 my $res;
                   9071:                                                 while ($res = $it->next(undef,1)) {
                   9072:                                                     next unless (ref($res));
                   9073:                                                     my $symb = $res->symb();
                   9074:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
                   9075:                                                     @interval=&EXT("resource.0.interval",$symb);
                   9076:                                                     if ($interval[1] eq 'map') {
                   9077:                                                         if ($res->answerable()) {
                   9078:                                                             $activeblock = 1;
                   9079:                                                             last;
                   9080:                                                         }
                   9081:                                                     }
                   9082:                                                 }
                   9083:                                             }
                   9084:                                         }
1.1172.2.66  raeburn  9085:                                     }
                   9086:                                 }
                   9087:                                 if ($activeblock) {
                   9088:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   9089:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   9090:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   9091:                                          }
                   9092:                                     }
                   9093:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   9094:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   9095:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  9096:                                         }
1.1162    raeburn  9097:                                     }
                   9098:                                 }
                   9099:                             }
                   9100:                         }
                   9101:                     }
                   9102:                 }
                   9103:             }
                   9104:         }
                   9105:     }
1.1172.2.66  raeburn  9106:     return %blockers;
1.1162    raeburn  9107: }
                   9108: 
1.1172.2.66  raeburn  9109: sub has_comm_blocking {
1.1172.2.128  raeburn  9110:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66  raeburn  9111:     my @blockers;
                   9112:     return unless ($env{'request.course.id'});
                   9113:     return unless ($priv eq 'bre');
                   9114:     return if ($env{'request.state'} eq 'construct');
1.1172.2.142  raeburn  9115:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   9116:     if ($env{'request.course.sec'}) {
                   9117:         $courseurl .= '/'.$env{'request.course.sec'};
                   9118:     }
                   9119:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1172.2.128  raeburn  9120:     my %blockinfo;
                   9121:     if (ref($blocks) eq 'HASH') {
                   9122:         %blockinfo = &get_commblock_resources($blocks);
                   9123:     } else {
                   9124:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   9125:         %blockinfo = %cachedblockers;
                   9126:     }
                   9127:     return unless (keys(%blockinfo) > 0);
1.1172.2.66  raeburn  9128:     my (%possibles,@symbs);
                   9129:     if (!$symb) {
1.1172.2.128  raeburn  9130:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  9131:     }
1.1172.2.66  raeburn  9132:     if ($symb) {
                   9133:         @symbs = ($symb);
                   9134:     } elsif (keys(%possibles)) {
                   9135:         @symbs = keys(%possibles);
                   9136:     }
                   9137:     my $noblock;
                   9138:     foreach my $symb (@symbs) {
                   9139:         last if ($noblock);
                   9140:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128  raeburn  9141:         foreach my $block (keys(%blockinfo)) {
1.1172.2.66  raeburn  9142:             if ($block =~ /^firstaccess____(.+)$/) {
                   9143:                 my $item = $1;
1.1172.2.126  raeburn  9144:                 unless ($blocked) {
                   9145:                     if (($item eq $map) || ($item eq $symb)) {
                   9146:                         $noblock = 1;
                   9147:                         last;
                   9148:                     }
1.1172.2.66  raeburn  9149:                 }
1.1162    raeburn  9150:             }
1.1172.2.128  raeburn  9151:             if (ref($blockinfo{$block}) eq 'HASH') {
                   9152:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   9153:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66  raeburn  9154:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   9155:                             push(@blockers,$block);
                   9156:                         }
                   9157:                     }
                   9158:                 }
1.1172.2.128  raeburn  9159:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   9160:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126  raeburn  9161:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   9162:                             push(@blockers,$block);
                   9163:                         }
1.1172.2.66  raeburn  9164:                     }
                   9165:                 }
1.1162    raeburn  9166:             }
                   9167:         }
                   9168:     }
1.1172.2.126  raeburn  9169:     unless ($noblock) {
                   9170:         return @blockers;
                   9171:     }
                   9172:     return;
1.1172.2.66  raeburn  9173: }
1.1162    raeburn  9174: }
                   9175: 
1.1172.2.146.  .1(raebu 9176:22): sub deeplink_check {
                   9177:22):     my ($priv,$symb,$uri) = @_;
                   9178:22):     return unless ($env{'request.course.id'});
                   9179:22):     return unless ($priv eq 'bre');
                   9180:22):     return if ($env{'request.state'} eq 'construct');
                   9181:22):     return if ($env{'request.role.adv'});
                   9182:22):     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9183:22):     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9184:22):     my (%possibles,@symbs);
                   9185:22):     if (!$symb) {
                   9186:22):         $symb = &symbread($uri,1,1,1,\%possibles);
                   9187:22):     }
                   9188:22):     if ($symb) {
                   9189:22):         @symbs = ($symb);
                   9190:22):     } elsif (keys(%possibles)) {
                   9191:22):         @symbs = keys(%possibles);
                   9192:22):     }
                   9193:22): 
                   9194:22):     my ($deeplink_symb,$allow);
                   9195:22):     if ($env{'request.deeplink.login'}) {
                   9196:22):         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
                   9197:22):     }
                   9198:22):     foreach my $symb (@symbs) {
                   9199:22):         last if ($allow);
                   9200:22):         my $deeplink = &EXT("resource.0.deeplink",$symb);
                   9201:22):         if ($deeplink eq '') {
                   9202:22):             $allow = 1;
                   9203:22):         } else {
                   9204:22):             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
                   9205:22):             if ($state ne 'only') {
                   9206:22):                 $allow = 1;
                   9207:22):             } else {
                   9208:22):                 my $check_deeplink_entry;
                   9209:22):                 if ($protect ne 'none') {
                   9210:22):                     my ($acctype,$item) = split(/:/,$protect);
                   9211:22):                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
                   9212:22):                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
                   9213:22):                             $check_deeplink_entry = 1
                   9214:22):                         }
                   9215:22):                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
                   9216:22):                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
                   9217:22):                             $check_deeplink_entry = 1;
                   9218:22):                         }
                   9219:22):                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
                   9220:22):                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
                   9221:22):                             $check_deeplink_entry = 1;
                   9222:22):                         }
                   9223:22):                     }
                   9224:22):                 }
                   9225:22):                 if (($protect eq 'none') || ($check_deeplink_entry)) {
                   9226:22):                     if ($scope eq 'res') {
                   9227:22):                         if ($symb eq $deeplink_symb) {
                   9228:22):                             $allow = 1;
                   9229:22):                         }
                   9230:22):                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
                   9231:22):                         my ($map_from_symb,$map_from_login);
                   9232:22):                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
                   9233:22):                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9234:22):                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
                   9235:22):                         } else {
                   9236:22):                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
                   9237:22):                         }
                   9238:22):                         if (($map_from_symb) && ($map_from_login)) {
                   9239:22):                             if ($map_from_symb eq $map_from_login) {
                   9240:22):                                 $allow = 1;
                   9241:22):                             } elsif ($scope eq 'rec') {
                   9242:22):                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
                   9243:22):                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
                   9244:22):                                     $allow = 1;
                   9245:22):                                 }
                   9246:22):                             }
                   9247:22):                         }
                   9248:22):                     }
                   9249:22):                 }
                   9250:22):             }
                   9251:22):         }
                   9252:22):     }
                   9253:22):     return if ($allow);
                   9254:22):     return 1;
                   9255:22): }
                   9256:22): 
1.1172.2.66  raeburn  9257: # -------------------------------- Deversion and split uri into path an filename
                   9258: 
1.1133    foxr     9259: #
1.1172.2.66  raeburn  9260: #   Removes the version from a URI and
1.1133    foxr     9261: #   splits it in to its filename and path to the filename.
                   9262: #   Seems like File::Basename could have done this more clearly.
                   9263: #   Parameters:
                   9264: #      $uri   - input URI
                   9265: #   Returns:
                   9266: #     Two element list consisting of 
                   9267: #     $pathname  - the URI up to and excluding the trailing /
                   9268: #     $filename  - The part of the URI following the last /
                   9269: #  NOTE:
                   9270: #    Another realization of this is simply:
                   9271: #    use File::Basename;
                   9272: #    ...
                   9273: #    $uri = shift;
                   9274: #    $filename = basename($uri);
                   9275: #    $path     = dirname($uri);
                   9276: #    return ($filename, $path);
                   9277: #
                   9278: #     The implementation below is probably faster however.
                   9279: #
1.710     albertel 9280: sub split_uri_for_cond {
                   9281:     my $uri=&deversion(&declutter(shift));
                   9282:     my @uriparts=split(/\//,$uri);
                   9283:     my $filename=pop(@uriparts);
                   9284:     my $pathname=join('/',@uriparts);
                   9285:     return ($pathname,$filename);
                   9286: }
1.232     www      9287: # --------------------------------------------------- Is a resource on the map?
                   9288: 
                   9289: sub is_on_map {
1.710     albertel 9290:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 9291:     #Trying to find the conditional for the file
1.620     albertel 9292:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 9293: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      9294:     if ($match) {
1.289     bowersj2 9295: 	return (1,$1);
                   9296:     } else {
1.434     www      9297: 	return (0,0);
1.289     bowersj2 9298:     }
1.12      www      9299: }
                   9300: 
1.427     www      9301: # --------------------------------------------------------- Get symb from alias
                   9302: 
                   9303: sub get_symb_from_alias {
                   9304:     my $symb=shift;
                   9305:     my ($map,$resid,$url)=&decode_symb($symb);
                   9306: # Already is a symb
                   9307:     if ($url) { return $symb; }
                   9308: # Must be an alias
                   9309:     my $aliassymb='';
                   9310:     my %bighash;
1.620     albertel 9311:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      9312:                             &GDBM_READER(),0640)) {
                   9313:         my $rid=$bighash{'mapalias_'.$symb};
                   9314: 	if ($rid) {
                   9315: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 9316: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   9317: 				    $resid,$bighash{'src_'.$rid});
1.427     www      9318: 	}
                   9319:         untie %bighash;
                   9320:     }
                   9321:     return $aliassymb;
                   9322: }
                   9323: 
1.12      www      9324: # ----------------------------------------------------------------- Define Role
                   9325: 
                   9326: sub definerole {
                   9327:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  9328:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 9329:     foreach my $role (split(':',$sysrole)) {
                   9330: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9331:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   9332:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   9333: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9334:                return "refused:s:$crole&$cqual"; 
                   9335:             }
                   9336:         }
1.191     harris41 9337:     }
1.800     albertel 9338:     foreach my $role (split(':',$domrole)) {
                   9339: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9340:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   9341:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   9342: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      9343:                return "refused:d:$crole&$cqual"; 
                   9344:             }
                   9345:         }
1.191     harris41 9346:     }
1.800     albertel 9347:     foreach my $role (split(':',$courole)) {
                   9348: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9349:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   9350:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   9351: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9352:                return "refused:c:$crole&$cqual"; 
                   9353:             }
                   9354:         }
1.191     harris41 9355:     }
1.1172.2.84  raeburn  9356:     my $uhome;
                   9357:     if (($uname ne '') && ($udom ne '')) {
                   9358:         $uhome = &homeserver($uname,$udom);
                   9359:         return $uhome if ($uhome eq 'no_host');
                   9360:     } else {
                   9361:         $uname = $env{'user.name'};
                   9362:         $udom = $env{'user.domain'};
                   9363:         $uhome = $env{'user.home'};
                   9364:     }
1.620     albertel 9365:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  9366:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      9367:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  9368:     return reply($command,$uhome);
1.12      www      9369:   } else {
                   9370:     return 'refused';
                   9371:   }
1.105     harris41 9372: }
                   9373: 
                   9374: # ---------------- Make a metadata query against the network of library servers
                   9375: 
                   9376: sub metadata_query {
1.1172.2.33  raeburn  9377:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 9378:     my %rhash;
1.845     albertel 9379:     my %libserv = &all_library();
1.244     matthew  9380:     my @server_list = (defined($server_array) ? @$server_array
                   9381:                                               : keys(%libserv) );
                   9382:     for my $server (@server_list) {
1.1172.2.33  raeburn  9383:         my $domains = '';
                   9384:         if (ref($domains_hash) eq 'HASH') {
                   9385:             $domains = $domains_hash->{$server};    
                   9386:         }
1.118     harris41 9387: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  9388: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 9389: 	    $rhash{$server}=$reply;
                   9390: 	}
                   9391: 	else {
                   9392: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  9393: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 9394: 			     $server);
                   9395: 	    $rhash{$server}=$reply;
                   9396: 	}
1.112     harris41 9397:     }
1.118     harris41 9398:     return \%rhash;
1.240     www      9399: }
                   9400: 
                   9401: # ----------------------------------------- Send log queries and wait for reply
                   9402: 
                   9403: sub log_query {
                   9404:     my ($uname,$udom,$query,%filters)=@_;
                   9405:     my $uhome=&homeserver($uname,$udom);
                   9406:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 9407:     my $uhost=&hostname($uhome);
1.800     albertel 9408:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      9409:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   9410:                        $uhome);
1.479     albertel 9411:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      9412:     return get_query_reply($queryid);
                   9413: }
                   9414: 
1.818     raeburn  9415: # -------------------------- Update MySQL table for portfolio file
                   9416: 
                   9417: sub update_portfolio_table {
1.821     raeburn  9418:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  9419:     if ($group ne '') {
                   9420:         $file_name =~s /^\Q$group\E//;
                   9421:     }
1.818     raeburn  9422:     my $homeserver = &homeserver($uname,$udom);
                   9423:     my $queryid=
1.821     raeburn  9424:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   9425:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  9426:     my $reply = &get_query_reply($queryid);
                   9427:     return $reply;
                   9428: }
                   9429: 
1.899     raeburn  9430: # -------------------------- Update MySQL allusers table
                   9431: 
                   9432: sub update_allusers_table {
                   9433:     my ($uname,$udom,$names) = @_;
                   9434:     my $homeserver = &homeserver($uname,$udom);
                   9435:     my $queryid=
                   9436:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   9437:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   9438:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   9439:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   9440:                'generation='.&escape($names->{'generation'}).'%%'.
                   9441:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   9442:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  9443:     return;
1.899     raeburn  9444: }
                   9445: 
1.508     raeburn  9446: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  9447: 
                   9448: sub fetch_enrollment_query {
1.511     raeburn  9449:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  9450:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  9451:     my $maxtries = 1;
1.508     raeburn  9452:     if ($context eq 'automated') {
                   9453:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  9454:         $sleep = 2;
                   9455:         $loopmax = 100;
1.547     raeburn  9456:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  9457:     } else {
                   9458:         $homeserver = &homeserver($cnum,$dom);
                   9459:     }
1.838     albertel 9460:     my $host=&hostname($homeserver);
1.506     raeburn  9461:     my $cmd = '';
1.1000    raeburn  9462:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 9463:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  9464:     }
                   9465:     $cmd =~ s/%%$//;
                   9466:     $cmd = &escape($cmd);
                   9467:     my $query = 'fetchenrollment';
1.620     albertel 9468:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  9469:     unless ($queryid=~/^\Q$host\E\_/) { 
                   9470:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   9471:         return 'error: '.$queryid;
                   9472:     }
1.1172.2.93  raeburn  9473:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9474:     my $tries = 1;
                   9475:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  9476:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9477:         $tries ++;
                   9478:     }
1.526     raeburn  9479:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 9480:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  9481:     } else {
1.901     albertel 9482:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  9483:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 9484:             foreach my $line (@responses) {
                   9485:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  9486:                 $$replyref{$key} = $value;
                   9487:             }
                   9488:         } else {
1.1117    foxr     9489:             my $pathname = LONCAPA::tempdir();
1.800     albertel 9490:             foreach my $line (@responses) {
                   9491:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  9492:                 $$replyref{$key} = $value;
                   9493:                 if ($value > 0) {
1.800     albertel 9494:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   9495:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  9496:                         my $destname = $pathname.'/'.$filename;
                   9497:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  9498:                         if ($xml_classlist =~ /^error/) {
                   9499:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   9500:                         } else {
1.1172.2.96  raeburn  9501:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  9502:                                 print FILE &unescape($xml_classlist);
                   9503:                                 close(FILE);
1.526     raeburn  9504:                             } else {
                   9505:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  9506:                             }
                   9507:                         }
                   9508:                     }
                   9509:                 }
                   9510:             }
                   9511:         }
                   9512:         return 'ok';
                   9513:     }
                   9514:     return 'error';
                   9515: }
                   9516: 
1.242     www      9517: sub get_query_reply {
1.1172.2.79  raeburn  9518:     my ($queryid,$sleep,$loopmax) = @_;
                   9519:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9520:         $sleep = 0.2;
                   9521:     }
                   9522:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9523:         $loopmax = 100;
                   9524:     }
1.1117    foxr     9525:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9526:     my $reply='';
1.1172.2.79  raeburn  9527:     for (1..$loopmax) {
                   9528: 	sleep($sleep);
1.240     www      9529:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  9530: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9531: 		$reply = join('',<$fh>);
                   9532: 		close($fh);
1.240     www      9533: 	   } else { return 'error: reply_file_error'; }
1.242     www      9534:            return &unescape($reply);
                   9535: 	}
1.240     www      9536:     }
1.242     www      9537:     return 'timeout:'.$queryid;
1.240     www      9538: }
                   9539: 
                   9540: sub courselog_query {
1.241     www      9541: #
                   9542: # possible filters:
                   9543: # url: url or symb
                   9544: # username
                   9545: # domain
                   9546: # action: view, submit, grade
                   9547: # start: timestamp
                   9548: # end: timestamp
                   9549: #
1.240     www      9550:     my (%filters)=@_;
1.620     albertel 9551:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9552:     if ($filters{'url'}) {
                   9553: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9554:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9555:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9556:     }
1.620     albertel 9557:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9558:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9559:     return &log_query($cname,$cdom,'courselog',%filters);
                   9560: }
                   9561: 
                   9562: sub userlog_query {
1.858     raeburn  9563: #
                   9564: # possible filters:
                   9565: # action: log check role
                   9566: # start: timestamp
                   9567: # end: timestamp
                   9568: #
1.240     www      9569:     my ($uname,$udom,%filters)=@_;
                   9570:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9571: }
                   9572: 
1.506     raeburn  9573: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9574: 
                   9575: sub auto_run {
1.508     raeburn  9576:     my ($cnum,$cdom) = @_;
1.876     raeburn  9577:     my $response = 0;
                   9578:     my $settings;
                   9579:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9580:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9581:         $settings = $domconfig{'autoenroll'};
                   9582:         if ($settings->{'run'} eq '1') {
                   9583:             $response = 1;
                   9584:         }
                   9585:     } else {
1.934     raeburn  9586:         my $homeserver;
                   9587:         if (&is_course($cdom,$cnum)) {
                   9588:             $homeserver = &homeserver($cnum,$cdom);
                   9589:         } else {
                   9590:             $homeserver = &domain($cdom,'primary');
                   9591:         }
                   9592:         if ($homeserver ne 'no_host') {
                   9593:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9594:         }
1.876     raeburn  9595:     }
1.506     raeburn  9596:     return $response;
                   9597: }
1.776     albertel 9598: 
1.506     raeburn  9599: sub auto_get_sections {
1.508     raeburn  9600:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9601:     my $homeserver;
                   9602:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9603:         $homeserver = &homeserver($cnum,$cdom);
                   9604:     }
                   9605:     if (!defined($homeserver)) { 
                   9606:         if ($cdom =~ /^$match_domain$/) {
                   9607:             $homeserver = &domain($cdom,'primary');
                   9608:         }
                   9609:     }
                   9610:     my @secs;
                   9611:     if (defined($homeserver)) {
                   9612:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9613:         unless ($response eq 'refused') {
                   9614:             @secs = split(/:/,$response);
                   9615:         }
1.506     raeburn  9616:     }
                   9617:     return @secs;
                   9618: }
1.776     albertel 9619: 
1.506     raeburn  9620: sub auto_new_course {
1.1099    raeburn  9621:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9622:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9623:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9624:     return $response;
                   9625: }
1.776     albertel 9626: 
1.506     raeburn  9627: sub auto_validate_courseID {
1.508     raeburn  9628:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9629:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9630:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9631:     return $response;
                   9632: }
1.776     albertel 9633: 
1.1007    raeburn  9634: sub auto_validate_instcode {
1.1020    raeburn  9635:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9636:     my ($homeserver,$response);
                   9637:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9638:         $homeserver = &homeserver($cnum,$cdom);
                   9639:     }
                   9640:     if (!defined($homeserver)) {
                   9641:         if ($cdom =~ /^$match_domain$/) {
                   9642:             $homeserver = &domain($cdom,'primary');
                   9643:         }
                   9644:     }
1.1065    raeburn  9645:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9646:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  9647:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9648:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9649: }
                   9650: 
1.1172.2.141  raeburn  9651: sub auto_validate_inst_crosslist {
                   9652:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
                   9653:     my ($homeserver,$response);
                   9654:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9655:         $homeserver = &homeserver($cnum,$cdom);
                   9656:     }
                   9657:     if (!defined($homeserver)) {
                   9658:         if ($cdom =~ /^$match_domain$/) {
                   9659:             $homeserver = &domain($cdom,'primary');
                   9660:         }
                   9661:     }
                   9662:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
                   9663:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
                   9664:                          &escape($instcode).':'.&escape($inst_xlist).':'.
                   9665:                          &escape($coowner),$homeserver);
                   9666:     }
                   9667:     return $response;
                   9668: }
                   9669: 
1.506     raeburn  9670: sub auto_create_password {
1.873     raeburn  9671:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9672:     my ($homeserver,$response);
1.506     raeburn  9673:     my $create_passwd = 0;
                   9674:     my $authchk = '';
1.873     raeburn  9675:     if ($udom =~ /^$match_domain$/) {
                   9676:         $homeserver = &domain($udom,'primary');
                   9677:     }
                   9678:     if ($homeserver eq '') {
                   9679:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9680:             $homeserver = &homeserver($cnum,$cdom);
                   9681:         }
                   9682:     }
                   9683:     if ($homeserver eq '') {
                   9684:         $authchk = 'nodomain';
1.506     raeburn  9685:     } else {
1.873     raeburn  9686:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9687:         if ($response eq 'refused') {
                   9688:             $authchk = 'refused';
                   9689:         } else {
1.901     albertel 9690:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9691:         }
1.506     raeburn  9692:     }
                   9693:     return ($authparam,$create_passwd,$authchk);
                   9694: }
                   9695: 
1.706     raeburn  9696: sub auto_photo_permission {
                   9697:     my ($cnum,$cdom,$students) = @_;
                   9698:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9699:     my ($outcome,$perm_reqd,$conditions) = 
                   9700: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9701:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9702: 	return (undef,undef);
                   9703:     }
1.706     raeburn  9704:     return ($outcome,$perm_reqd,$conditions);
                   9705: }
                   9706: 
                   9707: sub auto_checkphotos {
                   9708:     my ($uname,$udom,$pid) = @_;
                   9709:     my $homeserver = &homeserver($uname,$udom);
                   9710:     my ($result,$resulttype);
                   9711:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9712: 				   &escape($uname).':'.&escape($pid),
                   9713: 				   $homeserver));
1.709     albertel 9714:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9715: 	return (undef,undef);
                   9716:     }
1.706     raeburn  9717:     if ($outcome) {
                   9718:         ($result,$resulttype) = split(/:/,$outcome);
                   9719:     } 
                   9720:     return ($result,$resulttype);
                   9721: }
                   9722: 
                   9723: sub auto_photochoice {
                   9724:     my ($cnum,$cdom) = @_;
                   9725:     my $homeserver = &homeserver($cnum,$cdom);
                   9726:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9727: 						       &escape($cdom),
                   9728: 						       $homeserver)));
1.709     albertel 9729:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9730: 	return (undef,undef);
                   9731:     }
1.706     raeburn  9732:     return ($update,$comment);
                   9733: }
                   9734: 
                   9735: sub auto_photoupdate {
                   9736:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9737:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9738:     my $host=&hostname($homeserver);
1.706     raeburn  9739:     my $cmd = '';
                   9740:     my $maxtries = 1;
1.800     albertel 9741:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9742:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9743:     }
                   9744:     $cmd =~ s/%%$//;
                   9745:     $cmd = &escape($cmd);
                   9746:     my $query = 'institutionalphotos';
                   9747:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9748:     unless ($queryid=~/^\Q$host\E\_/) {
                   9749:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9750:         return 'error: '.$queryid;
                   9751:     }
                   9752:     my $reply = &get_query_reply($queryid);
                   9753:     my $tries = 1;
                   9754:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9755:         $reply = &get_query_reply($queryid);
                   9756:         $tries ++;
                   9757:     }
                   9758:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9759:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9760:     } else {
                   9761:         my @responses = split(/:/,$reply);
                   9762:         my $outcome = shift(@responses); 
                   9763:         foreach my $item (@responses) {
                   9764:             my ($key,$value) = split(/=/,$item);
                   9765:             $$photo{$key} = $value;
                   9766:         }
                   9767:         return $outcome;
                   9768:     }
                   9769:     return 'error';
                   9770: }
                   9771: 
1.521     raeburn  9772: sub auto_instcode_format {
1.793     albertel 9773:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9774: 	$cat_order) = @_;
1.521     raeburn  9775:     my $courses = '';
1.772     raeburn  9776:     my @homeservers;
1.521     raeburn  9777:     if ($caller eq 'global') {
1.841     albertel 9778: 	my %servers = &get_servers($codedom,'library');
                   9779: 	foreach my $tryserver (keys(%servers)) {
                   9780: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9781: 		push(@homeservers,$tryserver);
                   9782: 	    }
1.584     raeburn  9783:         }
1.1022    raeburn  9784:     } elsif ($caller eq 'requests') {
                   9785:         if ($codedom =~ /^$match_domain$/) {
                   9786:             my $chome = &domain($codedom,'primary');
                   9787:             unless ($chome eq 'no_host') {
                   9788:                 push(@homeservers,$chome);
                   9789:             }
                   9790:         }
1.521     raeburn  9791:     } else {
1.772     raeburn  9792:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9793:     }
1.793     albertel 9794:     foreach my $code (keys(%{$instcodes})) {
                   9795:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9796:     }
                   9797:     chop($courses);
1.772     raeburn  9798:     my $ok_response = 0;
                   9799:     my $response;
                   9800:     while (@homeservers > 0 && $ok_response == 0) {
                   9801:         my $server = shift(@homeservers); 
                   9802:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9803:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9804:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9805: 		split(/:/,$response);
1.772     raeburn  9806:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9807:             push(@{$codetitles},&str2array($codetitles_str));
                   9808:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9809:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9810:             $ok_response = 1;
                   9811:         }
                   9812:     }
                   9813:     if ($ok_response) {
1.521     raeburn  9814:         return 'ok';
1.772     raeburn  9815:     } else {
                   9816:         return $response;
1.521     raeburn  9817:     }
                   9818: }
                   9819: 
1.792     raeburn  9820: sub auto_instcode_defaults {
                   9821:     my ($domain,$returnhash,$code_order) = @_;
                   9822:     my @homeservers;
1.841     albertel 9823: 
                   9824:     my %servers = &get_servers($domain,'library');
                   9825:     foreach my $tryserver (keys(%servers)) {
                   9826: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9827: 	    push(@homeservers,$tryserver);
                   9828: 	}
1.792     raeburn  9829:     }
1.841     albertel 9830: 
1.792     raeburn  9831:     my $response;
1.841     albertel 9832:     foreach my $server (@homeservers) {
1.792     raeburn  9833:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9834:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9835: 	
                   9836: 	foreach my $pair (split(/\&/,$response)) {
                   9837: 	    my ($name,$value)=split(/\=/,$pair);
                   9838: 	    if ($name eq 'code_order') {
                   9839: 		@{$code_order} = split(/\&/,&unescape($value));
                   9840: 	    } else {
                   9841: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9842: 	    }
                   9843: 	}
                   9844: 	return 'ok';
1.792     raeburn  9845:     }
1.841     albertel 9846: 
                   9847:     return $response;
1.1003    raeburn  9848: }
                   9849: 
                   9850: sub auto_possible_instcodes {
1.1007    raeburn  9851:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9852:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9853:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9854:         return;
                   9855:     }
1.1003    raeburn  9856:     my (@homeservers,$uhome);
                   9857:     if (defined(&domain($domain,'primary'))) {
                   9858:         $uhome=&domain($domain,'primary');
                   9859:         push(@homeservers,&domain($domain,'primary'));
                   9860:     } else {
                   9861:         my %servers = &get_servers($domain,'library');
                   9862:         foreach my $tryserver (keys(%servers)) {
                   9863:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9864:                 push(@homeservers,$tryserver);
                   9865:             }
                   9866:         }
                   9867:     }
                   9868:     my $response;
                   9869:     foreach my $server (@homeservers) {
                   9870:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9871:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9872:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9873:             split(':',$response);
                   9874:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9875:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9876:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9877:             my ($name,$value)=split('=',$item);
                   9878:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9879:         }
                   9880:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9881:             my ($name,$value)=split('=',$item);
                   9882:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9883:         }
                   9884:         return 'ok';
                   9885:     }
                   9886:     return $response;
                   9887: }
1.792     raeburn  9888: 
1.1010    raeburn  9889: sub auto_courserequest_checks {
                   9890:     my ($dom) = @_;
1.1020    raeburn  9891:     my ($homeserver,%validations);
                   9892:     if ($dom =~ /^$match_domain$/) {
                   9893:         $homeserver = &domain($dom,'primary');
                   9894:     }
                   9895:     unless ($homeserver eq 'no_host') {
                   9896:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9897:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9898:             my @items = split(/&/,$response);
                   9899:             foreach my $item (@items) {
                   9900:                 my ($key,$value) = split('=',$item);
                   9901:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9902:             }
                   9903:         }
                   9904:     }
1.1010    raeburn  9905:     return %validations; 
                   9906: }
                   9907: 
1.1020    raeburn  9908: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9909:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9910:     my ($homeserver,$response);
                   9911:     if ($dom =~ /^$match_domain$/) {
                   9912:         $homeserver = &domain($dom,'primary');
                   9913:     }
1.1172.2.43  raeburn  9914:     unless ($homeserver eq 'no_host') {
                   9915:         my $customdata;
                   9916:         if (ref($custominfo) eq 'HASH') {
                   9917:             $customdata = &freeze_escape($custominfo);
                   9918:         }
1.1020    raeburn  9919:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9920:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9921:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9922:                                     $customdata,$homeserver));
1.1020    raeburn  9923:     }
                   9924:     return $response;
                   9925: }
                   9926: 
1.777     albertel 9927: sub auto_validate_class_sec {
1.918     raeburn  9928:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9929:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9930:     my $ownerlist;
                   9931:     if (ref($owners) eq 'ARRAY') {
                   9932:         $ownerlist = join(',',@{$owners});
                   9933:     } else {
                   9934:         $ownerlist = $owners;
                   9935:     }
1.773     raeburn  9936:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9937:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9938:     return $response;
                   9939: }
                   9940: 
1.1172.2.141  raeburn  9941: sub auto_instsec_reformat {
                   9942:     my ($cdom,$action,$instsecref) = @_;
                   9943:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
                   9944:     my @homeservers;
                   9945:     if (defined(&domain($cdom,'primary'))) {
                   9946:         push(@homeservers,&domain($cdom,'primary'));
                   9947:     } else {
                   9948:         my %servers = &get_servers($cdom,'library');
                   9949:         foreach my $tryserver (keys(%servers)) {
                   9950:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9951:                 push(@homeservers,$tryserver);
                   9952:             }
                   9953:         }
                   9954:     }
                   9955:     my $response;
                   9956:     my %reformatted = %{$instsecref};
                   9957:     foreach my $server (@homeservers) {
                   9958:         if (ref($instsecref) eq 'HASH') {
                   9959:             my $info = &freeze_escape($instsecref);
                   9960:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
                   9961:                                 $action.':'.$info,$server);
                   9962:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
                   9963:             my @items = split(/&/,$response);
                   9964:             foreach my $item (@items) {
                   9965:                 my ($key,$value) = split(/=/,$item);
                   9966:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
                   9967:             }
                   9968:         }
                   9969:     }
                   9970:     return %reformatted;
                   9971: }
                   9972: 
1.1172.2.94  raeburn  9973: sub auto_validate_instclasses {
                   9974:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9975:     my ($homeserver,%validations);
                   9976:     $homeserver = &homeserver($cnum,$cdom);
                   9977:     unless ($homeserver eq 'no_host') {
                   9978:         my $ownerlist;
                   9979:         if (ref($owners) eq 'ARRAY') {
                   9980:             $ownerlist = join(',',@{$owners});
                   9981:         } else {
                   9982:             $ownerlist = $owners;
                   9983:         }
                   9984:         if (ref($classesref) eq 'HASH') {
                   9985:             my $classes = &freeze_escape($classesref);
                   9986:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9987:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9988:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9989:                 my @items = split(/&/,$response);
                   9990:                 foreach my $item (@items) {
                   9991:                     my ($key,$value) = split('=',$item);
                   9992:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9993:                 }
                   9994:             }
                   9995:         }
                   9996:     }
                   9997:     return %validations;
                   9998: }
                   9999: 
1.1172.2.38  raeburn  10000: sub auto_crsreq_update {
                   10001:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  10002:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  10003:     my ($homeserver,%crsreqresponse);
                   10004:     if ($cdom =~ /^$match_domain$/) {
                   10005:         $homeserver = &domain($cdom,'primary');
                   10006:     }
                   10007:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   10008:         my $info;
                   10009:         if (ref($inbound) eq 'HASH') {
                   10010:             $info = &freeze_escape($inbound);
                   10011:         }
                   10012:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   10013:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   10014:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  10015:                             &escape($title).':'.&escape($code).':'.
                   10016:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  10017:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   10018:             my @items = split(/&/,$response);
                   10019:             foreach my $item (@items) {
                   10020:                 my ($key,$value) = split('=',$item);
                   10021:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   10022:             }
                   10023:         }
                   10024:     }
                   10025:     return \%crsreqresponse;
                   10026: }
                   10027: 
1.1172.2.78  raeburn  10028: sub auto_export_grades {
                   10029:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   10030:     my ($homeserver,%exportresponse);
                   10031:     if ($cdom =~ /^$match_domain$/) {
                   10032:         $homeserver = &domain($cdom,'primary');
                   10033:     }
                   10034:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   10035:         my $info;
                   10036:         if (ref($inforef) eq 'HASH') {
                   10037:             $info = &freeze_escape($inforef);
                   10038:         }
                   10039:         if (ref($gradesref) eq 'HASH') {
                   10040:             my $grades = &freeze_escape($gradesref);
                   10041:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   10042:                                 $info.':'.$grades,$homeserver);
                   10043:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   10044:                 my @items = split(/&/,$response);
                   10045:                 foreach my $item (@items) {
                   10046:                     my ($key,$value) = split('=',$item);
                   10047:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   10048:                 }
                   10049:             }
                   10050:         }
                   10051:     }
                   10052:     return \%exportresponse;
                   10053: }
                   10054: 
1.1172.2.68  raeburn  10055: sub check_instcode_cloning {
                   10056:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   10057:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   10058:         return;
                   10059:     }
                   10060:     my $canclone;
                   10061:     if (@{$code_order} > 0) {
                   10062:         my $instcoderegexp ='^';
                   10063:         my @clonecodes = split(/\&/,$cloner);
                   10064:         foreach my $item (@{$code_order}) {
                   10065:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   10066:                 foreach my $pair (@clonecodes) {
                   10067:                     my ($key,$val) = split(/\=/,$pair,2);
                   10068:                     $val = &unescape($val);
                   10069:                     if ($key eq $item) {
                   10070:                         $instcoderegexp .= '('.$val.')';
                   10071:                         last;
                   10072:                     }
                   10073:                 }
                   10074:             } else {
                   10075:                 $instcoderegexp .= $codedefaults->{$item};
                   10076:             }
                   10077:         }
                   10078:         $instcoderegexp .= '$';
                   10079:         my (@from,@to);
                   10080:         eval {
                   10081:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   10082:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   10083:         };
                   10084:         if ((@from > 0) && (@to > 0)) {
                   10085:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   10086:             if (!@diffs) {
                   10087:                 $canclone = 1;
                   10088:             }
                   10089:         }
                   10090:     }
                   10091:     return $canclone;
                   10092: }
                   10093: 
                   10094: sub default_instcode_cloning {
                   10095:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   10096:     my (%codedefaults,@code_order,$canclone);
                   10097:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   10098:         %codedefaults = %{$codedefaultsref};
                   10099:         @code_order = @{$codeorderref};
                   10100:     } elsif ($clonedom) {
                   10101:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   10102:     }
                   10103:     if (($domdefclone) && (@code_order)) {
                   10104:         my @clonecodes = split(/\+/,$domdefclone);
                   10105:         my $instcoderegexp ='^';
                   10106:         foreach my $item (@code_order) {
                   10107:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   10108:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   10109:             } else {
                   10110:                 $instcoderegexp .= $codedefaults{$item};
                   10111:             }
                   10112:         }
                   10113:         $instcoderegexp .= '$';
                   10114:         my (@from,@to);
                   10115:         eval {
                   10116:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   10117:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   10118:         };
                   10119:         if ((@from > 0) && (@to > 0)) {
                   10120:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   10121:             if (!@diffs) {
                   10122:                 $canclone = 1;
                   10123:             }
                   10124:         }
                   10125:     }
                   10126:     return $canclone;
                   10127: }
                   10128: 
1.679     raeburn  10129: # ------------------------------------------------------- Course Group routines
                   10130: 
                   10131: sub get_coursegroups {
1.809     raeburn  10132:     my ($cdom,$cnum,$group,$namespace) = @_;
                   10133:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  10134: }
                   10135: 
1.679     raeburn  10136: sub modify_coursegroup {
                   10137:     my ($cdom,$cnum,$groupsettings) = @_;
                   10138:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   10139: }
                   10140: 
1.809     raeburn  10141: sub toggle_coursegroup_status {
                   10142:     my ($cdom,$cnum,$group,$action) = @_;
                   10143:     my ($from_namespace,$to_namespace);
                   10144:     if ($action eq 'delete') {
                   10145:         $from_namespace = 'coursegroups';
                   10146:         $to_namespace = 'deleted_groups';
                   10147:     } else {
                   10148:         $from_namespace = 'deleted_groups';
                   10149:         $to_namespace = 'coursegroups';
                   10150:     }
                   10151:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  10152:     if (my $tmp = &error(%curr_group)) {
                   10153:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   10154:         return ('read error',$tmp);
                   10155:     } else {
                   10156:         my %savedsettings = %curr_group; 
1.809     raeburn  10157:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  10158:         my $deloutcome;
                   10159:         if ($result eq 'ok') {
1.809     raeburn  10160:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  10161:         } else {
                   10162:             return ('write error',$result);
                   10163:         }
                   10164:         if ($deloutcome eq 'ok') {
                   10165:             return 'ok';
                   10166:         } else {
                   10167:             return ('delete error',$deloutcome);
                   10168:         }
                   10169:     }
                   10170: }
                   10171: 
1.679     raeburn  10172: sub modify_group_roles {
1.957     raeburn  10173:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  10174:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   10175:     my $role = 'gr/'.&escape($userprivs);
                   10176:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  10177:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  10178:     if ($result eq 'ok') {
                   10179:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   10180:     }
1.679     raeburn  10181:     return $result;
                   10182: }
                   10183: 
                   10184: sub modify_coursegroup_membership {
                   10185:     my ($cdom,$cnum,$membership) = @_;
                   10186:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   10187:     return $result;
                   10188: }
                   10189: 
1.682     raeburn  10190: sub get_active_groups {
                   10191:     my ($udom,$uname,$cdom,$cnum) = @_;
                   10192:     my $now = time;
                   10193:     my %groups = ();
                   10194:     foreach my $key (keys(%env)) {
1.811     albertel 10195:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  10196:             my ($start,$end) = split(/\./,$env{$key});
                   10197:             if (($end!=0) && ($end<$now)) { next; }
                   10198:             if (($start!=0) && ($start>$now)) { next; }
                   10199:             if ($1 eq $cdom && $2 eq $cnum) {
                   10200:                 $groups{$3} = $env{$key} ;
                   10201:             }
                   10202:         }
                   10203:     }
                   10204:     return %groups;
                   10205: }
                   10206: 
1.683     raeburn  10207: sub get_group_membership {
                   10208:     my ($cdom,$cnum,$group) = @_;
                   10209:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   10210: }
                   10211: 
                   10212: sub get_users_groups {
                   10213:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  10214:     my @usersgroups;
1.683     raeburn  10215:     my $cachetime=1800;
                   10216: 
                   10217:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  10218:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   10219:     if (defined($cached)) {
1.734     albertel 10220:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  10221:     } else {  
                   10222:         $grouplist = '';
1.816     raeburn  10223:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  10224:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  10225:         my $access_end = $env{'course.'.$courseid.
                   10226:                               '.default_enrollment_end_date'};
                   10227:         my $now = time;
                   10228:         foreach my $key (keys(%roleshash)) {
                   10229:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   10230:                 my $group = $1;
                   10231:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   10232:                     my $start = $2;
                   10233:                     my $end = $1;
                   10234:                     if ($start == -1) { next; } # deleted from group
                   10235:                     if (($start!=0) && ($start>$now)) { next; }
                   10236:                     if (($end!=0) && ($end<$now)) {
                   10237:                         if ($access_end && $access_end < $now) {
                   10238:                             if ($access_end - $end < 86400) {
                   10239:                                 push(@usersgroups,$group);
1.733     raeburn  10240:                             }
                   10241:                         }
1.817     raeburn  10242:                         next;
1.733     raeburn  10243:                     }
1.817     raeburn  10244:                     push(@usersgroups,$group);
1.683     raeburn  10245:                 }
                   10246:             }
                   10247:         }
1.817     raeburn  10248:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   10249:         $grouplist = join(':',@usersgroups);
                   10250:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  10251:     }
1.733     raeburn  10252:     return @usersgroups;
1.683     raeburn  10253: }
                   10254: 
                   10255: sub devalidate_getgroups_cache {
                   10256:     my ($udom,$uname,$cdom,$cnum)=@_;
                   10257:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 10258: 
1.683     raeburn  10259:     my $hashid="$udom:$uname:$courseid";
                   10260:     &devalidate_cache_new('getgroups',$hashid);
                   10261: }
                   10262: 
1.12      www      10263: # ------------------------------------------------------------------ Plain Text
                   10264: 
                   10265: sub plaintext {
1.988     raeburn  10266:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  10267:     if ($short =~ m{^cr/}) {
1.758     albertel 10268: 	return (split('/',$short))[-1];
                   10269:     }
1.742     raeburn  10270:     if (!defined($cid)) {
                   10271:         $cid = $env{'request.course.id'};
                   10272:     }
                   10273:     my %rolenames = (
1.1008    raeburn  10274:                       Course    => 'std',
                   10275:                       Community => 'alt1',
1.742     raeburn  10276:                     );
1.1037    raeburn  10277:     if ($cid ne '') {
                   10278:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   10279:             unless ($forcedefault) {
                   10280:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   10281:                 &Apache::lonlocal::mt_escape(\$roletext);
                   10282:                 return &Apache::lonlocal::mt($roletext);
                   10283:             }
                   10284:         }
                   10285:     }
                   10286:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   10287:         (defined($rolenames{$type})) && 
                   10288:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  10289:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  10290:     } elsif ($cid ne '') {
                   10291:         my $crstype = $env{'course.'.$cid.'.type'};
                   10292:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   10293:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   10294:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   10295:         }
1.742     raeburn  10296:     }
1.1037    raeburn  10297:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      10298: }
                   10299: 
                   10300: # ----------------------------------------------------------------- Assign Role
                   10301: 
                   10302: sub assignrole {
1.957     raeburn  10303:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   10304:         $context)=@_;
1.21      www      10305:     my $mrole;
                   10306:     if ($role =~ /^cr\//) {
1.393     www      10307:         my $cwosec=$url;
1.811     albertel 10308:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      10309: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  10310:            my $refused = 1;
                   10311:            if ($context eq 'requestcourses') {
                   10312:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   10313:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   10314:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   10315:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10316:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10317:                            if ($crsenv{'internal.courseowner'} eq
                   10318:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   10319:                                $refused = '';
                   10320:                            }
                   10321:                        }
                   10322:                    }
                   10323:                }
                   10324:            }
                   10325:            if ($refused) {
                   10326:                &logthis('Refused custom assignrole: '.
                   10327:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   10328:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   10329:                return 'refused';
                   10330:            }
1.104     www      10331:         }
1.21      www      10332:         $mrole='cr';
1.678     raeburn  10333:     } elsif ($role =~ /^gr\//) {
                   10334:         my $cwogrp=$url;
1.811     albertel 10335:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  10336:         unless (&allowed('mdg',$cwogrp)) {
                   10337:             &logthis('Refused group assignrole: '.
                   10338:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   10339:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   10340:             return 'refused';
                   10341:         }
                   10342:         $mrole='gr';
1.21      www      10343:     } else {
1.82      www      10344:         my $cwosec=$url;
1.811     albertel 10345:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  10346:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   10347:             my $refused;
                   10348:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   10349:                 if (!(&allowed('c'.$role,$url))) {
                   10350:                     $refused = 1;
                   10351:                 }
                   10352:             } else {
                   10353:                 $refused = 1;
                   10354:             }
1.947     raeburn  10355:             if ($refused) {
1.1045    raeburn  10356:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10357:                 if (!$selfenroll && $context eq 'course') {
                   10358:                     my %crsenv;
                   10359:                     if ($role eq 'cc' || $role eq 'co') {
                   10360:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10361:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   10362:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   10363:                                 if ($crsenv{'internal.courseowner'} eq 
                   10364:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10365:                                     $refused = '';
                   10366:                                 }
                   10367:                             }
                   10368:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   10369:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   10370:                                 if ($crsenv{'internal.courseowner'} eq 
                   10371:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10372:                                     $refused = '';
                   10373:                                 }
                   10374:                             }
                   10375:                         }
                   10376:                     }
1.1172.2.146.  .13(raeb 10377:-23):                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   10378:-23):                     if ($role eq 'st') {
                   10379:-23):                         $refused = '';
                   10380:-23):                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
                   10381:-23):                         $refused = '';
                   10382:-23):                     }
1.1017    raeburn  10383:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  10384:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  10385:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  10386:                         my $wrongcc;
                   10387:                         if ($cnum =~ /^$match_community$/) {
                   10388:                             $wrongcc = 1 if ($role eq 'cc');
                   10389:                         } else {
                   10390:                             $wrongcc = 1 if ($role eq 'co');
                   10391:                         }
                   10392:                         unless ($wrongcc) {
                   10393:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10394:                             if ($crsenv{'internal.courseowner'} eq 
                   10395:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   10396:                                 $refused = '';
                   10397:                             }
1.1017    raeburn  10398:                         }
                   10399:                     }
1.1172.2.9  raeburn  10400:                 } elsif ($context eq 'requestauthor') {
                   10401:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   10402:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   10403:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   10404:                             $refused = '';
                   10405:                         } else {
                   10406:                             my %domdefaults = &get_domain_defaults($udom);
                   10407:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   10408:                                 my $checkbystatus;
                   10409:                                 if ($env{'user.adv'}) {
                   10410:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   10411:                                     if ($disposition eq 'automatic') {
                   10412:                                         $refused = '';
                   10413:                                     } elsif ($disposition eq '') {
                   10414:                                         $checkbystatus = 1;
                   10415:                                     }
                   10416:                                 } else {
                   10417:                                     $checkbystatus = 1;
                   10418:                                 }
                   10419:                                 if ($checkbystatus) {
                   10420:                                     if ($env{'environment.inststatus'}) {
                   10421:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   10422:                                         foreach my $type (@inststatuses) {
                   10423:                                             if (($type ne '') &&
                   10424:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   10425:                                                 $refused = '';
                   10426:                                             }
                   10427:                                         }
                   10428:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   10429:                                         $refused = '';
                   10430:                                     }
                   10431:                                 }
                   10432:                             }
                   10433:                         }
                   10434:                     }
1.1017    raeburn  10435:                 }
                   10436:                 if ($refused) {
1.947     raeburn  10437:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   10438:                              ' '.$role.' '.$end.' '.$start.' by '.
                   10439: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   10440:                     return 'refused';
                   10441:                 }
1.932     raeburn  10442:             }
1.1131    raeburn  10443:         } elsif ($role eq 'au') {
                   10444:             if ($url ne '/'.$udom.'/') {
                   10445:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   10446:                          ' to assign author role for '.$uname.':'.$udom.
                   10447:                          ' in domain: '.$url.' refused (wrong domain).');
                   10448:                 return 'refused';
                   10449:             }
1.104     www      10450:         }
1.21      www      10451:         $mrole=$role;
                   10452:     }
1.620     albertel 10453:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      10454:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      10455:     if ($end) { $command.='_'.$end; }
1.21      www      10456:     if ($start) {
                   10457: 	if ($end) { 
1.81      www      10458:            $command.='_'.$start; 
1.21      www      10459:         } else {
1.81      www      10460:            $command.='_0_'.$start;
1.21      www      10461:         }
                   10462:     }
1.739     raeburn  10463:     my $origstart = $start;
                   10464:     my $origend = $end;
1.957     raeburn  10465:     my $delflag;
1.357     www      10466: # actually delete
                   10467:     if ($deleteflag) {
1.373     www      10468: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      10469: # modify command to delete the role
1.620     albertel 10470:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      10471:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 10472: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      10473: # set start and finish to negative values for userrolelog
                   10474:            $start=-1;
                   10475:            $end=-1;
1.957     raeburn  10476:            $delflag = 1;
1.357     www      10477:         }
                   10478:     }
                   10479: # send command
1.349     www      10480:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      10481: # log new user role if status is ok
1.349     www      10482:     if ($answer eq 'ok') {
1.663     raeburn  10483: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  10484:         if (($role eq 'cc') || ($role eq 'in') ||
                   10485:             ($role eq 'ep') || ($role eq 'ad') ||
                   10486:             ($role eq 'ta') || ($role eq 'st') ||
                   10487:             ($role=~/^cr/) || ($role eq 'gr') ||
                   10488:             ($role eq 'co')) {
1.1172.2.13  raeburn  10489: # for course roles, perform group memberships changes triggered by role change.
                   10490:             unless ($role =~ /^gr/) {
                   10491:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   10492:                                                  $origstart,$selfenroll,$context);
                   10493:             }
1.1172.2.9  raeburn  10494:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10495:                            $selfenroll,$context);
                   10496:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  10497:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   10498:                  ($role eq 'da')) {
1.1172.2.9  raeburn  10499:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10500:                            $context);
                   10501:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   10502:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10503:                              $context);
                   10504:         }
1.1053    raeburn  10505:         if ($role eq 'cc') {
                   10506:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   10507:         }
1.349     www      10508:     }
                   10509:     return $answer;
1.169     harris41 10510: }
                   10511: 
1.1053    raeburn  10512: sub autoupdate_coowners {
                   10513:     my ($url,$end,$start,$uname,$udom) = @_;
                   10514:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   10515:     if (($cdom ne '') && ($cnum ne '')) {
                   10516:         my $now = time;
                   10517:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   10518:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   10519:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   10520:             my $instcode = $coursehash{'internal.coursecode'};
1.1172.2.141  raeburn  10521:             my $xlists = $coursehash{'internal.crosslistings'};
1.1053    raeburn  10522:             if ($instcode ne '') {
1.1056    raeburn  10523:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   10524:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  10525:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  10526:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1172.2.141  raeburn  10527:                         unless ($result eq 'valid') {
                   10528:                             if ($xlists ne '') {
                   10529:                                 foreach my $xlist (split(',',$xlists)) {
                   10530:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
                   10531:                                     $result =
                   10532:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
                   10533:                                                                       $inst_crosslist,$uname.':'.$udom);
                   10534:                                     last if ($result eq 'valid');
                   10535:                                 }
                   10536:                             }
                   10537:                         }
1.1056    raeburn  10538:                         if ($result eq 'valid') {
                   10539:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  10540:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10541:                                     push(@newcoowners,$coowner);
                   10542:                                 }
                   10543:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   10544:                                     push(@newcoowners,$uname.':'.$udom);
                   10545:                                 }
                   10546:                                 @newcoowners = sort(@newcoowners);
                   10547:                             } else {
                   10548:                                 push(@newcoowners,$uname.':'.$udom);
                   10549:                             }
1.1172.2.141  raeburn  10550:                         } elsif ($coursehash{'internal.co-owners'}) {
                   10551:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10552:                                 unless ($coowner eq $uname.':'.$udom) {
                   10553:                                     push(@newcoowners,$coowner);
1.1053    raeburn  10554:                                 }
                   10555:                             }
1.1172.2.141  raeburn  10556:                             unless (@newcoowners > 0) {
                   10557:                                 $delcoowners = 1;
                   10558:                                 $coowners = '';
                   10559:                             }
1.1053    raeburn  10560:                         }
                   10561:                         if (@newcoowners || $delcoowners) {
                   10562:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   10563:                                             $delcoowners,@newcoowners);
                   10564:                         }
                   10565:                     }
                   10566:                 }
                   10567:             }
                   10568:         }
                   10569:     }
                   10570: }
                   10571: 
                   10572: sub store_coowners {
                   10573:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   10574:     my $cid = $cdom.'_'.$cnum;
                   10575:     my ($coowners,$delresult,$putresult);
                   10576:     if (@newcoowners) {
                   10577:         $coowners = join(',',@newcoowners);
                   10578:         my %coownershash = (
                   10579:                             'internal.co-owners' => $coowners,
                   10580:                            );
                   10581:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   10582:         if ($putresult eq 'ok') {
                   10583:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   10584:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   10585:             }
                   10586:         }
                   10587:     }
                   10588:     if ($delcoowners) {
                   10589:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   10590:         if ($delresult eq 'ok') {
                   10591:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   10592:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   10593:             }
                   10594:         }
                   10595:     }
                   10596:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   10597:         my %crsinfo =
                   10598:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   10599:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   10600:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   10601:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   10602:         }
                   10603:     }
                   10604: }
                   10605: 
1.169     harris41 10606: # -------------------------------------------------- Modify user authentication
1.197     www      10607: # Overrides without validation
                   10608: 
1.169     harris41 10609: sub modifyuserauth {
                   10610:     my ($udom,$uname,$umode,$upass)=@_;
                   10611:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  10612:     my $allowed;
                   10613:     if (&allowed('mau',$udom)) {
                   10614:         $allowed = 1;
                   10615:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   10616:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   10617:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   10618:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10619:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10620:         if (($cdom ne '') && ($cnum ne '')) {
                   10621:             my $is_owner = &is_course_owner($cdom,$cnum);
                   10622:             if ($is_owner) {
                   10623:                 $allowed = 1;
                   10624:             }
                   10625:         }
                   10626:     }
                   10627:     unless ($allowed) { return 'refused'; }
1.197     www      10628:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 10629:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10630:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 10631:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10632: 		     &escape($upass),$uhome);
1.1172.2.134  raeburn  10633:     my $ip = &get_requestor_ip();
1.620     albertel 10634:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10635:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.134  raeburn  10636:          '(Remote '.$ip.'): '.$reply);
1.197     www      10637:     &log($udom,,$uname,$uhome,
1.620     albertel 10638:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10639:                                      $env{'user.name'}.', '.$umode.
1.1172.2.134  raeburn  10640:          '(Remote '.$ip.'): '.$reply);
1.169     harris41 10641:     unless ($reply eq 'ok') {
1.197     www      10642:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10643: 	return 'error: '.$reply;
                   10644:     }   
1.170     harris41 10645:     return 'ok';
1.80      www      10646: }
                   10647: 
1.81      www      10648: # --------------------------------------------------------------- Modify a user
1.80      www      10649: 
1.81      www      10650: sub modifyuser {
1.206     matthew  10651:     my ($udom,    $uname, $uid,
                   10652:         $umode,   $upass, $first,
                   10653:         $middle,  $last,  $gene,
1.1058    raeburn  10654:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10655:     $udom= &LONCAPA::clean_domain($udom);
                   10656:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10657:     my $showcandelete = 'none';
                   10658:     if (ref($candelete) eq 'ARRAY') {
                   10659:         if (@{$candelete} > 0) {
                   10660:             $showcandelete = join(', ',@{$candelete});
                   10661:         }
                   10662:     }
1.81      www      10663:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10664:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10665: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10666:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10667:                                      ' desiredhome not specified'). 
1.620     albertel 10668:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10669:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10670:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10671:     my $newuser;
                   10672:     if ($uhome eq 'no_host') {
                   10673:         $newuser = 1;
1.1172.2.146.  .13(raeb 10674:-23):         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   10675:-23):                 ($umode eq 'lti')) {
                   10676:-23):             return 'error: more information needed to create new user';
                   10677:-23):         }
1.1075    raeburn  10678:     }
1.80      www      10679: # ----------------------------------------------------------------- Create User
1.406     albertel 10680:     if (($uhome eq 'no_host') && 
1.1172.2.146.  .13(raeb 10681:-23): 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      10682:         my $unhome='';
1.844     albertel 10683:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10684:             $unhome = $desiredhome;
1.620     albertel 10685: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10686: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10687:         } else { # load balancing routine for determining $unhome
1.81      www      10688:             my $loadm=10000000;
1.841     albertel 10689: 	    my %servers = &get_servers($udom,'library');
                   10690: 	    foreach my $tryserver (keys(%servers)) {
                   10691: 		my $answer=reply('load',$tryserver);
                   10692: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10693: 		    $loadm=$answer;
                   10694: 		    $unhome=$tryserver;
                   10695: 		}
1.80      www      10696: 	    }
                   10697:         }
                   10698:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10699: 	    return 'error: unable to find a home server for '.$uname.
                   10700:                    ' in domain '.$udom;
1.80      www      10701:         }
                   10702:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10703:                          &escape($upass),$unhome);
                   10704: 	unless ($reply eq 'ok') {
                   10705:             return 'error: '.$reply;
                   10706:         }   
1.230     stredwic 10707:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10708:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10709: 	    return 'error: unable verify users home machine.';
1.80      www      10710:         }
1.209     matthew  10711:     }   # End of creation of new user
1.80      www      10712: # ---------------------------------------------------------------------- Add ID
                   10713:     if ($uid) {
                   10714:        $uid=~tr/A-Z/a-z/;
                   10715:        my %uidhash=&idrget($udom,$uname);
1.196     www      10716:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10717:          && (!$forceid)) {
1.80      www      10718: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10719: 	      return 'error: user id "'.$uid.'" does not match '.
                   10720:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10721:           }
                   10722:        } else {
                   10723: 	  &idput($udom,($uname => $uid));
                   10724:        }
                   10725:     }
                   10726: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10727:     my @tmp=&get('environment',
1.899     raeburn  10728: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10729:                     'permanentemail','inststatus'],
1.134     albertel 10730: 		   $udom,$uname);
1.1075    raeburn  10731:     my (%names,%oldnames);
1.313     matthew  10732:     if ($tmp[0] =~ m/^error:.*/) { 
                   10733:         %names=(); 
                   10734:     } else {
                   10735:         %names = @tmp;
1.1075    raeburn  10736:         %oldnames = %names;
1.313     matthew  10737:     }
1.388     www      10738: #
1.1058    raeburn  10739: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10740: # of users did not contain them), do not overwrite existing values
                   10741: # unless field is in $candelete array ref.  
                   10742: #
                   10743: 
                   10744:     my @fields = ('firstname','middlename','lastname','generation',
                   10745:                   'permanentemail','id');
                   10746:     my %newvalues;
                   10747:     if (ref($candelete) eq 'ARRAY') {
                   10748:         foreach my $field (@fields) {
                   10749:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10750:                 if ($field eq 'firstname') {
                   10751:                     $names{$field} = $first;
                   10752:                 } elsif ($field eq 'middlename') {
                   10753:                     $names{$field} = $middle;
                   10754:                 } elsif ($field eq 'lastname') {
                   10755:                     $names{$field} = $last;
                   10756:                 } elsif ($field eq 'generation') { 
                   10757:                     $names{$field} = $gene;
                   10758:                 } elsif ($field eq 'permanentemail') {
                   10759:                     $names{$field} = $email;
                   10760:                 } elsif ($field eq 'id') {
                   10761:                     $names{$field}  = $uid;
                   10762:                 }
                   10763:             }
                   10764:         }
                   10765:     }
1.388     www      10766:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10767:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10768:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10769:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10770:     if ($email) {
                   10771:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10772:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10773:     }
1.899     raeburn  10774:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10775:     if (defined($inststatus)) {
                   10776:         $names{'inststatus'} = '';
                   10777:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10778:         if (ref($usertypes) eq 'HASH') {
                   10779:             my @okstatuses; 
                   10780:             foreach my $item (split(/:/,$inststatus)) {
                   10781:                 if (defined($usertypes->{$item})) {
                   10782:                     push(@okstatuses,$item);  
                   10783:                 }
                   10784:             }
                   10785:             if (@okstatuses) {
                   10786:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10787:             }
                   10788:         }
                   10789:     }
1.1075    raeburn  10790:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10791:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10792:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10793:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10794:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10795:     } else {
                   10796:         $logmsg .= ' during self creation';
                   10797:     }
1.1075    raeburn  10798:     my $changed;
                   10799:     if ($newuser) {
                   10800:         $changed = 1;
                   10801:     } else {
                   10802:         foreach my $field (@fields) {
                   10803:             if ($names{$field} ne $oldnames{$field}) {
                   10804:                 $changed = 1;
                   10805:                 last;
                   10806:             }
                   10807:         }
                   10808:     }
                   10809:     unless ($changed) {
                   10810:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10811:         &logthis($logmsg);
                   10812:         return 'ok';
                   10813:     }
                   10814:     my $reply = &put('environment', \%names, $udom,$uname);
                   10815:     if ($reply ne 'ok') { 
                   10816:         return 'error: '.$reply;
                   10817:     }
1.1087    raeburn  10818:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10819:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10820:     }
1.1075    raeburn  10821:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10822:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10823:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10824:     &logthis($logmsg);
1.134     albertel 10825:     return 'ok';
1.80      www      10826: }
                   10827: 
1.81      www      10828: # -------------------------------------------------------------- Modify student
1.80      www      10829: 
1.81      www      10830: sub modifystudent {
                   10831:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10832:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10833:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10834:     if (!$cid) {
1.620     albertel 10835: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10836: 	    return 'not_in_class';
                   10837: 	}
1.80      www      10838:     }
                   10839: # --------------------------------------------------------------- Make the user
1.81      www      10840:     my $reply=&modifyuser
1.209     matthew  10841: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10842:          $desiredhome,$email,$inststatus);
1.80      www      10843:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10844:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10845:     # student's environment
1.297     matthew  10846:     $uid = undef if (!$forceid);
1.455     albertel 10847:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10848: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10849:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10850:     return $reply;
                   10851: }
                   10852: 
                   10853: sub modify_student_enrollment {
1.1172.2.23  raeburn  10854:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10855:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10856:     my ($cdom,$cnum,$chome);
                   10857:     if (!$cid) {
1.620     albertel 10858: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10859: 	    return 'not_in_class';
                   10860: 	}
1.620     albertel 10861: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10862: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10863:     } else {
                   10864: 	($cdom,$cnum)=split(/_/,$cid);
                   10865:     }
1.620     albertel 10866:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10867:     if (!$chome) {
1.457     raeburn  10868: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10869:     }
1.455     albertel 10870:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10871:     # Make sure the user exists
1.81      www      10872:     my $uhome=&homeserver($uname,$udom);
                   10873:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10874: 	return 'error: no such user';
                   10875:     }
1.297     matthew  10876:     # Get student data if we were not given enough information
                   10877:     if (!defined($first)  || $first  eq '' || 
                   10878:         !defined($last)   || $last   eq '' || 
                   10879:         !defined($uid)    || $uid    eq '' || 
                   10880:         !defined($middle) || $middle eq '' || 
                   10881:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10882:         # They did not supply us with enough data to enroll the student, so
                   10883:         # we need to pick up more information.
1.297     matthew  10884:         my %tmp = &get('environment',
1.294     matthew  10885:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10886:                        ,$udom,$uname);
                   10887: 
1.800     albertel 10888:         #foreach my $key (keys(%tmp)) {
                   10889:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10890:         #}
1.294     matthew  10891:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10892:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10893:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10894:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10895:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10896:     }
1.556     albertel 10897:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10898:     my $user = "$uname:$udom";
                   10899:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10900:     my $reply=cput('classlist',
1.1148    raeburn  10901: 		   {$user => 
1.1172.2.76  raeburn  10902: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10903: 		   $cdom,$cnum);
1.1148    raeburn  10904:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10905:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10906:     } else { 
1.81      www      10907: 	return 'error: '.$reply;
                   10908:     }
1.297     matthew  10909:     # Add student role to user
1.83      www      10910:     my $uurl='/'.$cid;
1.81      www      10911:     $uurl=~s/\_/\//g;
                   10912:     if ($usec) {
                   10913: 	$uurl.='/'.$usec;
                   10914:     }
1.1148    raeburn  10915:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10916:                              $selfenroll,$context);
                   10917:     if ($result ne 'ok') {
                   10918:         if ($old_entry{$user} ne '') {
                   10919:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10920:         } else {
                   10921:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10922:         }
                   10923:     }
                   10924:     return $result; 
1.21      www      10925: }
                   10926: 
1.556     albertel 10927: sub format_name {
                   10928:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10929:     my $name;
                   10930:     if ($first ne 'lastname') {
                   10931: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10932:     } else {
                   10933: 	if ($lastname=~/\S/) {
                   10934: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10935: 	    $name=~s/\s+,/,/;
                   10936: 	} else {
                   10937: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10938: 	}
                   10939:     }
                   10940:     $name=~s/^\s+//;
                   10941:     $name=~s/\s+$//;
                   10942:     $name=~s/\s+/ /g;
                   10943:     return $name;
                   10944: }
                   10945: 
1.84      www      10946: # ------------------------------------------------- Write to course preferences
                   10947: 
                   10948: sub writecoursepref {
                   10949:     my ($courseid,%prefs)=@_;
                   10950:     $courseid=~s/^\///;
                   10951:     $courseid=~s/\_/\//g;
                   10952:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10953:     my $chome=homeserver($cnum,$cdomain);
                   10954:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10955: 	return 'error: no such course';
                   10956:     }
                   10957:     my $cstring='';
1.800     albertel 10958:     foreach my $pref (keys(%prefs)) {
                   10959: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10960:     }
1.84      www      10961:     $cstring=~s/\&$//;
                   10962:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10963: }
                   10964: 
                   10965: # ---------------------------------------------------------- Make/modify course
                   10966: 
                   10967: sub createcourse {
1.741     raeburn  10968:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1172.2.146.  .1(raebu 10969:22):         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      10970:     $url=&declutter($url);
                   10971:     my $cid='';
1.1028    raeburn  10972:     if ($context eq 'requestcourses') {
                   10973:         my $can_create = 0;
                   10974:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10975:         if ($udom eq $ownerdom) {
1.1172.2.146.  .1(raebu 10976:22):             my $reload;
                   10977:22):             if (($callercontext eq 'auto') &&
                   10978:22):                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   10979:22):                 $reload = 'reload';
                   10980:22):             }
                   10981:22):             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  10982:                                   $context)) {
                   10983:                 $can_create = 1;
                   10984:             }
                   10985:         } else {
                   10986:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10987:                                            $category);
                   10988:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10989:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10990:                 if (@curr > 0) {
                   10991:                     my @options = qw(approval validate autolimit);
                   10992:                     my $optregex = join('|',@options);
                   10993:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10994:                         $can_create = 1;
                   10995:                     }
                   10996:                 }
                   10997:             }
                   10998:         }
                   10999:         if ($can_create) {
                   11000:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   11001:                 unless (&allowed('ccc',$udom)) {
                   11002:                     return 'refused'; 
                   11003:                 }
1.1017    raeburn  11004:             }
                   11005:         } else {
                   11006:             return 'refused';
                   11007:         }
1.1028    raeburn  11008:     } elsif (!&allowed('ccc',$udom)) {
                   11009:         return 'refused';
1.84      www      11010:     }
1.1011    raeburn  11011: # --------------------------------------------------------------- Get Unique ID
                   11012:     my $uname;
                   11013:     if ($cnum =~ /^$match_courseid$/) {
                   11014:         my $chome=&homeserver($cnum,$udom,'true');
                   11015:         if (($chome eq '') || ($chome eq 'no_host')) {
                   11016:             $uname = $cnum;
                   11017:         } else {
1.1038    raeburn  11018:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  11019:         }
                   11020:     } else {
1.1038    raeburn  11021:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  11022:     }
                   11023:     return $uname if ($uname =~ /^error/);
                   11024: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  11025:     if (!defined($course_server)) {
                   11026:         if (defined(&domain($udom,'primary'))) {
                   11027:             $course_server = &domain($udom,'primary');
                   11028:         } else {
                   11029:             $course_server = $env{'user.home'}; 
                   11030:         }
                   11031:     }
                   11032:     my %host_servers =
                   11033:         &Apache::lonnet::get_servers($udom,'library');
                   11034:     unless ($host_servers{$course_server}) {
                   11035:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  11036:     }
1.84      www      11037: # ------------------------------------------------------------- Make the course
                   11038:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  11039:                       $course_server);
1.84      www      11040:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  11041:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      11042:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   11043: 	return 'error: no such course';
                   11044:     }
1.271     www      11045: # ----------------------------------------------------------------- Course made
1.516     raeburn  11046: # log existence
1.1029    raeburn  11047:     my $now = time;
1.918     raeburn  11048:     my $newcourse = {
                   11049:                     $udom.'_'.$uname => {
1.921     raeburn  11050:                                      description => $description,
                   11051:                                      inst_code   => $inst_code,
                   11052:                                      owner       => $course_owner,
                   11053:                                      type        => $crstype,
1.1029    raeburn  11054:                                      creator     => $env{'user.name'}.':'.
                   11055:                                                     $env{'user.domain'},
                   11056:                                      created     => $now,
                   11057:                                      context     => $context,
1.918     raeburn  11058:                                                 },
                   11059:                     };
1.921     raeburn  11060:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      11061: # set toplevel url
1.271     www      11062:     my $topurl=$url;
                   11063:     unless ($nonstandard) {
                   11064: # ------------------------------------------ For standard courses, make top url
                   11065:         my $mapurl=&clutter($url);
1.278     www      11066:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 11067:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      11068: <map>
                   11069: <resource id="1" type="start"></resource>
                   11070: <resource id="2" src="$mapurl"></resource>
                   11071: <resource id="3" type="finish"></resource>
                   11072: <link index="1" from="1" to="2"></link>
                   11073: <link index="2" from="2" to="3"></link>
                   11074: </map>
                   11075: ENDINITMAP
                   11076:         $topurl=&declutter(
1.638     albertel 11077:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      11078:                           );
                   11079:     }
                   11080: # ----------------------------------------------------------- Write preferences
1.84      www      11081:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  11082:                      ('description'              => $description,
                   11083:                       'url'                      => $topurl,
                   11084:                       'internal.creator'         => $env{'user.name'}.':'.
                   11085:                                                     $env{'user.domain'},
                   11086:                       'internal.created'         => $now,
                   11087:                       'internal.creationcontext' => $context)
                   11088:                     );
1.84      www      11089:     return '/'.$udom.'/'.$uname;
                   11090: }
                   11091: 
1.1011    raeburn  11092: # ------------------------------------------------------------------- Create ID
                   11093: sub generate_coursenum {
1.1038    raeburn  11094:     my ($udom,$crstype) = @_;
1.1011    raeburn  11095:     my $domdesc = &domain($udom);
                   11096:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  11097:     my $first;
                   11098:     if ($crstype eq 'Community') {
                   11099:         $first = '0';
                   11100:     } else {
                   11101:         $first = int(1+rand(9)); 
                   11102:     } 
                   11103:     my $uname=$first.
1.1011    raeburn  11104:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   11105:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   11106:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   11107: # ----------------------------------------------- Make sure that does not exist
                   11108:     my $uhome=&homeserver($uname,$udom,'true');
                   11109:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  11110:         if ($crstype eq 'Community') {
                   11111:             $first = '0';
                   11112:         } else {
                   11113:             $first = int(1+rand(9));
                   11114:         }
                   11115:         $uname=$first.
1.1011    raeburn  11116:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   11117:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   11118:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   11119:         $uhome=&homeserver($uname,$udom,'true');
                   11120:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   11121:             return 'error: unable to generate unique course-ID';
                   11122:         }
                   11123:     }
                   11124:     return $uname;
                   11125: }
                   11126: 
1.813     albertel 11127: sub is_course {
1.1167    droeschl 11128:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   11129:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  11130:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   11131:     my $uhome=&homeserver($cnum,$cdom);
                   11132:     my $iscourse;
                   11133:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   11134:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   11135:     } else {
                   11136:         my $hashid = $cdom.':'.$cnum;
                   11137:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   11138:         unless (defined($cached)) {
                   11139:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   11140:                                         $cnum,undef,undef,'.');
                   11141:             $iscourse = 0;
                   11142:             if (exists($courses{$cdom.'_'.$cnum})) {
                   11143:                 $iscourse = 1;
                   11144:             }
                   11145:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   11146:         }
                   11147:     }
                   11148:     return unless($iscourse);
1.1167    droeschl 11149:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 11150: }
                   11151: 
1.1015    raeburn  11152: sub store_userdata {
                   11153:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  11154:     my $result;
1.1016    raeburn  11155:     if ($datakey ne '') {
1.1013    raeburn  11156:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  11157:             if ($udom eq '' || $uname eq '') {
                   11158:                 $udom = $env{'user.domain'};
                   11159:                 $uname = $env{'user.name'};
                   11160:             }
                   11161:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  11162:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   11163:                 $result = 'error: no_host';
                   11164:             } else {
1.1172.2.138  raeburn  11165:                 $storehash->{'ip'} = &get_requestor_ip();
1.1013    raeburn  11166:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   11167: 
                   11168:                 my $namevalue='';
                   11169:                 foreach my $key (keys(%{$storehash})) {
                   11170:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   11171:                 }
                   11172:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  11173:                 unless ($namespace eq 'courserequests') {
                   11174:                     $datakey = &escape($datakey);
                   11175:                 }
1.1105    raeburn  11176:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   11177:                                   $namevalue,$uhome);
1.1013    raeburn  11178:             }
                   11179:         } else {
                   11180:             $result = 'error: data to store was not a hash reference'; 
                   11181:         }
                   11182:     } else {
                   11183:         $result= 'error: invalid requestkey'; 
                   11184:     }
                   11185:     return $result;
                   11186: }
                   11187: 
1.21      www      11188: # ---------------------------------------------------------- Assign Custom Role
                   11189: 
                   11190: sub assigncustomrole {
1.957     raeburn  11191:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11192:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  11193:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      11194: }
                   11195: 
                   11196: # ----------------------------------------------------------------- Revoke Role
                   11197: 
                   11198: sub revokerole {
1.957     raeburn  11199:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11200:     my $now=time;
1.965     raeburn  11201:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      11202: }
                   11203: 
                   11204: # ---------------------------------------------------------- Revoke Custom Role
                   11205: 
                   11206: sub revokecustomrole {
1.957     raeburn  11207:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11208:     my $now=time;
1.357     www      11209:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  11210:            $deleteflag,$selfenroll,$context);
1.17      www      11211: }
                   11212: 
1.533     banghart 11213: # ------------------------------------------------------------ Disk usage
1.535     albertel 11214: sub diskusage {
1.955     raeburn  11215:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   11216:     $directorypath =~ s/\/$//;
                   11217:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   11218:                        .&escape($getpropath).':'.&escape($uname).':'
                   11219:                        .&escape($udom),homeserver($uname,$udom));
                   11220:     if ($listing eq 'unknown_cmd') {
                   11221:         if ($getpropath) {
                   11222:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   11223:         }
                   11224:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   11225:     }
1.514     albertel 11226:     return $listing;
1.512     banghart 11227: }
                   11228: 
1.566     banghart 11229: sub is_locked {
1.1096    raeburn  11230:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 11231:     my @check;
                   11232:     my $is_locked;
1.1093    raeburn  11233:     push (@check,$file_name);
1.613     albertel 11234:     my %locked = &get('file_permissions',\@check,
1.620     albertel 11235: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 11236:     my ($tmp)=keys(%locked);
                   11237:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  11238:     
1.566     banghart 11239:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  11240:         $is_locked = 'false';
                   11241:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  11242:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  11243:                $is_locked = 'true';
1.1096    raeburn  11244:                if (ref($which) eq 'ARRAY') {
                   11245:                    push(@{$which},$entry);
                   11246:                } else {
                   11247:                    last;
                   11248:                }
1.745     raeburn  11249:            }
                   11250:        }
1.566     banghart 11251:     } else {
                   11252:         $is_locked = 'false';
                   11253:     }
1.1093    raeburn  11254:     return $is_locked;
1.566     banghart 11255: }
                   11256: 
1.759     albertel 11257: sub declutter_portfile {
                   11258:     my ($file) = @_;
1.833     albertel 11259:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 11260:     return $file;
                   11261: }
                   11262: 
1.559     banghart 11263: # ------------------------------------------------------------- Mark as Read Only
                   11264: 
                   11265: sub mark_as_readonly {
                   11266:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 11267:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11268:     my ($tmp)=keys(%current_permissions);
                   11269:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 11270:     foreach my $file (@{$files}) {
1.759     albertel 11271: 	$file = &declutter_portfile($file);
1.561     banghart 11272:         push(@{$current_permissions{$file}},$what);
1.559     banghart 11273:     }
1.613     albertel 11274:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11275:     return;
                   11276: }
                   11277: 
1.572     banghart 11278: # ------------------------------------------------------------Save Selected Files
                   11279: 
                   11280: sub save_selected_files {
                   11281:     my ($user, $path, @files) = @_;
                   11282:     my $filename = $user."savedfiles";
1.573     banghart 11283:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  11284:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 11285:     foreach my $file (@files) {
1.620     albertel 11286:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 11287:     }
                   11288:     foreach my $file (@other_files) {
1.574     banghart 11289:         print (OUT $file."\n");
1.572     banghart 11290:     }
1.574     banghart 11291:     close (OUT);
1.572     banghart 11292:     return 'ok';
                   11293: }
                   11294: 
1.574     banghart 11295: sub clear_selected_files {
                   11296:     my ($user) = @_;
                   11297:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  11298:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 11299:     print (OUT undef);
                   11300:     close (OUT);
                   11301:     return ("ok");    
                   11302: }
                   11303: 
1.572     banghart 11304: sub files_in_path {
                   11305:     my ($user, $path) = @_;
                   11306:     my $filename = $user."savedfiles";
                   11307:     my %return_files;
1.1172.2.96  raeburn  11308:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 11309:     while (my $line_in = <IN>) {
1.574     banghart 11310:         chomp ($line_in);
                   11311:         my @paths_and_file = split (m!/!, $line_in);
                   11312:         my $file_part = pop (@paths_and_file);
                   11313:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 11314:         $path_part.='/';
                   11315:         my $path_and_file = $path_part.$file_part;
                   11316:         if ($path_part eq $path) {
                   11317:             $return_files{$file_part}= 'selected';
                   11318:         }
                   11319:     }
1.574     banghart 11320:     close (IN);
                   11321:     return (\%return_files);
1.572     banghart 11322: }
                   11323: 
                   11324: # called in portfolio select mode, to show files selected NOT in current directory
                   11325: sub files_not_in_path {
                   11326:     my ($user, $path) = @_;
                   11327:     my $filename = $user."savedfiles";
                   11328:     my @return_files;
                   11329:     my $path_part;
1.1172.2.96  raeburn  11330:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 11331:     while (my $line = <IN>) {
1.572     banghart 11332:         #ok, I know it's clunky, but I want it to work
1.800     albertel 11333:         my @paths_and_file = split(m|/|, $line);
                   11334:         my $file_part = pop(@paths_and_file);
                   11335:         chomp($file_part);
                   11336:         my $path_part = join('/', @paths_and_file);
1.572     banghart 11337:         $path_part .= '/';
                   11338:         my $path_and_file = $path_part.$file_part;
                   11339:         if ($path_part ne $path) {
1.800     albertel 11340:             push(@return_files, ($path_and_file));
1.572     banghart 11341:         }
                   11342:     }
1.800     albertel 11343:     close(OUT);
1.574     banghart 11344:     return (@return_files);
1.572     banghart 11345: }
                   11346: 
1.745     raeburn  11347: #----------------------------------------------Get portfolio file permissions
1.629     banghart 11348: 
1.745     raeburn  11349: sub get_portfile_permissions {
                   11350:     my ($domain,$user) = @_;
1.613     albertel 11351:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11352:     my ($tmp)=keys(%current_permissions);
                   11353:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11354:     return \%current_permissions;
                   11355: }
                   11356: 
                   11357: #---------------------------------------------Get portfolio file access controls
                   11358: 
1.749     raeburn  11359: sub get_access_controls {
1.745     raeburn  11360:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 11361:     my %access;
                   11362:     my $real_file = $file;
                   11363:     $file =~ s/\.meta$//;
1.745     raeburn  11364:     if (defined($file)) {
1.749     raeburn  11365:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   11366:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 11367:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  11368:             }
                   11369:         }
1.745     raeburn  11370:     } else {
1.749     raeburn  11371:         foreach my $key (keys(%{$current_permissions})) {
                   11372:             if ($key =~ /\0accesscontrol$/) {
                   11373:                 if (defined($group)) {
                   11374:                     if ($key !~ m-^\Q$group\E/-) {
                   11375:                         next;
                   11376:                     }
                   11377:                 }
                   11378:                 my ($fullpath) = split(/\0/,$key);
                   11379:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   11380:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   11381:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   11382:                     }
                   11383:                 }
                   11384:             }
                   11385:         }
                   11386:     }
                   11387:     return %access;
                   11388: }
                   11389: 
                   11390: sub modify_access_controls {
                   11391:     my ($file_name,$changes,$domain,$user)=@_;
                   11392:     my ($outcome,$deloutcome);
                   11393:     my %store_permissions;
                   11394:     my %new_values;
                   11395:     my %new_control;
                   11396:     my %translation;
                   11397:     my @deletions = ();
                   11398:     my $now = time;
                   11399:     if (exists($$changes{'activate'})) {
                   11400:         if (ref($$changes{'activate'}) eq 'HASH') {
                   11401:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   11402:             my $numnew = scalar(@newitems);
                   11403:             for (my $i=0; $i<$numnew; $i++) {
                   11404:                 my $newkey = $newitems[$i];
                   11405:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  11406:                 if ($newkey =~ /^\d+:/) { 
                   11407:                     $newkey =~ s/^(\d+)/$newid/;
                   11408:                     $translation{$1} = $newid;
                   11409:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   11410:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   11411:                     $translation{$1} = $newid;
                   11412:                 }
1.749     raeburn  11413:                 $new_values{$file_name."\0".$newkey} = 
                   11414:                                           $$changes{'activate'}{$newitems[$i]};
                   11415:                 $new_control{$newkey} = $now;
                   11416:             }
                   11417:         }
                   11418:     }
                   11419:     my %todelete;
                   11420:     my %changed_items;
                   11421:     foreach my $action ('delete','update') {
                   11422:         if (exists($$changes{$action})) {
                   11423:             if (ref($$changes{$action}) eq 'HASH') {
                   11424:                 foreach my $key (keys(%{$$changes{$action}})) {
                   11425:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   11426:                     if ($action eq 'delete') { 
                   11427:                         $todelete{$itemnum} = 1;
                   11428:                     } else {
                   11429:                         $changed_items{$itemnum} = $key;
                   11430:                     }
                   11431:                 }
1.745     raeburn  11432:             }
                   11433:         }
1.749     raeburn  11434:     }
                   11435:     # get lock on access controls for file.
                   11436:     my $lockhash = {
                   11437:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   11438:                                                        ':'.$env{'user.domain'},
                   11439:                    }; 
                   11440:     my $tries = 0;
                   11441:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11442:    
1.1172.2.79  raeburn  11443:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  11444:         $tries ++;
1.1172.2.79  raeburn  11445:         sleep(0.1);
1.749     raeburn  11446:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11447:     }
                   11448:     if ($gotlock eq 'ok') {
                   11449:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   11450:         my ($tmp)=keys(%curr_permissions);
                   11451:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   11452:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   11453:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   11454:             if (ref($curr_controls) eq 'HASH') {
                   11455:                 foreach my $control_item (keys(%{$curr_controls})) {
                   11456:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   11457:                     if (defined($todelete{$itemnum})) {
                   11458:                         push(@deletions,$file_name."\0".$control_item);
                   11459:                     } else {
                   11460:                         if (defined($changed_items{$itemnum})) {
                   11461:                             $new_control{$changed_items{$itemnum}} = $now;
                   11462:                             push(@deletions,$file_name."\0".$control_item);
                   11463:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   11464:                         } else {
                   11465:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   11466:                         }
                   11467:                     }
1.745     raeburn  11468:                 }
                   11469:             }
                   11470:         }
1.970     raeburn  11471:         my ($group);
                   11472:         if (&is_course($domain,$user)) {
                   11473:             ($group,my $file) = split(/\//,$file_name,2);
                   11474:         }
1.749     raeburn  11475:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   11476:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   11477:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   11478:         #  remove lock
                   11479:         my @del_lock = ($file_name."\0".'locked_access_records');
                   11480:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  11481:         my $sqlresult =
1.970     raeburn  11482:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  11483:                                     $group);
1.749     raeburn  11484:     } else {
                   11485:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  11486:     }
1.749     raeburn  11487:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  11488: }
                   11489: 
1.827     raeburn  11490: sub make_public_indefinitely {
                   11491:     my ($requrl) = @_;
                   11492:     my $now = time;
                   11493:     my $action = 'activate';
                   11494:     my $aclnum = 0;
                   11495:     if (&is_portfolio_url($requrl)) {
                   11496:         my (undef,$udom,$unum,$file_name,$group) =
                   11497:             &parse_portfolio_url($requrl);
                   11498:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   11499:         my %access_controls = &get_access_controls($current_perms,
                   11500:                                                    $group,$file_name);
                   11501:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   11502:             my ($num,$scope,$end,$start) = 
                   11503:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   11504:             if ($scope eq 'public') {
                   11505:                 if ($start <= $now && $end == 0) {
                   11506:                     $action = 'none';
                   11507:                 } else {
                   11508:                     $action = 'update';
                   11509:                     $aclnum = $num;
                   11510:                 }
                   11511:                 last;
                   11512:             }
                   11513:         }
                   11514:         if ($action eq 'none') {
                   11515:              return 'ok';
                   11516:         } else {
                   11517:             my %changes;
                   11518:             my $newend = 0;
                   11519:             my $newstart = $now;
                   11520:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   11521:             $changes{$action}{$newkey} = {
                   11522:                 type => 'public',
                   11523:                 time => {
                   11524:                     start => $newstart,
                   11525:                     end   => $newend,
                   11526:                 },
                   11527:             };
                   11528:             my ($outcome,$deloutcome,$new_values,$translation) =
                   11529:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   11530:             return $outcome;
                   11531:         }
                   11532:     } else {
                   11533:         return 'invalid';
                   11534:     }
                   11535: }
                   11536: 
1.745     raeburn  11537: #------------------------------------------------------Get Marked as Read Only
                   11538: 
                   11539: sub get_marked_as_readonly {
                   11540:     my ($domain,$user,$what,$group) = @_;
                   11541:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 11542:     my @readonly_files;
1.629     banghart 11543:     my $cmp1=$what;
                   11544:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  11545:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11546:         if (defined($group)) {
                   11547:             if ($file_name !~ m-^\Q$group\E/-) {
                   11548:                 next;
                   11549:             }
                   11550:         }
1.561     banghart 11551:         if (ref($value) eq "ARRAY"){
                   11552:             foreach my $stored_what (@{$value}) {
1.629     banghart 11553:                 my $cmp2=$stored_what;
1.759     albertel 11554:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  11555:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  11556:                 }
1.629     banghart 11557:                 if ($cmp1 eq $cmp2) {
1.561     banghart 11558:                     push(@readonly_files, $file_name);
1.745     raeburn  11559:                     last;
1.563     banghart 11560:                 } elsif (!defined($what)) {
                   11561:                     push(@readonly_files, $file_name);
1.745     raeburn  11562:                     last;
1.561     banghart 11563:                 }
                   11564:             }
1.745     raeburn  11565:         }
1.561     banghart 11566:     }
                   11567:     return @readonly_files;
                   11568: }
1.577     banghart 11569: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 11570: 
1.577     banghart 11571: sub get_marked_as_readonly_hash {
1.745     raeburn  11572:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 11573:     my %readonly_files;
1.745     raeburn  11574:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11575:         if (defined($group)) {
                   11576:             if ($file_name !~ m-^\Q$group\E/-) {
                   11577:                 next;
                   11578:             }
                   11579:         }
1.577     banghart 11580:         if (ref($value) eq "ARRAY"){
                   11581:             foreach my $stored_what (@{$value}) {
1.745     raeburn  11582:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 11583:                     foreach my $lock_descriptor(@{$stored_what}) {
                   11584:                         if ($lock_descriptor eq 'graded') {
                   11585:                             $readonly_files{$file_name} = 'graded';
                   11586:                         } elsif ($lock_descriptor eq 'handback') {
                   11587:                             $readonly_files{$file_name} = 'handback';
                   11588:                         } else {
                   11589:                             if (!exists($readonly_files{$file_name})) {
                   11590:                                 $readonly_files{$file_name} = 'locked';
                   11591:                             }
                   11592:                         }
1.745     raeburn  11593:                     }
1.750     banghart 11594:                 } 
1.577     banghart 11595:             }
                   11596:         } 
                   11597:     }
                   11598:     return %readonly_files;
                   11599: }
1.559     banghart 11600: # ------------------------------------------------------------ Unmark as Read Only
                   11601: 
                   11602: sub unmark_as_readonly {
1.629     banghart 11603:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   11604:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  11605:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 11606:     $file_name = &declutter_portfile($file_name);
1.634     albertel 11607:     my $symb_crs = $what;
                   11608:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  11609:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 11610:     my ($tmp)=keys(%current_permissions);
                   11611:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11612:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 11613:     foreach my $file (@readonly_files) {
1.759     albertel 11614: 	my $clean_file = &declutter_portfile($file);
                   11615: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 11616: 	my $current_locks = $current_permissions{$file};
1.563     banghart 11617:         my @new_locks;
                   11618:         my @del_keys;
                   11619:         if (ref($current_locks) eq "ARRAY"){
                   11620:             foreach my $locker (@{$current_locks}) {
1.632     albertel 11621:                 my $compare=$locker;
1.749     raeburn  11622:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  11623:                     $compare=join('',@{$locker});
1.746     raeburn  11624:                     if ($compare ne $symb_crs) {
                   11625:                         push(@new_locks, $locker);
                   11626:                     }
1.563     banghart 11627:                 }
                   11628:             }
1.650     albertel 11629:             if (scalar(@new_locks) > 0) {
1.563     banghart 11630:                 $current_permissions{$file} = \@new_locks;
                   11631:             } else {
                   11632:                 push(@del_keys, $file);
1.613     albertel 11633:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11634:                 delete($current_permissions{$file});
1.563     banghart 11635:             }
                   11636:         }
1.561     banghart 11637:     }
1.613     albertel 11638:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11639:     return;
                   11640: }
1.512     banghart 11641: 
1.17      www      11642: # ------------------------------------------------------------ Directory lister
                   11643: 
                   11644: sub dirlist {
1.955     raeburn  11645:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11646:     $uri=~s/^\///;
                   11647:     $uri=~s/\/$//;
1.253     stredwic 11648:     my ($udom, $uname);
1.955     raeburn  11649:     if ($getuserdir) {
1.253     stredwic 11650:         $udom = $userdomain;
                   11651:         $uname = $username;
1.955     raeburn  11652:     } else {
                   11653:         (undef,$udom,$uname)=split(/\//,$uri);
                   11654:         if(defined($userdomain)) {
                   11655:             $udom = $userdomain;
                   11656:         }
                   11657:         if(defined($username)) {
                   11658:             $uname = $username;
                   11659:         }
1.253     stredwic 11660:     }
1.955     raeburn  11661:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11662: 
1.955     raeburn  11663:     $dirRoot = $perlvar{'lonDocRoot'};
                   11664:     if (defined($getpropath)) {
                   11665:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11666:         $dirRoot =~ s/\/$//;
1.955     raeburn  11667:     } elsif (defined($getuserdir)) {
                   11668:         my $subdir=$uname.'__';
                   11669:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11670:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11671:                    ."/$udom/$subdir/$uname";
                   11672:     } elsif (defined($alternateRoot)) {
                   11673:         $dirRoot = $alternateRoot;
1.751     banghart 11674:     }
1.253     stredwic 11675: 
                   11676:     if($udom) {
                   11677:         if($uname) {
1.1135    raeburn  11678:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11679:             if ($uhome eq 'no_host') {
                   11680:                 return ([],'no_host');
                   11681:             }
1.955     raeburn  11682:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11683:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11684:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11685:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11686:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11687:             } else {
                   11688:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11689:             }
1.605     matthew  11690:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11691:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11692:                 @listing_results = split(/:/,$listing);
                   11693:             } else {
                   11694:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11695:             }
1.1135    raeburn  11696:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11697:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11698:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11699:                 return ([],$listing);
                   11700:             } else {
                   11701:                 return (\@listing_results);
1.1135    raeburn  11702:             }
1.955     raeburn  11703:         } elsif(!$alternateRoot) {
1.1136    raeburn  11704:             my (%allusers,%listerror);
1.841     albertel 11705: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11706:  	    foreach my $tryserver (keys(%servers)) {
                   11707:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11708:                                   &escape($udom),$tryserver);
                   11709:                 if ($listing eq 'unknown_cmd') {
                   11710: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11711: 				      $udom, $tryserver);
                   11712:                 } else {
                   11713:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11714:                 }
1.841     albertel 11715: 		if ($listing eq 'unknown_cmd') {
                   11716: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11717: 				      $udom, $tryserver);
                   11718: 		    @listing_results = split(/:/,$listing);
                   11719: 		} else {
                   11720: 		    @listing_results =
                   11721: 			map { &unescape($_); } split(/:/,$listing);
                   11722: 		}
1.1136    raeburn  11723:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11724:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11725:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11726:                     $listerror{$tryserver} = $listing;
                   11727:                 } else {
1.841     albertel 11728: 		    foreach my $line (@listing_results) {
                   11729: 			my ($entry) = split(/&/,$line,2);
                   11730: 			$allusers{$entry} = 1;
                   11731: 		    }
                   11732: 		}
1.253     stredwic 11733:             }
1.1136    raeburn  11734:             my @alluserslist=();
1.800     albertel 11735:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11736:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11737:             }
1.1172.2.80  raeburn  11738:             if (!%listerror) {
                   11739:                 # no errors
                   11740:                 return (\@alluserslist);
                   11741:             } elsif (scalar(keys(%servers)) == 1) {
                   11742:                 # one library server, one error
                   11743:                 my ($key) = keys(%listerror);
                   11744:                 return (\@alluserslist, $listerror{$key});
                   11745:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11746:                 # con_lost indicates that we might miss data from at least one
                   11747:                 # library server
                   11748:                 return (\@alluserslist, 'con_lost');
                   11749:             } else {
                   11750:                 # multiple library servers and no con_lost -> data should be
                   11751:                 # complete.
                   11752:                 return (\@alluserslist);
                   11753:             }
                   11754: 
1.253     stredwic 11755:         } else {
1.1136    raeburn  11756:             return ([],'missing username');
1.253     stredwic 11757:         }
1.955     raeburn  11758:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11759:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11760:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11761:         return (\@all_domains);
1.955     raeburn  11762:     } else {
1.1136    raeburn  11763:         return ([],'missing domain');
1.275     stredwic 11764:     }
                   11765: }
                   11766: 
                   11767: # --------------------------------------------- GetFileTimestamp
                   11768: # This function utilizes dirlist and returns the date stamp for
                   11769: # when it was last modified.  It will also return an error of -1
                   11770: # if an error occurs
                   11771: 
                   11772: sub GetFileTimestamp {
1.955     raeburn  11773:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11774:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11775:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11776:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11777:                                     undef,$getuserdir);
                   11778:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11779:         return -1;
                   11780:     }
                   11781:     if (ref($fileref) eq 'ARRAY') {
                   11782:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11783:         # @stats contains first the filename, then the stat output
                   11784:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11785:     } else {
                   11786:         return -1;
1.253     stredwic 11787:     }
1.26      www      11788: }
                   11789: 
1.712     albertel 11790: sub stat_file {
                   11791:     my ($uri) = @_;
1.787     albertel 11792:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11793: 
1.955     raeburn  11794:     my ($udom,$uname,$file);
1.712     albertel 11795:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11796: 	($udom,$uname,$file) =
1.811     albertel 11797: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11798: 	$file = 'userfiles/'.$file;
                   11799:     }
                   11800:     if ($uri =~ m-^/res/-) {
                   11801: 	($udom,$uname) = 
1.807     albertel 11802: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11803: 	$file = $uri;
                   11804:     }
                   11805: 
                   11806:     if (!$udom || !$uname || !$file) {
                   11807: 	# unable to handle the uri
                   11808: 	return ();
                   11809:     }
1.956     raeburn  11810:     my $getpropath;
                   11811:     if ($file =~ /^userfiles\//) {
                   11812:         $getpropath = 1;
                   11813:     }
1.1136    raeburn  11814:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11815:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11816:         return ();
                   11817:     } else {
                   11818:         if (ref($listref) eq 'ARRAY') {
                   11819:             my @stats = split('&',$listref->[0]);
                   11820: 	    shift(@stats); #filename is first
                   11821: 	    return @stats;
                   11822:         }
1.712     albertel 11823:     }
                   11824:     return ();
                   11825: }
                   11826: 
1.26      www      11827: # -------------------------------------------------------- Value of a Condition
                   11828: 
1.713     albertel 11829: # gets the value of a specific preevaluated condition
                   11830: #    stored in the string  $env{user.state.<cid>}
                   11831: # or looks up a condition reference in the bighash and if if hasn't
                   11832: # already been evaluated recurses into docondval to get the value of
                   11833: # the condition, then memoizing it to 
                   11834: #   $env{user.state.<cid>.<condition>}
1.40      www      11835: sub directcondval {
                   11836:     my $number=shift;
1.620     albertel 11837:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11838: 	&Apache::lonuserstate::evalstate();
                   11839:     }
1.713     albertel 11840:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11841: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11842:     } elsif ($number =~ /^_/) {
                   11843: 	my $sub_condition;
                   11844: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11845: 		&GDBM_READER(),0640)) {
                   11846: 	    $sub_condition=$bighash{'conditions'.$number};
                   11847: 	    untie(%bighash);
                   11848: 	}
                   11849: 	my $value = &docondval($sub_condition);
1.949     raeburn  11850: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11851: 	return $value;
                   11852:     }
1.620     albertel 11853:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11854:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11855:     } else {
                   11856:        return 2;
                   11857:     }
                   11858: }
                   11859: 
1.713     albertel 11860: # get the collection of conditions for this resource
1.26      www      11861: sub condval {
                   11862:     my $condidx=shift;
1.54      www      11863:     my $allpathcond='';
1.713     albertel 11864:     foreach my $cond (split(/\|/,$condidx)) {
                   11865: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11866: 	    $allpathcond.=
                   11867: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11868: 	}
1.191     harris41 11869:     }
1.54      www      11870:     $allpathcond=~s/\|$//;
1.713     albertel 11871:     return &docondval($allpathcond);
                   11872: }
                   11873: 
                   11874: #evaluates an expression of conditions
                   11875: sub docondval {
                   11876:     my ($allpathcond) = @_;
                   11877:     my $result=0;
                   11878:     if ($env{'request.course.id'}
                   11879: 	&& defined($allpathcond)) {
                   11880: 	my $operand='|';
                   11881: 	my @stack;
                   11882: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11883: 	    if ($chunk eq '(') {
                   11884: 		push @stack,($operand,$result);
                   11885: 	    } elsif ($chunk eq ')') {
                   11886: 		my $before=pop @stack;
                   11887: 		if (pop @stack eq '&') {
                   11888: 		    $result=$result>$before?$before:$result;
                   11889: 		} else {
                   11890: 		    $result=$result>$before?$result:$before;
                   11891: 		}
                   11892: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11893: 		$operand=$chunk;
                   11894: 	    } else {
                   11895: 		my $new=directcondval($chunk);
                   11896: 		if ($operand eq '&') {
                   11897: 		    $result=$result>$new?$new:$result;
                   11898: 		} else {
                   11899: 		    $result=$result>$new?$result:$new;
                   11900: 		}
                   11901: 	    }
                   11902: 	}
1.26      www      11903:     }
                   11904:     return $result;
1.421     albertel 11905: }
                   11906: 
                   11907: # ---------------------------------------------------- Devalidate courseresdata
                   11908: 
                   11909: sub devalidatecourseresdata {
                   11910:     my ($coursenum,$coursedomain)=@_;
                   11911:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11912:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11913: }
                   11914: 
1.763     www      11915: 
1.200     www      11916: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11917: #
                   11918: #  Parameters:
                   11919: #      $coursenum    - Number of the course.
                   11920: #      $coursedomain - Domain at which the course was created.
                   11921: #  Returns:
                   11922: #     A hash of the course parameters along (I think) with timestamps
                   11923: #     and version info.
1.877     foxr     11924: 
1.624     albertel 11925: sub get_courseresdata {
                   11926:     my ($coursenum,$coursedomain)=@_;
1.200     www      11927:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11928:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11929:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11930:     my %dumpreply;
1.417     albertel 11931:     unless (defined($cached)) {
1.624     albertel 11932: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11933: 	$result=\%dumpreply;
1.251     albertel 11934: 	my ($tmp) = keys(%dumpreply);
                   11935: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11936: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11937: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11938: 	    return $tmp;
1.416     albertel 11939: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11940: 	    $result=undef;
1.599     albertel 11941: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11942: 	}
                   11943:     }
1.624     albertel 11944:     return $result;
                   11945: }
                   11946: 
1.633     albertel 11947: sub devalidateuserresdata {
                   11948:     my ($uname,$udom)=@_;
                   11949:     my $hashid="$udom:$uname";
                   11950:     &devalidate_cache_new('userres',$hashid);
                   11951: }
                   11952: 
1.624     albertel 11953: sub get_userresdata {
                   11954:     my ($uname,$udom)=@_;
                   11955:     #most student don\'t have any data set, check if there is some data
                   11956:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11957: 
                   11958:     my $hashid="$udom:$uname";
                   11959:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11960:     if (!defined($cached)) {
                   11961: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11962: 	$result=\%resourcedata;
                   11963: 	&do_cache_new('userres',$hashid,$result,600);
                   11964:     }
                   11965:     my ($tmp)=keys(%$result);
                   11966:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11967: 	return $result;
                   11968:     }
                   11969:     #error 2 occurs when the .db doesn't exist
                   11970:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11971:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11972: 	    &logthis("<font color=\"blue\">WARNING:".
                   11973: 		     " Trying to get resource data for ".
                   11974: 		     $uname." at ".$udom.": ".
                   11975: 		     $tmp."</font>");
                   11976:         }
1.624     albertel 11977:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11978: 	#&EXT_cache_set($udom,$uname);
                   11979: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11980: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11981:     }
                   11982:     return $tmp;
                   11983: }
1.879     foxr     11984: #----------------------------------------------- resdata - return resource data
                   11985: #  Purpose:
                   11986: #    Return resource data for either users or for a course.
                   11987: #  Parameters:
                   11988: #     $name      - Course/user name.
                   11989: #     $domain    - Name of the domain the user/course is registered on.
                   11990: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   11991: #     @which     - Array of names of resources desired.
                   11992: #  Returns:
                   11993: #     The value of the first reasource in @which that is found in the
                   11994: #     resource hash.
                   11995: #  Exceptional Conditions:
                   11996: #     If the $type passed in is not valid (not the string 'course' or 
                   11997: #     'user', an undefined  reference is returned.
                   11998: #     If none of the resources are found, an undef is returned
1.624     albertel 11999: sub resdata {
                   12000:     my ($name,$domain,$type,@which)=@_;
                   12001:     my $result;
                   12002:     if ($type eq 'course') {
                   12003: 	$result=&get_courseresdata($name,$domain);
                   12004:     } elsif ($type eq 'user') {
                   12005: 	$result=&get_userresdata($name,$domain);
                   12006:     }
                   12007:     if (!ref($result)) { return $result; }    
1.251     albertel 12008:     foreach my $item (@which) {
1.927     albertel 12009: 	if (defined($result->{$item->[0]})) {
                   12010: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 12011: 	}
1.250     albertel 12012:     }
1.291     albertel 12013:     return undef;
1.200     www      12014: }
                   12015: 
1.1172.2.146.  .1(raebu 12016:22): sub get_domain_lti {
                   12017:22):     my ($cdom,$context) = @_;
          .4(raebu 12018:22):     my ($name,$cachename,%lti);
          .1(raebu 12019:22):     if ($context eq 'consumer') {
                   12020:22):         $name = 'ltitools';
                   12021:22):     } elsif ($context eq 'provider') {
                   12022:22):         $name = 'lti';
          .4(raebu 12023:22):     } elsif ($context eq 'linkprot') {
                   12024:22):         $name = 'ltisec';
          .1(raebu 12025:22):     } else {
                   12026:22):         return %lti;
                   12027:22):     }
          .4(raebu 12028:22):     if ($context eq 'linkprot') {
                   12029:22):         $cachename = $context;
                   12030:22):     } else {
                   12031:22):         $cachename = $name;
                   12032:22):     }
                   12033:22):     my ($result,$cached)=&is_cached_new($cachename,$cdom);
          .1(raebu 12034:22):     if (defined($cached)) {
                   12035:22):         if (ref($result) eq 'HASH') {
                   12036:22):             %lti = %{$result};
                   12037:22):         }
                   12038:22):     } else {
                   12039:22):         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   12040:22):         if (ref($domconfig{$name}) eq 'HASH') {
          .4(raebu 12041:22):             if ($context eq 'linkprot') {
                   12042:22):                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
                   12043:22):                     %lti = %{$domconfig{$name}{'linkprot'}};
                   12044:22):                 }
                   12045:22):             } else {
                   12046:22):                 %lti = %{$domconfig{$name}};
                   12047:22):             }
          .1(raebu 12048:22):         }
                   12049:22):         my $cachetime = 24*60*60;
          .4(raebu 12050:22):         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
          .1(raebu 12051:22):     }
                   12052:22):     return %lti;
                   12053:22): }
                   12054:22): 
                   12055:22): sub get_course_lti {
          .13(raeb 12056:-23):     my ($cnum,$cdom,$context) = @_;
                   12057:-23):     my ($name,$cachename,%lti);
                   12058:-23):     if ($context eq 'consumer') {
                   12059:-23):         $name = 'ltitools';
                   12060:-23):         $cachename = 'courseltitools';
                   12061:-23):     } elsif ($context eq 'provider') {
                   12062:-23):         $name = 'lti';
                   12063:-23):         $cachename = 'courselti';
                   12064:-23):     } else {
                   12065:-23):         return %lti;
                   12066:-23):     }
          .1(raebu 12067:22):     my $hashid=$cdom.'_'.$cnum;
          .13(raeb 12068:-23):     my ($result,$cached)=&is_cached_new($cachename,$hashid);
          .1(raebu 12069:22):     if (defined($cached)) {
                   12070:22):         if (ref($result) eq 'HASH') {
          .13(raeb 12071:-23):             %lti = %{$result};
          .1(raebu 12072:22):         }
                   12073:22):     } else {
          .13(raeb 12074:-23):         %lti = &dump($name,$cdom,$cnum,undef,undef,undef,1);
          .1(raebu 12075:22):         my $cachetime = 24*60*60;
          .13(raeb 12076:-23):         &do_cache_new($cachename,$hashid,\%lti,$cachetime);
          .1(raebu 12077:22):     }
          .13(raeb 12078:-23):     return %lti;
          .1(raebu 12079:22): }
                   12080:22): 
          .3(raebu 12081:22): sub courselti_itemid {
                   12082:22):     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
                   12083:22):     my ($chome,$itemid);
                   12084:22):     $chome = &homeserver($cnum,$cdom);
                   12085:22):     return if ($chome eq 'no_host');
                   12086:22):     if (ref($params) eq 'HASH') {
                   12087:22):         my $rep;
                   12088:22):         if (grep { $_ eq $chome } current_machine_ids()) {
                   12089:22):             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
                   12090:22):         } else {
                   12091:22):             my $escurl = &escape($url);
                   12092:22):             my $escmethod = &escape($method);
                   12093:22):             my $items = &freeze_escape($params);
                   12094:22):             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
                   12095:22):         }
                   12096:22):         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   12097:22):                 ($rep eq 'unknown_cmd')) {
                   12098:22):             $itemid = $rep;
                   12099:22):         }
                   12100:22):     }
                   12101:22):     return $itemid;
                   12102:22): }
                   12103:22): 
                   12104:22): sub domainlti_itemid {
                   12105:22):     my ($cdom,$url,$method,$params,$context) = @_;
                   12106:22):     my ($primary_id,$itemid);
                   12107:22):     $primary_id = &domain($cdom,'primary');
                   12108:22):     return if ($primary_id eq '');
                   12109:22):     if (ref($params) eq 'HASH') {
                   12110:22):         my $rep;
                   12111:22):         if (grep { $_ eq $primary_id } current_machine_ids()) {
                   12112:22):             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
                   12113:22):         } else {
                   12114:22):             my $cnum = '';
                   12115:22):             my $escurl = &escape($url);
                   12116:22):             my $escmethod = &escape($method);
                   12117:22):             my $items = &freeze_escape($params);
                   12118:22):             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
                   12119:22):         }
                   12120:22):         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   12121:22):                 ($rep eq 'unknown_cmd')) {
                   12122:22):             $itemid = $rep;
                   12123:22):         }
                   12124:22):     }
                   12125:22):     return $itemid;
                   12126:22): }
                   12127:22): 
          .15(raeb 12128:-23): sub get_ltitools_id {
                   12129:-23):     my ($context,$cdom,$cnum,$title) = @_;
                   12130:-23):     my ($lockhash,$tries,$gotlock,$id,$error);
                   12131:-23): 
                   12132:-23):     # get lock on ltitools db
                   12133:-23):     $lockhash = {
                   12134:-23):                    lock => $env{'user.name'}.
                   12135:-23):                            ':'.$env{'user.domain'},
                   12136:-23):                 };
                   12137:-23):     $tries = 0;
                   12138:-23):     if ($context eq 'domain') {
                   12139:-23):         $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
                   12140:-23):     } else {
                   12141:-23):         $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
                   12142:-23):     }
                   12143:-23):     while (($gotlock ne 'ok') && ($tries<10)) {
                   12144:-23):         $tries ++;
                   12145:-23):         sleep (0.1);
                   12146:-23):         if ($context eq 'domain') {
                   12147:-23):             $gotlock = &newput_dom('ltitools',$lockhash,$cdom);
                   12148:-23):         } else {
                   12149:-23):             $gotlock = &newput('ltitools',$lockhash,$cdom,$cnum);
                   12150:-23):         }
                   12151:-23):     }
                   12152:-23):     if ($gotlock eq 'ok') {
                   12153:-23):         my %currids;
                   12154:-23):         if ($context eq 'domain') {
                   12155:-23):             %currids = &dump_dom('ltitools',$cdom);
                   12156:-23):         } else {
                   12157:-23):             %currids = &dump('ltitools',$cdom,$cnum);
                   12158:-23):         }
                   12159:-23):         if ($currids{'lock'}) {
                   12160:-23):             delete($currids{'lock'});
                   12161:-23):             if (keys(%currids)) {
                   12162:-23):                 my @curr = sort { $a <=> $b } keys(%currids);
                   12163:-23):                 if ($curr[-1] =~ /^\d+$/) {
                   12164:-23):                     $id = 1 + $curr[-1];
                   12165:-23):                 }
                   12166:-23):             } else {
                   12167:-23):                 $id = 1;
                   12168:-23):             }
                   12169:-23):             if ($id) {
                   12170:-23):                 if ($context eq 'domain') {
                   12171:-23):                     unless (&newput_dom('ltitools',{ $id => $title },$cdom) eq 'ok') {
                   12172:-23):                         $error = 'nostore';
                   12173:-23):                     }
                   12174:-23):                 } else {
                   12175:-23):                     unless (&newput('ltitools',{ $id => $title },$cdom,$cnum) eq 'ok') {
                   12176:-23):                         $error = 'nostore';
                   12177:-23):                     }
                   12178:-23):                 }
                   12179:-23):             } else {
                   12180:-23):                 $error = 'nonumber';
                   12181:-23):             }
                   12182:-23):         }
                   12183:-23):         my $dellockoutcome;
                   12184:-23):         if ($context eq 'domain') {
                   12185:-23):             $dellockoutcome = &del_dom('ltitools',['lock'],$cdom);
                   12186:-23):         } else {
                   12187:-23):             $dellockoutcome = &del('ltitools',['lock'],$cdom,$cnum);
                   12188:-23):         }
                   12189:-23):     } else {
                   12190:-23):         $error = 'nolock';
                   12191:-23):     }
                   12192:-23):     return ($id,$error);
                   12193:-23): }
                   12194:-23): 
          .9(raebu 12195:23): sub count_supptools {
                   12196:23):     my ($cnum,$cdom,$ignorecache,$reload)=@_;
1.1172.2.31  raeburn  12197:     my $hashid=$cnum.':'.$cdom;
1.1172.2.146.  .9(raebu 12198:23):     my ($numexttools,$cached);
1.1172.2.31  raeburn  12199:     unless ($ignorecache) {
1.1172.2.146.  .9(raebu 12200:23):         ($numexttools,$cached) = &is_cached_new('supptools',$hashid);
1.1172.2.31  raeburn  12201:     }
                   12202:     unless (defined($cached)) {
                   12203:         my $chome=&homeserver($cnum,$cdom);
1.1172.2.146.  .9(raebu 12204:23):         $numexttools = 0;
1.1172.2.31  raeburn  12205:         unless ($chome eq 'no_host') {
1.1172.2.146.  .9(raebu 12206:23):             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$reload);
                   12207:23):             if (ref($supplemental) eq 'HASH') {
                   12208:23):                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   12209:23):                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
                   12210:23):                         if ($key =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   12211:23):                             $numexttools ++;
                   12212:23):                         }
                   12213:23):                     }
                   12214:23):                 }
                   12215:23):             }
1.1172.2.31  raeburn  12216:         }
1.1172.2.146.  .9(raebu 12217:23):         &do_cache_new('supptools',$hashid,$numexttools,600);
1.1172.2.31  raeburn  12218:     }
1.1172.2.146.  .9(raebu 12219:23):     return $numexttools;
                   12220:23): }
                   12221:23): 
                   12222:23): sub has_unhidden_suppfiles {
                   12223:23):     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
                   12224:23):     my $hashid=$cnum.':'.$cdom;
                   12225:23):     my ($showsupp,$cached);
                   12226:23):     unless ($ignorecache) {
                   12227:23):         ($showsupp,$cached) = &is_cached_new('showsupp',$hashid);
                   12228:23):     }
                   12229:23):     unless (defined($cached)) {
                   12230:23):         my $chome=&homeserver($cnum,$cdom);
                   12231:23):         unless ($chome eq 'no_host') {
                   12232:23):             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$ignorecache,$possdel);
                   12233:23):             if (ref($supplemental) eq 'HASH') {
                   12234:23):                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   12235:23):                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
                   12236:23):                         next if ($key =~ /\.sequence$/);
                   12237:23):                         if (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
                   12238:23):                             foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
                   12239:23):                                 unless ($supplemental->{'hidden'}->{$id}) {
                   12240:23):                                     $showsupp = 1;
                   12241:23):                                     last;
                   12242:23):                                 }
                   12243:23):                             }
                   12244:23):                         }
                   12245:23):                         last if ($showsupp);
                   12246:23):                     }
                   12247:23):                 }
                   12248:23):             }
                   12249:23):         }
                   12250:23):         &do_cache_new('showsupp',$hashid,$showsupp,600);
                   12251:23):     }
                   12252:23):     return $showsupp;
1.1172.2.31  raeburn  12253: }
                   12254: 
1.379     matthew  12255: #
                   12256: # EXT resource caching routines
                   12257: #
                   12258: 
1.1172.2.146.  .1(raebu 12259:22): {
                   12260:22): # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   12261:22): #
                   12262:22): # The course for which we cache
                   12263:22): my $cachedmapkey='';
                   12264:22): # The cached recursive maps for this course
                   12265:22): my %cachedmaps=();
                   12266:22): # When this was last done
                   12267:22): my $cachedmaptime='';
                   12268:22): 
1.379     matthew  12269: sub clear_EXT_cache_status {
1.383     albertel 12270:     &delenv('cache.EXT.');
1.379     matthew  12271: }
                   12272: 
                   12273: sub EXT_cache_status {
                   12274:     my ($target_domain,$target_user) = @_;
1.383     albertel 12275:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 12276:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  12277:         # We know already the user has no data
                   12278:         return 1;
                   12279:     } else {
                   12280:         return 0;
                   12281:     }
                   12282: }
                   12283: 
                   12284: sub EXT_cache_set {
                   12285:     my ($target_domain,$target_user) = @_;
1.383     albertel 12286:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  12287:     #&appenv({$cachename => time});
1.379     matthew  12288: }
                   12289: 
1.28      www      12290: # --------------------------------------------------------- Value of a Variable
1.58      www      12291: sub EXT {
1.715     albertel 12292: 
1.1172.2.28  raeburn  12293:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      12294:     unless ($varname) { return ''; }
1.218     albertel 12295:     #get real user name/domain, courseid and symb
                   12296:     my $courseid;
1.359     albertel 12297:     my $publicuser;
1.427     www      12298:     if ($symbparm) {
                   12299: 	$symbparm=&get_symb_from_alias($symbparm);
                   12300:     }
1.218     albertel 12301:     if (!($uname && $udom)) {
1.790     albertel 12302:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 12303:       if (!$symbparm) {	$symbparm=$cursymb; }
                   12304:     } else {
1.620     albertel 12305: 	$courseid=$env{'request.course.id'};
1.218     albertel 12306:     }
1.48      www      12307:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   12308:     my $rest;
1.320     albertel 12309:     if (defined($therest[0])) {
1.48      www      12310:        $rest=join('.',@therest);
                   12311:     } else {
                   12312:        $rest='';
                   12313:     }
1.320     albertel 12314: 
1.57      www      12315:     my $qualifierrest=$qualifier;
                   12316:     if ($rest) { $qualifierrest.='.'.$rest; }
                   12317:     my $spacequalifierrest=$space;
                   12318:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      12319:     if ($realm eq 'user') {
1.48      www      12320: # --------------------------------------------------------------- user.resource
                   12321: 	if ($space eq 'resource') {
1.651     albertel 12322: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   12323: 		  || defined($Apache::lonhomework::parsing_a_task))
                   12324: 		 &&
1.1172.2.142  raeburn  12325: 		 ($symbparm eq &symbread()) ) {
1.744     albertel 12326: 		# if we are in the middle of processing the resource the
                   12327: 		# get the value we are planning on committing
                   12328:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   12329:                     return $Apache::lonhomework::results{$qualifierrest};
                   12330:                 } else {
                   12331:                     return $Apache::lonhomework::history{$qualifierrest};
                   12332:                 }
1.335     albertel 12333: 	    } else {
1.359     albertel 12334: 		my %restored;
1.620     albertel 12335: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 12336: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   12337: 		} else {
                   12338: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   12339: 		}
1.335     albertel 12340: 		return $restored{$qualifierrest};
                   12341: 	    }
1.48      www      12342: # ----------------------------------------------------------------- user.access
                   12343:         } elsif ($space eq 'access') {
1.218     albertel 12344: 	    # FIXME - not supporting calls for a specific user
1.48      www      12345:             return &allowed($qualifier,$rest);
                   12346: # ------------------------------------------ user.preferences, user.environment
                   12347:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 12348: 	    if (($uname eq $env{'user.name'}) &&
                   12349: 		($udom eq $env{'user.domain'})) {
                   12350: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 12351: 	    } else {
1.359     albertel 12352: 		my %returnhash;
                   12353: 		if (!$publicuser) {
                   12354: 		    %returnhash=&userenvironment($udom,$uname,
                   12355: 						 $qualifierrest);
                   12356: 		}
1.218     albertel 12357: 		return $returnhash{$qualifierrest};
                   12358: 	    }
1.48      www      12359: # ----------------------------------------------------------------- user.course
                   12360:         } elsif ($space eq 'course') {
1.218     albertel 12361: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12362:             return $env{join('.',('request.course',$qualifier))};
1.48      www      12363: # ------------------------------------------------------------------- user.role
                   12364:         } elsif ($space eq 'role') {
1.218     albertel 12365: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12366:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      12367:             if ($qualifier eq 'value') {
                   12368: 		return $role;
                   12369:             } elsif ($qualifier eq 'extent') {
                   12370:                 return $where;
                   12371:             }
                   12372: # ----------------------------------------------------------------- user.domain
                   12373:         } elsif ($space eq 'domain') {
1.218     albertel 12374:             return $udom;
1.48      www      12375: # ------------------------------------------------------------------- user.name
                   12376:         } elsif ($space eq 'name') {
1.218     albertel 12377:             return $uname;
1.48      www      12378: # ---------------------------------------------------- Any other user namespace
1.29      www      12379:         } else {
1.359     albertel 12380: 	    my %reply;
                   12381: 	    if (!$publicuser) {
                   12382: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   12383: 	    }
                   12384: 	    return $reply{$qualifierrest};
1.48      www      12385:         }
1.236     www      12386:     } elsif ($realm eq 'query') {
                   12387: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 12388:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   12389: 						[$spacequalifierrest]);
1.620     albertel 12390: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      12391:    } elsif ($realm eq 'request') {
1.48      www      12392: # ------------------------------------------------------------- request.browser
                   12393:         if ($space eq 'browser') {
1.1145    bisitz   12394:             return $env{'browser.'.$qualifier};
1.57      www      12395: # ------------------------------------------------------------ request.filename
                   12396:         } else {
1.620     albertel 12397:             return $env{'request.'.$spacequalifierrest};
1.29      www      12398:         }
1.28      www      12399:     } elsif ($realm eq 'course') {
1.48      www      12400: # ---------------------------------------------------------- course.description
1.620     albertel 12401:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      12402:     } elsif ($realm eq 'resource') {
1.165     www      12403: 
1.620     albertel 12404: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 12405: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   12406: 	}
1.693     albertel 12407: 
1.1172.2.30  raeburn  12408:         if ($qualifier eq '') {
                   12409: 	    if ($space eq 'title') {
                   12410: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   12411: 	        return &gettitle($symbparm);
                   12412: 	    }
1.693     albertel 12413: 	
1.1172.2.30  raeburn  12414: 	    if ($space eq 'map') {
                   12415: 	        my ($map) = &decode_symb($symbparm);
                   12416: 	        return &symbread($map);
                   12417: 	    }
                   12418:             if ($space eq 'maptitle') {
                   12419:                 my ($map) = &decode_symb($symbparm);
                   12420:                 return &gettitle($map);
                   12421:             }
                   12422: 	    if ($space eq 'filename') {
                   12423: 	        if ($symbparm) {
                   12424: 		    return &clutter((&decode_symb($symbparm))[2]);
                   12425: 	        }
                   12426: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 12427: 	    }
1.1172.2.30  raeburn  12428: 
                   12429:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   12430:                 if ($space eq 'visibleparts') {
                   12431:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   12432:                     my $item;
                   12433:                     if (ref($navmap)) {
                   12434:                         my $res = $navmap->getBySymb($symbparm);
                   12435:                         my $parts = $res->parts();
                   12436:                         if (ref($parts) eq 'ARRAY') {
                   12437:                             $item = join(',',@{$parts});
                   12438:                         }
                   12439:                         undef($navmap);
                   12440:                     }
                   12441:                     return $item;
                   12442:                 }
                   12443:             }
                   12444:         }
1.693     albertel 12445: 
                   12446: 	my ($section, $group, @groups);
1.593     albertel 12447: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  12448:         if (($courseid eq '') && ($cid)) {
                   12449:             $courseid = $cid;
                   12450:         }
                   12451: 	if (($symbparm && $courseid) && 
                   12452: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      12453: 
1.218     albertel 12454: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      12455: 
1.60      www      12456: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 12457: 	    my $symbp=$symbparm;
1.735     albertel 12458: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 12459: 
                   12460: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   12461: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   12462: 
1.620     albertel 12463: 	    if (($env{'user.name'} eq $uname) &&
                   12464: 		($env{'user.domain'} eq $udom)) {
                   12465: 		$section=$env{'request.course.sec'};
1.733     raeburn  12466:                 @groups = split(/:/,$env{'request.course.groups'});  
                   12467:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 12468: 	    } else {
1.539     albertel 12469: 		if (! defined($usection)) {
1.551     albertel 12470: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 12471: 		} else {
                   12472: 		    $section = $usection;
                   12473: 		}
1.733     raeburn  12474:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 12475: 	    }
                   12476: 
                   12477: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   12478: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   12479: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   12480: 
1.593     albertel 12481: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 12482: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 12483: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      12484: 
1.60      www      12485: # ----------------------------------------------------------- first, check user
1.624     albertel 12486: 
                   12487: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 12488: 				       ([$courselevelr,'resource'],
                   12489: 					[$courselevelm,'map'     ],
                   12490: 					[$courselevel, 'course'  ]));
1.931     albertel 12491: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      12492: 
1.594     albertel 12493: # ------------------------------------------------ second, check some of course
1.684     raeburn  12494:             my $coursereply;
1.691     raeburn  12495:             if (@groups > 0) {
                   12496:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   12497:                                        $mapparm,$spacequalifierrest);
1.927     albertel 12498:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  12499:             }
1.96      www      12500: 
1.684     raeburn  12501: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 12502: 				  $env{'course.'.$courseid.'.domain'},
                   12503: 				  'course',
                   12504: 				  ([$seclevelr,   'resource'],
                   12505: 				   [$seclevelm,   'map'     ],
                   12506: 				   [$seclevel,    'course'  ],
                   12507: 				   [$courselevelr,'resource']));
                   12508: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      12509: 
1.60      www      12510: # ------------------------------------------------------ third, check map parms
1.218     albertel 12511: 	    my %parmhash=();
                   12512: 	    my $thisparm='';
                   12513: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 12514: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 12515: 		    &GDBM_READER(),0640)) {
1.218     albertel 12516: 		$thisparm=$parmhash{$symbparm};
                   12517: 		untie(%parmhash);
                   12518: 	    }
1.927     albertel 12519: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 12520: 	}
1.594     albertel 12521: # ------------------------------------------ fourth, look in resource metadata
1.71      www      12522: 
1.1172.2.146.  .13(raeb 12523:-23):         my $what = $spacequalifierrest;
                   12524:-23):         $what=~s/\./\_/;
                   12525:-23):         my $filename;
1.282     albertel 12526: 	if (!$symbparm) { $symbparm=&symbread(); }
                   12527: 	if ($symbparm) {
1.409     www      12528: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 12529: 	} else {
1.620     albertel 12530: 	    $filename=$env{'request.filename'};
1.282     albertel 12531: 	}
1.1172.2.146.  .13(raeb 12532:-23):         my $toolsymb;
                   12533:-23):         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   12534:-23):             $toolsymb = $symbparm;
                   12535:-23):         }
                   12536:-23): 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 12537: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1172.2.146.  .13(raeb 12538:-23): 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 12539: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      12540: 
1.1172.2.146.  .13(raeb 12541:-23): # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 12542: 	if ($symbparm && defined($courseid) && 
1.620     albertel 12543: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 12544: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   12545: 				     $env{'course.'.$courseid.'.domain'},
                   12546: 				     'course',
1.927     albertel 12547: 				     ([$courselevelm,'map'   ],
                   12548: 				      [$courselevel, 'course']));
                   12549: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 12550: 	}
1.145     www      12551: # ------------------------------------------------------------------ Cascade up
1.218     albertel 12552: 	unless ($space eq '0') {
1.336     albertel 12553: 	    my @parts=split(/_/,$space);
                   12554: 	    my $id=pop(@parts);
                   12555: 	    my $part=join('_',@parts);
                   12556: 	    if ($part eq '') { $part='0'; }
1.927     albertel 12557: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 12558: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  12559: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 12560: 	}
1.395     albertel 12561: 	if ($recurse) { return undef; }
1.1172.2.146.  .13(raeb 12562:-23): 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 12563: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      12564: # ---------------------------------------------------- Any other user namespace
                   12565:     } elsif ($realm eq 'environment') {
                   12566: # ----------------------------------------------------------------- environment
1.620     albertel 12567: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   12568: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 12569: 	} else {
1.770     albertel 12570: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   12571: 		return '';
                   12572: 	    }
1.219     albertel 12573: 	    my %returnhash=&userenvironment($udom,$uname,
                   12574: 					    $spacequalifierrest);
                   12575: 	    return $returnhash{$spacequalifierrest};
                   12576: 	}
1.28      www      12577:     } elsif ($realm eq 'system') {
1.48      www      12578: # ----------------------------------------------------------------- system.time
                   12579: 	if ($space eq 'time') {
                   12580: 	    return time;
                   12581:         }
1.696     albertel 12582:     } elsif ($realm eq 'server') {
                   12583: # ----------------------------------------------------------------- system.time
                   12584: 	if ($space eq 'name') {
                   12585: 	    return $ENV{'SERVER_NAME'};
                   12586:         }
1.1172.2.146.  .1(raebu 12587:22):     } elsif ($realm eq 'client') {
                   12588:22):         if ($space eq 'remote_addr') {
                   12589:22):             return &get_requestor_ip();
                   12590:22):         }
1.28      www      12591:     }
1.48      www      12592:     return '';
1.61      www      12593: }
                   12594: 
1.927     albertel 12595: sub get_reply {
                   12596:     my ($reply_value) = @_;
1.940     raeburn  12597:     if (ref($reply_value) eq 'ARRAY') {
                   12598:         if (wantarray) {
                   12599: 	    return @$reply_value;
                   12600:         }
                   12601:         return $reply_value->[0];
                   12602:     } else {
                   12603:         return $reply_value;
1.927     albertel 12604:     }
                   12605: }
                   12606: 
1.691     raeburn  12607: sub check_group_parms {
                   12608:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   12609:     my @groupitems = ();
                   12610:     my $resultitem;
1.927     albertel 12611:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  12612:     foreach my $group (@{$groups}) {
                   12613:         foreach my $level (@levels) {
1.927     albertel 12614:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   12615:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  12616:         }
                   12617:     }
                   12618:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   12619:                             $env{'course.'.$courseid.'.domain'},
                   12620:                                      'course',@groupitems);
                   12621:     return $coursereply;
                   12622: }
                   12623: 
1.1172.2.146.  .1(raebu 12624:22): sub get_map_hierarchy {
                   12625:22):     my ($mapname,$courseid) = @_;
                   12626:22):     my @recurseup = ();
                   12627:22):     if ($mapname) {
                   12628:22):         if (($cachedmapkey eq $courseid) &&
                   12629:22):             (abs($cachedmaptime-time)<5)) {
                   12630:22):             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   12631:22):                 return @{$cachedmaps{$mapname}};
                   12632:22):             }
                   12633:22):         }
                   12634:22):         my $navmap = Apache::lonnavmaps::navmap->new();
                   12635:22):         if (ref($navmap)) {
                   12636:22):             @recurseup = $navmap->recurseup_maps($mapname);
                   12637:22):             undef($navmap);
                   12638:22):             $cachedmaps{$mapname} = \@recurseup;
                   12639:22):             $cachedmaptime=time;
                   12640:22):             $cachedmapkey=$courseid;
                   12641:22):         }
                   12642:22):     }
                   12643:22):     return @recurseup;
                   12644:22): }
                   12645:22): 
          .2(raebu 12646:22): }
          .1(raebu 12647:22): 
1.691     raeburn  12648: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  12649:     my ($courseid,@groups) = @_;
                   12650:     @groups = sort(@groups);
1.691     raeburn  12651:     return @groups;
                   12652: }
                   12653: 
1.395     albertel 12654: sub packages_tab_default {
1.1172.2.146.  .13(raeb 12655:-23):     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 12656:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 12657: 
                   12658:     my (@extension,@specifics,$do_default);
1.1172.2.146.  .13(raeb 12659:-23):     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 12660: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 12661: 	if ($pack_type eq 'default') {
                   12662: 	    $do_default=1;
                   12663: 	} elsif ($pack_type eq 'extension') {
                   12664: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 12665: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 12666: 	    # only look at packages defaults for packages that this id is
1.738     albertel 12667: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   12668: 	}
                   12669:     }
                   12670:     # first look for a package that matches the requested part id
                   12671:     foreach my $package (@specifics) {
                   12672: 	my (undef,$pack_type,$pack_part)=@{$package};
                   12673: 	next if ($pack_part ne $part);
                   12674: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12675: 	    return $packagetab{"$pack_type&$name&default"};
                   12676: 	}
                   12677:     }
                   12678:     # look for any possible matching non extension_ package
                   12679:     foreach my $package (@specifics) {
                   12680: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 12681: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12682: 	    return $packagetab{"$pack_type&$name&default"};
                   12683: 	}
1.585     albertel 12684: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 12685: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   12686: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 12687: 	}
                   12688:     }
1.738     albertel 12689:     # look for any posible extension_ match
                   12690:     foreach my $package (@extension) {
                   12691: 	my ($package,$pack_type)=@{$package};
                   12692: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12693: 	    return $packagetab{"$pack_type&$name&default"};
                   12694: 	}
                   12695: 	if (defined($packagetab{$package."&$name&default"})) {
                   12696: 	    return $packagetab{$package."&$name&default"};
                   12697: 	}
                   12698:     }
                   12699:     # look for a global default setting
                   12700:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   12701: 	return $packagetab{"default&$name&default"};
                   12702:     }
1.395     albertel 12703:     return undef;
                   12704: }
                   12705: 
1.334     albertel 12706: sub add_prefix_and_part {
                   12707:     my ($prefix,$part)=@_;
                   12708:     my $keyroot;
                   12709:     if (defined($prefix) && $prefix !~ /^__/) {
                   12710: 	# prefix that has a part already
                   12711: 	$keyroot=$prefix;
                   12712:     } elsif (defined($prefix)) {
                   12713: 	# prefix that is missing a part
                   12714: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   12715:     } else {
                   12716: 	# no prefix at all
                   12717: 	if (defined($part)) { $keyroot='_'.$part; }
                   12718:     }
                   12719:     return $keyroot;
                   12720: }
                   12721: 
1.71      www      12722: # ---------------------------------------------------------------- Get metadata
                   12723: 
1.599     albertel 12724: my %metaentry;
1.1070    www      12725: my %importedpartids;
1.1172.2.99  raeburn  12726: my %importedrespids;
1.71      www      12727: sub metadata {
1.1172.2.146.  .13(raeb 12728:-23):     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      12729:     $uri=&declutter($uri);
1.288     albertel 12730:     # if it is a non metadata possible uri return quickly
1.529     albertel 12731:     if (($uri eq '') || 
                   12732: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.146.  .1(raebu 12733:22): 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  12734:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 12735: 	return undef;
                   12736:     }
1.1172.2.49  raeburn  12737:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 12738: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 12739: 	return undef;
1.288     albertel 12740:     }
1.73      www      12741:     my $filename=$uri;
                   12742:     $uri=~s/\.meta$//;
1.172     www      12743: #
                   12744: # Is the metadata already cached?
1.177     www      12745: # Look at timestamp of caching
1.172     www      12746: # Everything is cached by the main uri, libraries are never directly cached
                   12747: #
1.428     albertel 12748:     if (!defined($liburi)) {
1.599     albertel 12749: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 12750: 	if (defined($cached)) { return $result->{':'.$what}; }
                   12751:     }
1.1172.2.146.  .13(raeb 12752:-23): 
                   12753:-23): #
                   12754:-23): # If the uri is for an external tool the file from
                   12755:-23): # which metadata should be retrieved depends on whether
                   12756:-23): # the tool had been configured to be gradable (set in the Course
                   12757:-23): # Editor or Resource Editor).
                   12758:-23): #
                   12759:-23): # If a valid symb has been included as the third arg in the call
                   12760:-23): # to &metadata() that can be used to retrieve the value of
                   12761:-23): # parameter_0_gradable set for the resource, and included in the
                   12762:-23): # uploaded map containing the tool. The value is retrieved via
                   12763:-23): # &EXT(), if a valid symb is available.  Otherwise the value of
                   12764:-23): # gradable in the exttool_$marker.db file for the tool instance
                   12765:-23): # is retrieved via &get().
                   12766:-23): #
                   12767:-23): # When lonuserstate::traceroute() calls lonnet::EXT() for
                   12768:-23): # hiddenresource and encrypturl (during course initialization)
                   12769:-23): # the map-level parameter for resource.0.gradable included in the
                   12770:-23): # uploaded map containing the tool will not yet have been stored
                   12771:-23): # in the user_course_parms.db file for the user's session, so in
                   12772:-23): # this case fall back to retrieving gradable status from the
                   12773:-23): # exttool_$marker.db file.
                   12774:-23): #
                   12775:-23): # In order to avoid an infinite loop, &metadata() will return
                   12776:-23): # before a call to &EXT(), if the uri is for an external tool
                   12777:-23): # and the $what for which metadata is being requested is
                   12778:-23): # parameter_0_gradable or 0_gradable.
                   12779:-23): #
                   12780:-23): 
                   12781:-23):     if ($uri =~ /ext\.tool$/) {
                   12782:-23):         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   12783:-23):             return;
                   12784:-23):         } else {
                   12785:-23):             my ($checked,$use_passback);
                   12786:-23):             if ($toolsymb ne '') {
                   12787:-23):                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
                   12788:-23):                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
                   12789:-23):                     $checked = 1;
                   12790:-23):                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   12791:-23):                         $use_passback = 1;
                   12792:-23):                     }
                   12793:-23):                 }
                   12794:-23):             }
                   12795:-23):             unless ($checked) {
                   12796:-23):                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   12797:-23):                 $marker=~s/\D//g;
                   12798:-23):                 if ($marker) {
                   12799:-23):                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   12800:-23):                     $use_passback = $toolsettings{'gradable'};
                   12801:-23):                 }
                   12802:-23):             }
                   12803:-23):             if ($use_passback) {
                   12804:-23):                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   12805:-23):             } else {
                   12806:-23):                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   12807:-23):             }
                   12808:-23):         }
                   12809:-23):     }
                   12810:-23): 
1.428     albertel 12811:     {
1.1069    www      12812: # Imported parts would go here
1.1172.2.99  raeburn  12813:         my @origfiletagids=();
1.1069    www      12814:         my $importedparts=0;
1.1172.2.99  raeburn  12815: 
                   12816: # Imported responseids would go here
                   12817:         my $importedresponses=0;
1.172     www      12818: #
                   12819: # Is this a recursive call for a library?
                   12820: #
1.599     albertel 12821: #	if (! exists($metacache{$uri})) {
                   12822: #	    $metacache{$uri}={};
                   12823: #	}
1.924     albertel 12824: 	my $cachetime = 60*60;
1.171     www      12825:         if ($liburi) {
                   12826: 	    $liburi=&declutter($liburi);
                   12827:             $filename=$liburi;
1.401     bowersj2 12828:         } else {
1.599     albertel 12829: 	    &devalidate_cache_new('meta',$uri);
                   12830: 	    undef(%metaentry);
1.401     bowersj2 12831: 	}
1.140     www      12832:         my %metathesekeys=();
1.73      www      12833:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 12834: 	my $metastring;
1.1140    www      12835: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 12836: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 12837: 	    $metastring = 
1.929     albertel 12838: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 12839: 					  ('grade_target' => 'meta'));
                   12840: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  12841: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   12842:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 12843: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 12844: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 12845: 	    $metastring=&getfile($file);
1.489     albertel 12846: 	}
1.208     albertel 12847:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      12848:         my $token;
1.140     www      12849:         undef %metathesekeys;
1.71      www      12850:         while ($token=$parser->get_token) {
1.339     albertel 12851: 	    if ($token->[0] eq 'S') {
                   12852: 		if (defined($token->[2]->{'package'})) {
1.172     www      12853: #
                   12854: # This is a package - get package info
                   12855: #
1.339     albertel 12856: 		    my $package=$token->[2]->{'package'};
                   12857: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12858: 		    if (defined($token->[2]->{'id'})) { 
                   12859: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12860: 		    }
1.599     albertel 12861: 		    if ($metaentry{':packages'}) {
                   12862: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12863: 		    } else {
1.599     albertel 12864: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12865: 		    }
1.736     albertel 12866: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12867: 			my $part=$keyroot;
                   12868: 			$part=~s/^\_//;
1.736     albertel 12869: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12870: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12871: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12872: 			    # ignore package.tab specified default values
                   12873:                             # here &package_tab_default() will fetch those
                   12874: 			    if ($subp eq 'default') { next; }
1.736     albertel 12875: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12876: 			    my $unikey;
                   12877: 			    if ($pack =~ /_0$/) {
                   12878: 				$unikey='parameter_0_'.$name;
                   12879: 				$part=0;
                   12880: 			    } else {
                   12881: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12882: 			    }
1.339     albertel 12883: 			    if ($subp eq 'display') {
                   12884: 				$value.=' [Part: '.$part.']';
                   12885: 			    }
1.599     albertel 12886: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12887: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12888: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12889: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12890: 			    }
1.599     albertel 12891: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12892: 				$metaentry{':'.$unikey}=
                   12893: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12894: 			    }
1.339     albertel 12895: 			}
                   12896: 		    }
                   12897: 		} else {
1.172     www      12898: #
                   12899: # This is not a package - some other kind of start tag
1.339     albertel 12900: #
                   12901: 		    my $entry=$token->[1];
1.1068    www      12902: 		    my $unikey='';
1.175     www      12903: 
1.339     albertel 12904: 		    if ($entry eq 'import') {
1.175     www      12905: #
                   12906: # Importing a library here
1.339     albertel 12907: #
1.1067    www      12908:                         my $location=$parser->get_text('/import');
                   12909:                         my $dir=$filename;
                   12910:                         $dir=~s|[^/]*$||;
                   12911:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  12912: 
                   12913:                         my $importid=$token->[2]->{'id'};
1.1068    www      12914:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  12915: #
                   12916: # Check metadata for imported file to
                   12917: # see if it contained response items
                   12918: #
                   12919:                         my %currmetaentry = %metaentry;
                   12920:                         my $libresponseorder = &metadata($location,'responseorder');
                   12921:                         my $origfile;
                   12922:                         if ($libresponseorder ne '') {
                   12923:                             if ($#origfiletagids<0) {
                   12924:                                 undef(%importedrespids);
                   12925:                                 undef(%importedpartids);
                   12926:                             }
                   12927:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   12928:                             if (@{$importedrespids{$importid}} > 0) {
                   12929:                                 $importedresponses = 1;
                   12930: # We need to get the original file and the imported file to get the response order correct
                   12931: # Load and inspect original file
                   12932:                                 if ($#origfiletagids<0) {
                   12933:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12934:                                     $origfile=&getfile($origfilelocation);
                   12935:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12936:                                 }
                   12937:                             }
                   12938:                         }
                   12939: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12940: # hash populated for imported library file
                   12941:                         %metaentry = %currmetaentry;
                   12942:                         undef(%currmetaentry);
1.1068    www      12943:                         if ($importmode eq 'problem') {
1.1069    www      12944: # Import as problem/response
1.1068    www      12945:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12946:                         } elsif ($importmode eq 'part') {
                   12947: # Import as part(s)
1.1069    www      12948:                            $importedparts=1;
                   12949: # We need to get the original file and the imported file to get the part order correct
                   12950: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  12951: # Load and inspect original file if we didn't do that already
                   12952:                            if ($#origfiletagids<0) {
                   12953:                                undef(%importedrespids);
                   12954:                                undef(%importedpartids);
                   12955:                                if ($origfile eq '') {
                   12956:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12957:                                    $origfile=&getfile($origfilelocation);
                   12958:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12959:                                }
1.1070    www      12960:                            }
                   12961: 
1.1069    www      12962: # Load and inspect imported file
                   12963:                            my $impfile=&getfile($location);
                   12964:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12965:                            if ($#impfilepartids>=0) {
                   12966: # This problem had parts
1.1070    www      12967:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12968:                            } else {
                   12969: # Importing by turning a single problem into a problem part
                   12970: # It gets the import-tags ID as part-ID
                   12971:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12972:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12973:                            }
1.1068    www      12974:                         } else {
                   12975: # Normal import
                   12976:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12977:                            if (defined($token->[2]->{'id'})) {
                   12978:                               $unikey.='_'.$token->[2]->{'id'};
                   12979:                            }
1.1067    www      12980:                         }
                   12981: 
1.339     albertel 12982: 			if ($depthcount<20) {
1.736     albertel 12983: 			    my $metadata = 
1.1172.2.146.  .13(raeb 12984:-23): 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 12985: 					  $depthcount+1);
                   12986: 			    foreach my $meta (split(',',$metadata)) {
                   12987: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12988: 				$metathesekeys{$meta}=1;
1.339     albertel 12989: 			    }
1.1068    www      12990: 			
                   12991:                         }
1.1067    www      12992: 		    } else {
                   12993: #
                   12994: # Not importing, some other kind of non-package, non-library start tag
                   12995: # 
                   12996:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12997:                         if (defined($token->[2]->{'id'})) {
                   12998:                             $unikey.='_'.$token->[2]->{'id'};
                   12999:                         }
1.339     albertel 13000: 			if (defined($token->[2]->{'name'})) { 
                   13001: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   13002: 			}
                   13003: 			$metathesekeys{$unikey}=1;
1.736     albertel 13004: 			foreach my $param (@{$token->[3]}) {
                   13005: 			    $metaentry{':'.$unikey.'.'.$param} =
                   13006: 				$token->[2]->{$param};
1.339     albertel 13007: 			}
                   13008: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 13009: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 13010: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   13011: 		 # only ws inside the tag, and not in default, so use default
                   13012: 		 # as value
1.599     albertel 13013: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 13014: 			} elsif ( $internaltext =~ /\S/ ) {
                   13015: 		  # something interesting inside the tag
                   13016: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 13017: 			} else {
1.908     albertel 13018: 		  # no interesting values, don't set a default
1.339     albertel 13019: 			}
1.172     www      13020: # end of not-a-package not-a-library import
1.339     albertel 13021: 		    }
1.172     www      13022: # end of not-a-package start tag
1.339     albertel 13023: 		}
1.172     www      13024: # the next is the end of "start tag"
1.339     albertel 13025: 	    }
                   13026: 	}
1.483     albertel 13027: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 13028: 	$extension = lc($extension);
                   13029: 	if ($extension eq 'htm') { $extension='html'; }
                   13030: 
1.737     albertel 13031: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 13032: 	    #no specific packages #how's our extension
                   13033: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 13034: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 13035: 					 \%metathesekeys);
                   13036: 	}
1.883     albertel 13037: 
                   13038: 	if (!exists($metaentry{':packages'})
                   13039: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 13040: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 13041: 		#no specific packages well let's get default then
                   13042: 		if ($key!~/^default&/) { next; }
1.488     albertel 13043: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 13044: 					     \%metathesekeys);
                   13045: 	    }
                   13046: 	}
1.338     www      13047: # are there custom rights to evaluate
1.599     albertel 13048: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 13049: 
1.338     www      13050:     #
                   13051:     # Importing a rights file here
1.339     albertel 13052:     #
                   13053: 	    unless ($depthcount) {
1.599     albertel 13054: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 13055: 		my $dir=$filename;
                   13056: 		$dir=~s|[^/]*$||;
                   13057: 		$location=&filelocation($dir,$location);
1.736     albertel 13058: 		my $rights_metadata =
1.1172.2.146.  .13(raeb 13059:-23): 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 13060: 			      $depthcount+1);
                   13061: 		foreach my $rights (split(',',$rights_metadata)) {
                   13062: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   13063: 		    $metathesekeys{$rights}=1;
1.339     albertel 13064: 		}
                   13065: 	    }
                   13066: 	}
1.737     albertel 13067: 	# uniqifiy package listing
                   13068: 	my %seen;
                   13069: 	my @uniq_packages =
                   13070: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   13071: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   13072: 
1.1172.2.99  raeburn  13073:         if (($importedresponses) || ($importedparts)) {
                   13074:             if ($importedparts) {
1.1070    www      13075: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  13076:                 $metaentry{':partorder'}='';
                   13077:                 $metathesekeys{'partorder'}=1;
                   13078:             }
                   13079:             if ($importedresponses) {
                   13080: # We had imported responses and need to rebuild responseorder
                   13081:                 $metaentry{':responseorder'}='';
                   13082:                 $metathesekeys{'responseorder'}=1;
                   13083:             }
                   13084:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   13085:                 my $origid = $origfiletagids[$index+1];
                   13086:                 if ($origfiletagids[$index] eq 'part') {
                   13087: # Original part, part of the problem
                   13088:                     if ($importedparts) {
                   13089:                         $metaentry{':partorder'}.=','.$origid;
                   13090:                     }
                   13091:                 } elsif ($origfiletagids[$index] eq 'import') {
                   13092:                     if ($importedparts) {
                   13093: # We have imported parts at this position
                   13094:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   13095:                     }
                   13096:                     if ($importedresponses) {
                   13097: # We have imported responses at this position
                   13098:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   13099:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   13100:                         }
                   13101:                     }
                   13102:                 } else {
                   13103: # Original response item, part of the problem
                   13104:                     if ($importedresponses) {
                   13105:                         $metaentry{':responseorder'}.=','.$origid;
                   13106:                     }
                   13107:                 }
                   13108:             }
                   13109:             if ($importedparts) {
                   13110:                 $metaentry{':partorder'}=~s/^\,//;
                   13111:             }
                   13112:             if ($importedresponses) {
                   13113:                 $metaentry{':responseorder'}=~s/^\,//;
                   13114:             }
1.1070    www      13115:         }
                   13116: 
1.737     albertel 13117: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 13118: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  13119: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 13120: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      13121: # this is the end of "was not already recently cached
1.71      www      13122:     }
1.599     albertel 13123:     return $metaentry{':'.$what};
1.261     albertel 13124: }
                   13125: 
1.488     albertel 13126: sub metadata_create_package_def {
1.483     albertel 13127:     my ($uri,$key,$package,$metathesekeys)=@_;
                   13128:     my ($pack,$name,$subp)=split(/\&/,$key);
                   13129:     if ($subp eq 'default') { next; }
                   13130:     
1.599     albertel 13131:     if (defined($metaentry{':packages'})) {
                   13132: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 13133:     } else {
1.599     albertel 13134: 	$metaentry{':packages'}=$package;
1.483     albertel 13135:     }
                   13136:     my $value=$packagetab{$key};
                   13137:     my $unikey;
                   13138:     $unikey='parameter_0_'.$name;
1.599     albertel 13139:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 13140:     $$metathesekeys{$unikey}=1;
1.599     albertel 13141:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   13142: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 13143:     }
1.599     albertel 13144:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   13145: 	$metaentry{':'.$unikey}=
                   13146: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 13147:     }
                   13148: }
                   13149: 
1.261     albertel 13150: sub metadata_generate_part0 {
                   13151:     my ($metadata,$metacache,$uri) = @_;
                   13152:     my %allnames;
1.737     albertel 13153:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 13154: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 13155: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   13156: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 13157: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 13158: 	    $allnames{$name}=$part;
                   13159: 	  }
                   13160: 	}
                   13161:     }
                   13162:     foreach my $name (keys(%allnames)) {
                   13163:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 13164:       my $key=":parameter_0_$name";
1.261     albertel 13165:       $$metacache{"$key.part"}='0';
                   13166:       $$metacache{"$key.name"}=$name;
1.428     albertel 13167:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 13168: 					   $allnames{$name}.'_'.$name.
                   13169: 					   '.type'};
1.428     albertel 13170:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 13171: 			     '.display'};
1.644     www      13172:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 13173:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 13174:       $$metacache{"$key.display"}=$olddis;
                   13175:     }
1.71      www      13176: }
                   13177: 
1.764     albertel 13178: # ------------------------------------------------------ Devalidate title cache
                   13179: 
                   13180: sub devalidate_title_cache {
                   13181:     my ($url)=@_;
                   13182:     if (!$env{'request.course.id'}) { return; }
                   13183:     my $symb=&symbread($url);
                   13184:     if (!$symb) { return; }
                   13185:     my $key=$env{'request.course.id'}."\0".$symb;
                   13186:     &devalidate_cache_new('title',$key);
                   13187: }
                   13188: 
1.1014    droeschl 13189: # ------------------------------------------------- Get the title of a course
                   13190: 
                   13191: sub current_course_title {
                   13192:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   13193: }
1.301     www      13194: # ------------------------------------------------- Get the title of a resource
                   13195: 
                   13196: sub gettitle {
                   13197:     my $urlsymb=shift;
                   13198:     my $symb=&symbread($urlsymb);
1.534     albertel 13199:     if ($symb) {
1.620     albertel 13200: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 13201: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 13202: 	if (defined($cached)) { 
                   13203: 	    return $result;
                   13204: 	}
1.534     albertel 13205: 	my ($map,$resid,$url)=&decode_symb($symb);
                   13206: 	my $title='';
1.907     albertel 13207: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   13208: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   13209: 	} else {
                   13210: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   13211: 		    &GDBM_READER(),0640)) {
                   13212: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   13213: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   13214: 		untie(%bighash);
                   13215: 	    }
1.534     albertel 13216: 	}
                   13217: 	$title=~s/\&colon\;/\:/gs;
                   13218: 	if ($title) {
1.1159    www      13219: # Remember both $symb and $title for dynamic metadata
                   13220:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      13221:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      13222: # Cache this title and then return it
1.599     albertel 13223: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 13224: 	}
                   13225: 	$urlsymb=$url;
                   13226:     }
                   13227:     my $title=&metadata($urlsymb,'title');
                   13228:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   13229:     return $title;
1.301     www      13230: }
1.613     albertel 13231: 
1.614     albertel 13232: sub get_slot {
                   13233:     my ($which,$cnum,$cdom)=@_;
                   13234:     if (!$cnum || !$cdom) {
1.790     albertel 13235: 	(undef,my $courseid)=&whichuser();
1.620     albertel 13236: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   13237: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 13238:     }
1.703     albertel 13239:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   13240:     my %slotinfo;
                   13241:     if (exists($remembered{$key})) {
                   13242: 	$slotinfo{$which} = $remembered{$key};
                   13243:     } else {
                   13244: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   13245: 	&Apache::lonhomework::showhash(%slotinfo);
                   13246: 	my ($tmp)=keys(%slotinfo);
                   13247: 	if ($tmp=~/^error:/) { return (); }
                   13248: 	$remembered{$key} = $slotinfo{$which};
                   13249:     }
1.616     albertel 13250:     if (ref($slotinfo{$which}) eq 'HASH') {
                   13251: 	return %{$slotinfo{$which}};
                   13252:     }
                   13253:     return $slotinfo{$which};
1.614     albertel 13254: }
1.1150    raeburn  13255: 
                   13256: sub get_reservable_slots {
                   13257:     my ($cnum,$cdom,$uname,$udom) = @_;
                   13258:     my $now = time;
                   13259:     my $reservable_info;
                   13260:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   13261:     if (exists($remembered{$key})) {
                   13262:         $reservable_info = $remembered{$key};
                   13263:     } else {
                   13264:         my %resv;
                   13265:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   13266:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   13267:         $reservable_info = \%resv;
                   13268:         $remembered{$key} = $reservable_info;
                   13269:     }
                   13270:     return $reservable_info;
                   13271: }
                   13272: 
                   13273: sub get_course_slots {
                   13274:     my ($cnum,$cdom) = @_;
                   13275:     my $hashid=$cnum.':'.$cdom;
                   13276:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   13277:     if (defined($cached)) {
                   13278:         if (ref($result) eq 'HASH') {
                   13279:             return %{$result};
                   13280:         }
                   13281:     } else {
                   13282:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   13283:         my ($tmp) = keys(%slots);
                   13284:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  13285:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  13286:             return %slots;
                   13287:         }
                   13288:     }
                   13289:     return;
                   13290: }
                   13291: 
                   13292: sub devalidate_slots_cache {
                   13293:     my ($cnum,$cdom)=@_;
                   13294:     my $hashid=$cnum.':'.$cdom;
                   13295:     &devalidate_cache_new('allslots',$hashid);
                   13296: }
                   13297: 
1.1172.2.8  raeburn  13298: sub get_coursechange {
                   13299:     my ($cdom,$cnum) = @_;
                   13300:     if ($cdom eq '' || $cnum eq '') {
                   13301:         return unless ($env{'request.course.id'});
                   13302:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   13303:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   13304:     }
                   13305:     my $hashid=$cdom.'_'.$cnum;
                   13306:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   13307:     if ((defined($cached)) && ($change ne '')) {
                   13308:         return $change;
                   13309:     } else {
                   13310:         my %crshash;
                   13311:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   13312:         if ($crshash{'internal.contentchange'} eq '') {
                   13313:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   13314:             if ($change eq '') {
                   13315:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   13316:                 $change = $crshash{'internal.created'};
                   13317:             }
                   13318:         } else {
                   13319:             $change = $crshash{'internal.contentchange'};
                   13320:         }
                   13321:         my $cachetime = 600;
                   13322:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   13323:     }
                   13324:     return $change;
                   13325: }
                   13326: 
                   13327: sub devalidate_coursechange_cache {
1.1172.2.146.  .9(raebu 13328:23):     my ($cdom,$cnum)=@_;
                   13329:23):     my $hashid=$cdom.'_'.$cnum;
1.1172.2.8  raeburn  13330:     &devalidate_cache_new('crschange',$hashid);
                   13331: }
                   13332: 
1.1172.2.146.  .9(raebu 13333:23): sub get_suppchange {
                   13334:23):     my ($cdom,$cnum) = @_;
                   13335:23):     if ($cdom eq '' || $cnum eq '') {
                   13336:23):         return unless ($env{'request.course.id'});
                   13337:23):         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   13338:23):         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   13339:23):     }
                   13340:23):     my $hashid=$cdom.'_'.$cnum;
                   13341:23):     my ($change,$cached)=&is_cached_new('suppchange',$hashid);
                   13342:23):     if ((defined($cached)) && ($change ne '')) {
                   13343:23):         return $change;
                   13344:23):     } else {
                   13345:23):         my %crshash = &get('environment',['internal.supplementalchange'],$cdom,$cnum);
                   13346:23):         if ($crshash{'internal.supplementalchange'} eq '') {
                   13347:23):             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   13348:23):             if ($change eq '') {
                   13349:23):                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   13350:23):                 $change = $crshash{'internal.created'};
                   13351:23):             }
                   13352:23):         } else {
                   13353:23):             $change = $crshash{'internal.supplementalchange'};
                   13354:23):         }
                   13355:23):         my $cachetime = 600;
                   13356:23):         &do_cache_new('suppchange',$hashid,$change,$cachetime);
                   13357:23):     }
                   13358:23):     return $change;
                   13359:23): }
                   13360:23): 
                   13361:23): sub devalidate_suppchange_cache {
                   13362:23):     my ($cdom,$cnum)=@_;
                   13363:23):     my $hashid=$cdom.'_'.$cnum;
                   13364:23):     &devalidate_cache_new('suppchange',$hashid);
                   13365:23): }
                   13366:23): 
                   13367:23): sub update_supp_caches {
                   13368:23):     my ($cdom,$cnum) = @_;
                   13369:23):     my %servers = &internet_dom_servers($cdom);
                   13370:23):     my @ids=&current_machine_ids();
                   13371:23):     foreach my $server (keys(%servers)) {
                   13372:23):         next if (grep(/^\Q$server\E$/,@ids));
                   13373:23):         my $hashid=$cnum.':'.$cdom;
                   13374:23):         my $cachekey = &escape('showsupp').':'.&escape($hashid);
                   13375:23):         &remote_devalidate_cache($server,[$cachekey]);
                   13376:23):     }
                   13377:23):     &has_unhidden_suppfiles($cnum,$cdom,1,1);
                   13378:23):     &count_supptools($cnum,$cdom,1);
                   13379:23):     my $now = time;
                   13380:23):     if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   13381:23):         &Apache::lonnet::appenv({'request.course.suppupdated' => $now});
                   13382:23):     }
                   13383:23):     &put('environment',{'internal.supplementalchange' => $now},
                   13384:23):          $cdom,$cnum);
                   13385:23):     &Apache::lonnet::appenv(
                   13386:23):         {'course.'.$cdom.'_'.$cnum.'.internal.supplementalchange' => $now});
                   13387:23):     &do_cache_new('suppchange',$cdom.'_'.$cnum,$now,600);
                   13388:23): }
                   13389:23): 
1.31      www      13390: # ------------------------------------------------- Update symbolic store links
                   13391: 
                   13392: sub symblist {
                   13393:     my ($mapname,%newhash)=@_;
1.438     www      13394:     $mapname=&deversion(&declutter($mapname));
1.31      www      13395:     my %hash;
1.620     albertel 13396:     if (($env{'request.course.fn'}) && (%newhash)) {
                   13397:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 13398:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  13399: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 13400: 		next if ($url eq 'last_known'
                   13401: 			 && $env{'form.no_update_last_known'});
                   13402: 		$hash{declutter($url)}=&encode_symb($mapname,
                   13403: 						    $newhash{$url}->[1],
                   13404: 						    $newhash{$url}->[0]);
1.191     harris41 13405:             }
1.31      www      13406:             if (untie(%hash)) {
                   13407: 		return 'ok';
                   13408:             }
                   13409:         }
                   13410:     }
                   13411:     return 'error';
1.212     www      13412: }
                   13413: 
                   13414: # --------------------------------------------------------------- Verify a symb
                   13415: 
                   13416: sub symbverify {
1.1172.2.11  raeburn  13417:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      13418:     my $thisfn=$thisurl;
1.439     www      13419:     $thisfn=&declutter($thisfn);
1.215     www      13420: # direct jump to resource in page or to a sequence - will construct own symbs
                   13421:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   13422: # check URL part
1.409     www      13423:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      13424: 
1.431     www      13425:     unless ($url eq $thisfn) { return 0; }
1.213     www      13426: 
1.216     www      13427:     $symb=&symbclean($symb);
1.510     www      13428:     $thisurl=&deversion($thisurl);
1.439     www      13429:     $thisfn=&deversion($thisfn);
1.213     www      13430: 
                   13431:     my %bighash;
                   13432:     my $okay=0;
1.431     www      13433: 
1.620     albertel 13434:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13435:                             &GDBM_READER(),0640)) {
1.1032    raeburn  13436:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   13437:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  13438:             if ($map =~ m{^uploaded/.+\.page$}) {
                   13439:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   13440:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   13441:             }
                   13442:         }
                   13443:         my $ids;
1.1172.2.122  raeburn  13444:         if ($map =~ m{^uploaded/.+\.page$}) {
                   13445:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13  raeburn  13446:         } else {
                   13447:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  13448:         }
1.1102    raeburn  13449:         unless ($ids) {
1.1172.2.13  raeburn  13450:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  13451:             $ids=$bighash{$idkey};
1.216     www      13452:         }
                   13453:         if ($ids) {
                   13454: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  13455:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   13456:                 $symb =~ s/\?.+$//;
                   13457:             }
1.800     albertel 13458: 	    foreach my $id (split(/\,/,$ids)) {
                   13459: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      13460:                if (
                   13461:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  13462:    eq $symb) {
1.1172.2.11  raeburn  13463:                    if (ref($encstate)) {
                   13464:                        $$encstate = $bighash{'encrypted_'.$id};
                   13465:                    }
1.1172.2.13  raeburn  13466:                    if (($env{'request.role.adv'}) ||
                   13467:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  13468:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  13469:                        $okay=1;
                   13470:                        last;
                   13471:                    }
                   13472:                }
                   13473:            }
1.216     www      13474:         }
1.213     www      13475: 	untie(%bighash);
                   13476:     }
                   13477:     return $okay;
1.31      www      13478: }
                   13479: 
1.210     www      13480: # --------------------------------------------------------------- Clean-up symb
                   13481: 
                   13482: sub symbclean {
                   13483:     my $symb=shift;
1.568     albertel 13484:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      13485: # remove version from map
                   13486:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      13487: 
1.210     www      13488: # remove version from URL
                   13489:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      13490: 
1.507     www      13491: # remove wrapper
                   13492: 
1.510     www      13493:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 13494:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      13495:     return $symb;
1.409     www      13496: }
                   13497: 
                   13498: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 13499: 
                   13500: sub encode_symb {
                   13501:     my ($map,$resid,$url)=@_;
                   13502:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   13503: }
1.409     www      13504: 
                   13505: sub decode_symb {
1.568     albertel 13506:     my $symb=shift;
                   13507:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   13508:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      13509:     return (&fixversion($map),$resid,&fixversion($url));
                   13510: }
                   13511: 
                   13512: sub fixversion {
                   13513:     my $fn=shift;
1.609     banghart 13514:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      13515:     my %bighash;
                   13516:     my $uri=&clutter($fn);
1.620     albertel 13517:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      13518: # is this cached?
1.599     albertel 13519:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      13520:     if (defined($cached)) { return $result; }
                   13521: # unfortunately not cached, or expired
1.620     albertel 13522:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      13523: 	    &GDBM_READER(),0640)) {
                   13524:  	if ($bighash{'version_'.$uri}) {
                   13525:  	    my $version=$bighash{'version_'.$uri};
1.444     www      13526:  	    unless (($version eq 'mostrecent') || 
                   13527: 		    ($version==&getversion($uri))) {
1.440     www      13528:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   13529:  	    }
                   13530:  	}
                   13531:  	untie %bighash;
1.413     www      13532:     }
1.599     albertel 13533:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      13534: }
                   13535: 
                   13536: sub deversion {
                   13537:     my $url=shift;
                   13538:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   13539:     return $url;
1.210     www      13540: }
                   13541: 
1.31      www      13542: # ------------------------------------------------------ Return symb list entry
                   13543: 
                   13544: sub symbread {
1.1172.2.126  raeburn  13545:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128  raeburn  13546:         $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54  raeburn  13547:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128  raeburn  13548:     if (defined($env{$cache_str})) {
1.1172.2.126  raeburn  13549:         unless (ref($possibles) eq 'HASH') {
                   13550:             if ($ignorecachednull) {
                   13551:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   13552:             } else {
                   13553:                 return $env{$cache_str};
                   13554:             }
1.1172.2.66  raeburn  13555:         }
                   13556:     }
1.242     www      13557: # no filename provided? try from environment
1.1172.2.54  raeburn  13558:     unless ($thisfn) {
1.620     albertel 13559:         if ($env{'request.symb'}) {
1.1172.2.128  raeburn  13560:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13  raeburn  13561:         }
                   13562:         $thisfn=$env{'request.filename'};
1.44      www      13563:     }
1.569     albertel 13564:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      13565: # is that filename actually a symb? Verify, clean, and return
                   13566:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 13567: 	if (&symbverify($thisfn,$1)) {
1.1172.2.128  raeburn  13568: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 13569: 	}
1.242     www      13570:     }
1.44      www      13571:     $thisfn=declutter($thisfn);
1.31      www      13572:     my %hash;
1.37      www      13573:     my %bighash;
                   13574:     my $syval='';
1.620     albertel 13575:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.1172.2.128  raeburn  13576:         unless ($ignoresymbdb) {
1.1172.2.126  raeburn  13577:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   13578:                           &GDBM_READER(),0640)) {
1.1172.2.146.  .7(raebu 13579:22): 	        $syval=$hash{$thisfn};
1.1172.2.126  raeburn  13580:                 untie(%hash);
                   13581:             }
1.1172.2.128  raeburn  13582:             if ($syval && $checkforblock) {
                   13583:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126  raeburn  13584:                 if (@blockers) {
                   13585:                     $syval='';
                   13586:                 }
                   13587:             }
1.37      www      13588:         }
                   13589: # ---------------------------------------------------------- There was an entry
                   13590:         if ($syval) {
1.601     albertel 13591: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 13592: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  13593: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13594: 		    #return $env{$cache_str}='';
1.601     albertel 13595: 		#}    
                   13596: 		#$syval.=$1;
                   13597: 	    #}
1.37      www      13598:         } else {
                   13599: # ------------------------------------------------------- Was not in symb table
1.620     albertel 13600:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13601:                             &GDBM_READER(),0640)) {
1.37      www      13602: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      13603:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      13604:               unless ($ids) { 
                   13605:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      13606:               }
                   13607:               unless ($ids) {
                   13608: # alias?
                   13609: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      13610:               }
1.37      www      13611:               if ($ids) {
                   13612: # ------------------------------------------------------------------- Has ID(s)
                   13613:                  my @possibilities=split(/\,/,$ids);
1.39      www      13614:                  if ($#possibilities==0) {
                   13615: # ----------------------------------------------- There is only one possibility
1.37      www      13616: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 13617: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13618: 						    $resid,$thisfn);
1.1172.2.66  raeburn  13619:                      if (ref($possibles) eq 'HASH') {
1.1172.2.126  raeburn  13620:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   13621:                              $possibles->{$syval} = 1;
                   13622:                          }
1.1172.2.66  raeburn  13623:                      }
                   13624:                      if ($checkforblock) {
1.1172.2.126  raeburn  13625:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127  raeburn  13626:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126  raeburn  13627:                              if (@blockers) {
                   13628:                                  $syval = '';
                   13629:                                  untie(%bighash);
                   13630:                                  return $env{$cache_str}='';
                   13631:                              }
1.1172.2.66  raeburn  13632:                          }
                   13633:                      }
                   13634:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      13635: # ------------------------------------------ There is more than one possibility
                   13636:                      my $realpossible=0;
1.800     albertel 13637:                      foreach my $id (@possibilities) {
                   13638: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  13639:                          my $canaccess;
                   13640:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   13641:                              $canaccess = 1;
                   13642:                          } else {
                   13643:                              $canaccess = &allowed('bre',$file);
                   13644:                          }
                   13645:                          if ($canaccess) {
                   13646:          		     my ($mapid,$resid)=split(/\./,$id);
                   13647:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   13648:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13649:                                                              $resid,$thisfn);
1.1172.2.126  raeburn  13650:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127  raeburn  13651:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66  raeburn  13652:                                  if ($checkforblock) {
1.1172.2.127  raeburn  13653:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126  raeburn  13654:                                      if (@blockers > 0) {
                   13655:                                          $syval = '';
                   13656:                                      } else {
1.1172.2.66  raeburn  13657:                                          $syval = $poss_syval;
                   13658:                                          $realpossible++;
                   13659:                                      }
                   13660:                                  } else {
                   13661:                                      $syval = $poss_syval;
                   13662:                                      $realpossible++;
                   13663:                                  }
1.1172.2.126  raeburn  13664:                                  if ($syval) {
                   13665:                                      if (ref($possibles) eq 'HASH') {
                   13666:                                          $possibles->{$syval} = 1;
                   13667:                                      }
                   13668:                                  }
1.1172.2.66  raeburn  13669:                              }
1.39      www      13670: 			 }
1.191     harris41 13671:                      }
1.39      www      13672: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      13673:                  } else {
                   13674:                      $syval='';
1.37      www      13675:                  }
                   13676: 	      }
1.1172.2.66  raeburn  13677:               untie(%bighash);
1.481     raeburn  13678:            }
1.31      www      13679:         }
1.62      www      13680:         if ($syval) {
1.1172.2.128  raeburn  13681: 	    return $env{$cache_str}=$syval;
1.62      www      13682:         }
1.31      www      13683:     }
1.949     raeburn  13684:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13685:     return $env{$cache_str}='';
1.31      www      13686: }
                   13687: 
                   13688: # ---------------------------------------------------------- Return random seed
                   13689: 
1.32      www      13690: sub numval {
                   13691:     my $txt=shift;
                   13692:     $txt=~tr/A-J/0-9/;
                   13693:     $txt=~tr/a-j/0-9/;
                   13694:     $txt=~tr/K-T/0-9/;
                   13695:     $txt=~tr/k-t/0-9/;
                   13696:     $txt=~tr/U-Z/0-5/;
                   13697:     $txt=~tr/u-z/0-5/;
                   13698:     $txt=~s/\D//g;
1.564     albertel 13699:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      13700:     return int($txt);
1.368     albertel 13701: }
                   13702: 
1.484     albertel 13703: sub numval2 {
                   13704:     my $txt=shift;
                   13705:     $txt=~tr/A-J/0-9/;
                   13706:     $txt=~tr/a-j/0-9/;
                   13707:     $txt=~tr/K-T/0-9/;
                   13708:     $txt=~tr/k-t/0-9/;
                   13709:     $txt=~tr/U-Z/0-5/;
                   13710:     $txt=~tr/u-z/0-5/;
                   13711:     $txt=~s/\D//g;
                   13712:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13713:     my $total;
                   13714:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 13715:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 13716:     return int($total);
                   13717: }
                   13718: 
1.575     albertel 13719: sub numval3 {
                   13720:     use integer;
                   13721:     my $txt=shift;
                   13722:     $txt=~tr/A-J/0-9/;
                   13723:     $txt=~tr/a-j/0-9/;
                   13724:     $txt=~tr/K-T/0-9/;
                   13725:     $txt=~tr/k-t/0-9/;
                   13726:     $txt=~tr/U-Z/0-5/;
                   13727:     $txt=~tr/u-z/0-5/;
                   13728:     $txt=~s/\D//g;
                   13729:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13730:     my $total;
                   13731:     foreach my $val (@txts) { $total+=$val; }
                   13732:     if ($_64bit) { $total=(($total<<32)>>32); }
                   13733:     return $total;
                   13734: }
                   13735: 
1.675     albertel 13736: sub digest {
                   13737:     my ($data)=@_;
                   13738:     my $digest=&Digest::MD5::md5($data);
                   13739:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   13740:     my ($e,$f);
                   13741:     {
                   13742:         use integer;
                   13743:         $e=($a+$b);
                   13744:         $f=($c+$d);
                   13745:         if ($_64bit) {
                   13746:             $e=(($e<<32)>>32);
                   13747:             $f=(($f<<32)>>32);
                   13748:         }
                   13749:     }
                   13750:     if (wantarray) {
                   13751: 	return ($e,$f);
                   13752:     } else {
                   13753: 	my $g;
                   13754: 	{
                   13755: 	    use integer;
                   13756: 	    $g=($e+$f);
                   13757: 	    if ($_64bit) {
                   13758: 		$g=(($g<<32)>>32);
                   13759: 	    }
                   13760: 	}
                   13761: 	return $g;
                   13762:     }
                   13763: }
                   13764: 
1.368     albertel 13765: sub latest_rnd_algorithm_id {
1.675     albertel 13766:     return '64bit5';
1.366     albertel 13767: }
1.32      www      13768: 
1.503     albertel 13769: sub get_rand_alg {
                   13770:     my ($courseid)=@_;
1.790     albertel 13771:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 13772:     if ($courseid) {
1.620     albertel 13773: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 13774:     }
                   13775:     return &latest_rnd_algorithm_id();
                   13776: }
                   13777: 
1.562     albertel 13778: sub validCODE {
                   13779:     my ($CODE)=@_;
                   13780:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   13781:     return 0;
                   13782: }
                   13783: 
1.491     albertel 13784: sub getCODE {
1.620     albertel 13785:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 13786:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   13787: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   13788: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 13789: 	return $Apache::lonhomework::history{'resource.CODE'};
                   13790:     }
                   13791:     return undef;
                   13792: }
1.1133    foxr     13793: #
                   13794: #  Determines the random seed for a specific context:
                   13795: #
                   13796: # parameters:
                   13797: #   symb      - in course context the symb for the seed.
                   13798: #   course_id - The course id of the form domain_coursenum.
                   13799: #   domain    - Domain for the user.
                   13800: #   course    - Course for the user.
                   13801: #   cenv      - environment of the course.
                   13802: #
                   13803: # NOTE:
                   13804: #   All parameters are picked out of the environment if missing
                   13805: #   or not defined.
                   13806: #   If a symb cannot be determined the current time is used instead.
                   13807: #
                   13808: #  For a given well defined symb, courside, domain, username,
                   13809: #  and course environment, the seed is reproducible.
                   13810: #
1.31      www      13811: sub rndseed {
1.1133    foxr     13812:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 13813:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 13814:     if (!defined($symb)) {
1.366     albertel 13815: 	unless ($symb=$wsymb) { return time; }
                   13816:     }
1.1146    foxr     13817:     if (!defined $courseid) { 
                   13818: 	$courseid=$wcourseid; 
                   13819:     }
                   13820:     if (!defined $domain) { $domain=$wdomain; }
                   13821:     if (!defined $username) { $username=$wusername }
1.1133    foxr     13822: 
                   13823:     my $which;
                   13824:     if (defined($cenv->{'rndseed'})) {
                   13825: 	$which = $cenv->{'rndseed'};
                   13826:     } else {
                   13827: 	$which =&get_rand_alg($courseid);
                   13828:     }
1.491     albertel 13829:     if (defined(&getCODE())) {
1.675     albertel 13830: 	if ($which eq '64bit5') {
                   13831: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   13832: 	} elsif ($which eq '64bit4') {
1.575     albertel 13833: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   13834: 	} else {
                   13835: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   13836: 	}
1.675     albertel 13837:     } elsif ($which eq '64bit5') {
                   13838: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 13839:     } elsif ($which eq '64bit4') {
                   13840: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 13841:     } elsif ($which eq '64bit3') {
                   13842: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 13843:     } elsif ($which eq '64bit2') {
                   13844: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 13845:     } elsif ($which eq '64bit') {
                   13846: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   13847:     }
                   13848:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   13849: }
                   13850: 
                   13851: sub rndseed_32bit {
                   13852:     my ($symb,$courseid,$domain,$username)=@_;
                   13853:     {
                   13854: 	use integer;
                   13855: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   13856: 	my $symbseed=numval($symb) << 22;
                   13857: 	my $namechck=unpack("%32C*",$username) << 17;
                   13858: 	my $nameseed=numval($username) << 12;
                   13859: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   13860: 	my $courseseed=unpack("%32C*",$courseid);
                   13861: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 13862: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13863: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13864: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 13865: 	return $num;
                   13866:     }
                   13867: }
                   13868: 
                   13869: sub rndseed_64bit {
                   13870:     my ($symb,$courseid,$domain,$username)=@_;
                   13871:     {
                   13872: 	use integer;
                   13873: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   13874: 	my $symbseed=numval($symb) << 10;
                   13875: 	my $namechck=unpack("%32S*",$username);
                   13876: 	
                   13877: 	my $nameseed=numval($username) << 21;
                   13878: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   13879: 	my $courseseed=unpack("%32S*",$courseid);
                   13880: 	
                   13881: 	my $num1=$symbchck+$symbseed+$namechck;
                   13882: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13883: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13884: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13885: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 13886: 	return "$num1,$num2";
1.155     albertel 13887:     }
1.366     albertel 13888: }
                   13889: 
1.443     albertel 13890: sub rndseed_64bit2 {
                   13891:     my ($symb,$courseid,$domain,$username)=@_;
                   13892:     {
                   13893: 	use integer;
                   13894: 	# strings need to be an even # of cahracters long, it it is odd the
                   13895:         # last characters gets thrown away
                   13896: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13897: 	my $symbseed=numval($symb) << 10;
                   13898: 	my $namechck=unpack("%32S*",$username.' ');
                   13899: 	
                   13900: 	my $nameseed=numval($username) << 21;
1.501     albertel 13901: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13902: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13903: 	
                   13904: 	my $num1=$symbchck+$symbseed+$namechck;
                   13905: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13906: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13907: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13908: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13909: 	return "$num1,$num2";
                   13910:     }
                   13911: }
                   13912: 
                   13913: sub rndseed_64bit3 {
                   13914:     my ($symb,$courseid,$domain,$username)=@_;
                   13915:     {
                   13916: 	use integer;
                   13917: 	# strings need to be an even # of cahracters long, it it is odd the
                   13918:         # last characters gets thrown away
                   13919: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13920: 	my $symbseed=numval2($symb) << 10;
                   13921: 	my $namechck=unpack("%32S*",$username.' ');
                   13922: 	
                   13923: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13924: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13925: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13926: 	
                   13927: 	my $num1=$symbchck+$symbseed+$namechck;
                   13928: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13929: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13930: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13931: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13932: 	
1.503     albertel 13933: 	return "$num1:$num2";
1.443     albertel 13934:     }
                   13935: }
                   13936: 
1.575     albertel 13937: sub rndseed_64bit4 {
                   13938:     my ($symb,$courseid,$domain,$username)=@_;
                   13939:     {
                   13940: 	use integer;
                   13941: 	# strings need to be an even # of cahracters long, it it is odd the
                   13942:         # last characters gets thrown away
                   13943: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13944: 	my $symbseed=numval3($symb) << 10;
                   13945: 	my $namechck=unpack("%32S*",$username.' ');
                   13946: 	
                   13947: 	my $nameseed=numval3($username) << 21;
                   13948: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13949: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13950: 	
                   13951: 	my $num1=$symbchck+$symbseed+$namechck;
                   13952: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13953: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13954: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13955: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13956: 	
1.575     albertel 13957: 	return "$num1:$num2";
                   13958:     }
                   13959: }
                   13960: 
1.675     albertel 13961: sub rndseed_64bit5 {
                   13962:     my ($symb,$courseid,$domain,$username)=@_;
                   13963:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13964:     return "$num1:$num2";
                   13965: }
                   13966: 
1.366     albertel 13967: sub rndseed_CODE_64bit {
                   13968:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13969:     {
1.366     albertel 13970: 	use integer;
1.443     albertel 13971: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13972: 	my $symbseed=numval2($symb);
1.491     albertel 13973: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13974: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13975: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13976: 	my $num1=$symbseed+$CODEchck;
                   13977: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13978: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13979: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13980: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13981: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13982: 	return "$num1:$num2";
1.366     albertel 13983:     }
                   13984: }
                   13985: 
1.575     albertel 13986: sub rndseed_CODE_64bit4 {
                   13987:     my ($symb,$courseid,$domain,$username)=@_;
                   13988:     {
                   13989: 	use integer;
                   13990: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13991: 	my $symbseed=numval3($symb);
                   13992: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13993: 	my $CODEseed=numval3(&getCODE());
                   13994: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13995: 	my $num1=$symbseed+$CODEchck;
                   13996: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13997: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13998: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13999: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   14000: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   14001: 	return "$num1:$num2";
                   14002:     }
                   14003: }
                   14004: 
1.675     albertel 14005: sub rndseed_CODE_64bit5 {
                   14006:     my ($symb,$courseid,$domain,$username)=@_;
                   14007:     my $code = &getCODE();
                   14008:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   14009:     return "$num1:$num2";
                   14010: }
                   14011: 
1.366     albertel 14012: sub setup_random_from_rndseed {
                   14013:     my ($rndseed)=@_;
1.503     albertel 14014:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  14015: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   14016:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   14017:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   14018:         } else {
                   14019:             &Math::Random::random_set_seed($num1,$num2);
                   14020:         }
1.366     albertel 14021:     } else {
                   14022: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 14023:     }
1.36      albertel 14024: }
                   14025: 
1.474     albertel 14026: sub latest_receipt_algorithm_id {
1.835     albertel 14027:     return 'receipt3';
1.474     albertel 14028: }
                   14029: 
1.480     www      14030: sub recunique {
                   14031:     my $fucourseid=shift;
                   14032:     my $unique;
1.835     albertel 14033:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   14034: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 14035: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      14036:     } else {
                   14037: 	$unique=$perlvar{'lonReceipt'};
                   14038:     }
                   14039:     return unpack("%32C*",$unique);
                   14040: }
                   14041: 
                   14042: sub recprefix {
                   14043:     my $fucourseid=shift;
                   14044:     my $prefix;
1.835     albertel 14045:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   14046: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 14047: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      14048:     } else {
                   14049: 	$prefix=$perlvar{'lonHostID'};
                   14050:     }
                   14051:     return unpack("%32C*",$prefix);
                   14052: }
                   14053: 
1.76      www      14054: sub ireceipt {
1.474     albertel 14055:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 14056: 
                   14057:     my $return =&recprefix($fucourseid).'-';
                   14058: 
                   14059:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   14060: 	$env{'request.state'} eq 'construct') {
                   14061: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   14062: 	return $return;
                   14063:     }
                   14064: 
1.76      www      14065:     my $cuname=unpack("%32C*",$funame);
                   14066:     my $cudom=unpack("%32C*",$fudom);
                   14067:     my $cucourseid=unpack("%32C*",$fucourseid);
                   14068:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      14069:     my $cunique=&recunique($fucourseid);
1.474     albertel 14070:     my $cpart=unpack("%32S*",$part);
1.835     albertel 14071:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   14072: 
1.790     albertel 14073: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 14074: 			       
                   14075: 	$return.= ($cunique%$cuname+
                   14076: 		   $cunique%$cudom+
                   14077: 		   $cusymb%$cuname+
                   14078: 		   $cusymb%$cudom+
                   14079: 		   $cucourseid%$cuname+
                   14080: 		   $cucourseid%$cudom+
                   14081: 		   $cpart%$cuname+
                   14082: 		   $cpart%$cudom);
                   14083:     } else {
                   14084: 	$return.= ($cunique%$cuname+
                   14085: 		   $cunique%$cudom+
                   14086: 		   $cusymb%$cuname+
                   14087: 		   $cusymb%$cudom+
                   14088: 		   $cucourseid%$cuname+
                   14089: 		   $cucourseid%$cudom);
                   14090:     }
                   14091:     return $return;
1.76      www      14092: }
                   14093: 
                   14094: sub receipt {
1.474     albertel 14095:     my ($part)=@_;
1.790     albertel 14096:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 14097:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      14098: }
1.260     ng       14099: 
1.790     albertel 14100: sub whichuser {
                   14101:     my ($passedsymb)=@_;
                   14102:     my ($symb,$courseid,$domain,$name,$publicuser);
                   14103:     if (defined($env{'form.grade_symb'})) {
                   14104: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   14105: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   14106: 	if (!$allowed &&
                   14107: 	    exists($env{'request.course.sec'}) &&
                   14108: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   14109: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   14110: 			      '/'.$env{'request.course.sec'});
                   14111: 	}
                   14112: 	if ($allowed) {
                   14113: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   14114: 	    $courseid=$tmp_courseid;
                   14115: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   14116: 	    ($name)=&get_env_multiple('form.grade_username');
                   14117: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   14118: 	}
                   14119:     }
                   14120:     if (!$passedsymb) {
                   14121: 	$symb=&symbread();
                   14122:     } else {
                   14123: 	$symb=$passedsymb;
                   14124:     }
                   14125:     $courseid=$env{'request.course.id'};
                   14126:     $domain=$env{'user.domain'};
                   14127:     $name=$env{'user.name'};
                   14128:     if ($name eq 'public' && $domain eq 'public') {
                   14129: 	if (!defined($env{'form.username'})) {
                   14130: 	    $env{'form.username'}.=time.rand(10000000);
                   14131: 	}
                   14132: 	$name.=$env{'form.username'};
                   14133:     }
                   14134:     return ($symb,$courseid,$domain,$name,$publicuser);
                   14135: 
                   14136: }
                   14137: 
1.36      albertel 14138: # ------------------------------------------------------------ Serves up a file
1.472     albertel 14139: # returns either the contents of the file or 
                   14140: # -1 if the file doesn't exist
1.481     raeburn  14141: #
                   14142: # if the target is a file that was uploaded via DOCS, 
                   14143: # a check will be made to see if a current copy exists on the local server,
                   14144: # if it does this will be served, otherwise a copy will be retrieved from
                   14145: # the home server for the course and stored in /home/httpd/html/userfiles on
                   14146: # the local server.   
1.472     albertel 14147: 
1.36      albertel 14148: sub getfile {
1.538     albertel 14149:     my ($file) = @_;
1.609     banghart 14150:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 14151:     &repcopy($file);
                   14152:     return &readfile($file);
                   14153: }
                   14154: 
                   14155: sub repcopy_userfile {
                   14156:     my ($file)=@_;
1.1142    raeburn  14157:     my $londocroot = $perlvar{'lonDocRoot'};
                   14158:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  14159:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 14160:     my ($cdom,$cnum,$filename) = 
1.811     albertel 14161: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 14162:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   14163:     if (-e "$file") {
1.828     www      14164: # we already have a local copy, check it out
1.538     albertel 14165: 	my @fileinfo = stat($file);
1.828     www      14166: 	my $rtncode;
                   14167: 	my $info;
1.538     albertel 14168: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 14169: 	if ($lwpresp ne 'ok') {
1.828     www      14170: # there is no such file anymore, even though we had a local copy
1.482     albertel 14171: 	    if ($rtncode eq '404') {
1.538     albertel 14172: 		unlink($file);
1.482     albertel 14173: 	    }
                   14174: 	    return -1;
                   14175: 	}
                   14176: 	if ($info < $fileinfo[9]) {
1.828     www      14177: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  14178: 	    return 'ok';
1.828     www      14179: 	} else {
                   14180: # the file is outdated, get rid of it
                   14181: 	    unlink($file);
1.482     albertel 14182: 	}
1.828     www      14183:     }
                   14184: # one way or the other, at this point, we don't have the file
                   14185: # construct the correct path for the file
                   14186:     my @parts = ($cdom,$cnum); 
                   14187:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   14188: 	push @parts, split(/\//,$1);
                   14189:     }
                   14190:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   14191:     foreach my $part (@parts) {
                   14192: 	$path .= '/'.$part;
                   14193: 	if (!-e $path) {
                   14194: 	    mkdir($path,0770);
1.482     albertel 14195: 	}
                   14196:     }
1.828     www      14197: # now the path exists for sure
                   14198: # get a user agent
                   14199:     my $ua=new LWP::UserAgent;
                   14200:     my $transferfile=$file.'.in.transfer';
                   14201: # FIXME: this should flock
                   14202:     if (-e $transferfile) { return 'ok'; }
                   14203:     my $request;
                   14204:     $uri=~s/^\///;
1.980     raeburn  14205:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  14206:     my $hostname = &hostname($homeserver);
1.980     raeburn  14207:     my $protocol = $protocol{$homeserver};
                   14208:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  14209:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      14210:     my $response=$ua->request($request,$transferfile);
                   14211: # did it work?
                   14212:     if ($response->is_error()) {
                   14213: 	unlink($transferfile);
                   14214: 	&logthis("Userfile repcopy failed for $uri");
                   14215: 	return -1;
                   14216:     }
                   14217: # worked, rename the transfer file
                   14218:     rename($transferfile,$file);
1.607     raeburn  14219:     return 'ok';
1.481     raeburn  14220: }
                   14221: 
1.517     albertel 14222: sub tokenwrapper {
                   14223:     my $uri=shift;
1.980     raeburn  14224:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 14225:     $uri=~s|^/||;
1.620     albertel 14226:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 14227:     my $token=$1;
1.552     albertel 14228:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   14229:     if ($udom && $uname && $file) {
                   14230: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  14231:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  14232:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.120  raeburn  14233:         my $hostname = &hostname($homeserver);
1.980     raeburn  14234:         my $protocol = $protocol{$homeserver};
                   14235:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  14236:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 14237:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   14238:                                '&tokenissued='.$perlvar{'lonHostID'};
                   14239:     } else {
                   14240:         return '/adm/notfound.html';
                   14241:     }
                   14242: }
                   14243: 
1.828     www      14244: # call with reqtype HEAD: get last modification time
                   14245: # call with reqtype GET: get the file contents
                   14246: # Do not call this with reqtype GET for large files! It loads everything into memory
                   14247: #
1.481     raeburn  14248: sub getuploaded {
                   14249:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   14250:     $uri=~s/^\///;
1.980     raeburn  14251:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  14252:     my $hostname = &hostname($homeserver);
1.980     raeburn  14253:     my $protocol = $protocol{$homeserver};
                   14254:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  14255:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  14256:     my $ua=new LWP::UserAgent;
                   14257:     my $request=new HTTP::Request($reqtype,$uri);
                   14258:     my $response=$ua->request($request);
                   14259:     $$rtncode = $response->code;
1.482     albertel 14260:     if (! $response->is_success()) {
                   14261: 	return 'failed';
                   14262:     }      
                   14263:     if ($reqtype eq 'HEAD') {
1.486     www      14264: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 14265:     } elsif ($reqtype eq 'GET') {
                   14266: 	$$info = $response->content;
1.472     albertel 14267:     }
1.482     albertel 14268:     return 'ok';
1.36      albertel 14269: }
                   14270: 
1.481     raeburn  14271: sub readfile {
                   14272:     my $file = shift;
                   14273:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   14274:     my $fh;
1.1172.2.96  raeburn  14275:     open($fh,"<",$file);
1.481     raeburn  14276:     my $a='';
1.800     albertel 14277:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  14278:     return $a;
                   14279: }
                   14280: 
1.36      albertel 14281: sub filelocation {
1.590     banghart 14282:     my ($dir,$file) = @_;
                   14283:     my $location;
                   14284:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 14285: 
                   14286:     if ($file =~ m-^/adm/-) {
                   14287: 	$file=~s-^/adm/wrapper/-/-;
                   14288: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   14289:     }
1.882     albertel 14290: 
1.1139    www      14291:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  14292:         $location = $file;
1.609     banghart 14293:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 14294:         my ($udom,$uname,$filename)=
1.811     albertel 14295:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 14296:         my $home=&homeserver($uname,$udom);
                   14297:         my $is_me=0;
                   14298:         my @ids=&current_machine_ids();
                   14299:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   14300:         if ($is_me) {
1.1117    foxr     14301:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 14302:         } else {
                   14303:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   14304:   	      $udom.'/'.$uname.'/'.$filename;
                   14305:         }
1.882     albertel 14306:     } elsif ($file =~ m-^/adm/-) {
                   14307: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 14308:     } else {
                   14309:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      14310:         $file=~s:^/(res|priv)/:/:;
                   14311:         my $space=$1;
1.590     banghart 14312:         if ( !( $file =~ m:^/:) ) {
                   14313:             $location = $dir. '/'.$file;
                   14314:         } else {
1.1142    raeburn  14315:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 14316:         }
1.59      albertel 14317:     }
1.590     banghart 14318:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 14319:     while ($location=~m{/\.\./}) {
                   14320: 	if ($location =~ m{/[^/]+/\.\./}) {
                   14321: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   14322: 	} else {
                   14323: 	    $location=~ s{/\.\./}{/}g;
                   14324: 	}
                   14325:     } #remove dir/..
1.590     banghart 14326:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   14327:     return $location;
1.46      www      14328: }
1.36      albertel 14329: 
1.46      www      14330: sub hreflocation {
                   14331:     my ($dir,$file)=@_;
1.980     raeburn  14332:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 14333: 	$file=filelocation($dir,$file);
1.700     albertel 14334:     } elsif ($file=~m-^/adm/-) {
                   14335: 	$file=~s-^/adm/wrapper/-/-;
                   14336: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 14337:     }
                   14338:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   14339: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   14340:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  14341: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   14342: 	        {/uploaded/$1/$2/}x;
1.46      www      14343:     }
1.913     albertel 14344:     if ($file=~ m{^/userfiles/}) {
                   14345: 	$file =~ s{^/userfiles/}{/uploaded/};
                   14346:     }
1.462     albertel 14347:     return $file;
1.465     albertel 14348: }
                   14349: 
1.1139    www      14350: 
                   14351: 
                   14352: 
                   14353: 
1.465     albertel 14354: sub current_machine_domains {
1.853     albertel 14355:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   14356: }
                   14357: 
                   14358: sub machine_domains {
                   14359:     my ($hostname) = @_;
1.465     albertel 14360:     my @domains;
1.838     albertel 14361:     my %hostname = &all_hostnames();
1.465     albertel 14362:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  14363: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 14364: 	if ($hostname eq $name) {
1.844     albertel 14365: 	    push(@domains,&host_domain($id));
1.465     albertel 14366: 	}
                   14367:     }
                   14368:     return @domains;
                   14369: }
                   14370: 
                   14371: sub current_machine_ids {
1.853     albertel 14372:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   14373: }
                   14374: 
                   14375: sub machine_ids {
                   14376:     my ($hostname) = @_;
                   14377:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 14378:     my @ids;
1.888     albertel 14379:     my %name_to_host = &all_names();
1.889     albertel 14380:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   14381: 	return @{ $name_to_host{$hostname} };
                   14382:     }
                   14383:     return;
1.31      www      14384: }
                   14385: 
1.824     raeburn  14386: sub additional_machine_domains {
                   14387:     my @domains;
1.1172.2.142  raeburn  14388:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
                   14389:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
                   14390:             while( my $line = <$fh>) {
                   14391:                 chomp($line);
                   14392:                 $line =~ s/\s//g;
                   14393:                 push(@domains,$line);
                   14394:             }
                   14395:             close($fh);
                   14396:         }
1.824     raeburn  14397:     }
                   14398:     return @domains;
                   14399: }
                   14400: 
                   14401: sub default_login_domain {
                   14402:     my $domain = $perlvar{'lonDefDomain'};
                   14403:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   14404:     foreach my $posdom (&current_machine_domains(),
                   14405:                         &additional_machine_domains()) {
                   14406:         if (lc($posdom) eq lc($testdomain)) {
                   14407:             $domain=$posdom;
                   14408:             last;
                   14409:         }
                   14410:     }
                   14411:     return $domain;
                   14412: }
                   14413: 
1.1172.2.106  raeburn  14414: sub shared_institution {
1.1172.2.136  raeburn  14415:     my ($dom,$lonhost) = @_;
                   14416:     if ($lonhost eq '') {
                   14417:         $lonhost = $perlvar{'lonHostID'};
                   14418:     }
1.1172.2.106  raeburn  14419:     my $same_intdom;
1.1172.2.136  raeburn  14420:     my $hostintdom = &internet_dom($lonhost);
1.1172.2.106  raeburn  14421:     if ($hostintdom ne '') {
                   14422:         my %iphost = &get_iphost();
                   14423:         my $primary_id = &domain($dom,'primary');
                   14424:         my $primary_ip = &get_host_ip($primary_id);
                   14425:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   14426:             foreach my $id (@{$iphost{$primary_ip}}) {
                   14427:                 my $intdom = &internet_dom($id);
                   14428:                 if ($intdom eq $hostintdom) {
                   14429:                     $same_intdom = 1;
                   14430:                     last;
                   14431:                 }
                   14432:             }
                   14433:         }
                   14434:     }
                   14435:     return $same_intdom;
                   14436: }
                   14437: 
1.1172.2.120  raeburn  14438: sub uses_sts {
                   14439:     my ($ignore_cache) = @_;
                   14440:     my $lonhost = $perlvar{'lonHostID'};
                   14441:     my $hostname = &hostname($lonhost);
                   14442:     my $sts_on;
                   14443:     if ($protocol{$lonhost} eq 'https') {
                   14444:         my $cachetime = 12*3600;
                   14445:         if (!$ignore_cache) {
                   14446:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   14447:             if (defined($cached)) {
                   14448:                 return $sts_on;
                   14449:             }
                   14450:         }
1.1172.2.121  raeburn  14451:         my $ua=new LWP::UserAgent;
1.1172.2.120  raeburn  14452:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   14453:         my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121  raeburn  14454:         my $response=$ua->request($request);
1.1172.2.120  raeburn  14455:         if ($response->is_success) {
                   14456:             my $has_sts = $response->header('Strict-Transport-Security');
                   14457:             if ($has_sts eq '') {
                   14458:                 $sts_on = 0;
                   14459:             } else {
                   14460:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   14461:                     my $maxage = $1;
                   14462:                     if ($maxage) {
                   14463:                         $sts_on = 1;
                   14464:                     } else {
                   14465:                         $sts_on = 0;
                   14466:                     }
                   14467:                 } else {
                   14468:                     $sts_on = 0;
                   14469:                 }
                   14470:             }
                   14471:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   14472:         }
                   14473:     }
                   14474:     return;
                   14475: }
                   14476: 
1.1172.2.142  raeburn  14477: sub waf_allssl {
                   14478:     my ($host_name) = @_;
                   14479:     my $alias = &get_proxy_alias();
                   14480:     if ($host_name eq '') {
                   14481:         $host_name = $ENV{'SERVER_NAME'};
                   14482:     }
                   14483:     if (($host_name ne '') && ($alias eq $host_name)) {
                   14484:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
                   14485:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   14486:         if ($defdomdefaults{'waf_sslopt'}) {
                   14487:             return $defdomdefaults{'waf_sslopt'};
                   14488:         }
                   14489:     }
                   14490:     return;
                   14491: }
                   14492: 
1.1172.2.134  raeburn  14493: sub get_requestor_ip {
                   14494:     my ($r,$nolookup,$noproxy) = @_;
                   14495:     my $from_ip;
                   14496:     if (ref($r)) {
1.1172.2.142  raeburn  14497:         if ($r->can('useragent_ip')) {
                   14498:             if ($noproxy && $r->can('client_ip')) {
                   14499:                 $from_ip = $r->client_ip();
                   14500:             } else {
                   14501:                 $from_ip = $r->useragent_ip();
                   14502:             }
                   14503:         } elsif ($r->connection->can('remote_ip')) {
                   14504:             $from_ip = $r->connection->remote_ip();
                   14505:         } else {
                   14506:             $from_ip = $r->get_remote_host($nolookup);
                   14507:         }
1.1172.2.134  raeburn  14508:     } else {
                   14509:         $from_ip = $ENV{'REMOTE_ADDR'};
                   14510:     }
1.1172.2.142  raeburn  14511:     return $from_ip if ($noproxy);
                   14512:    # Who controls proxy settings for server
                   14513:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14514:     my $proxyinfo = &get_proxy_settings($dom_in_use);
                   14515:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
                   14516:         if ($proxyinfo->{'vpnint'}) {
                   14517:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
                   14518:                 return $from_ip;
                   14519:             }
                   14520:         }
                   14521:         if ($proxyinfo->{'trusted'}) {
                   14522:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
                   14523:                 my $ipheader = $proxyinfo->{'ipheader'};
                   14524:                 my ($ip,$xfor);
                   14525:                 if (ref($r)) {
                   14526:                     if ($ipheader) {
                   14527:                         $ip = $r->headers_in->{$ipheader};
                   14528:                     }
                   14529:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
                   14530:                 } else {
                   14531:                     if ($ipheader) {
                   14532:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
                   14533:                     }
                   14534:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
                   14535:                 }
                   14536:                 if (($ip eq '') && ($xfor ne '')) {
                   14537:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
                   14538:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
                   14539:                             $ip = $poss_ip;
                   14540:                             last;
                   14541:                         }
                   14542:                     }
                   14543:                 }
                   14544:                 if ($ip ne '') {
                   14545:                     return $ip;
                   14546:                 }
                   14547:             }
                   14548:         }
                   14549:     }
1.1172.2.134  raeburn  14550:     return $from_ip;
                   14551: }
                   14552: 
1.1172.2.142  raeburn  14553: sub get_proxy_settings {
                   14554:     my ($dom_in_use) = @_;
                   14555:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   14556:     my $proxyinfo = {
                   14557:                        ipheader => $domdefaults{'waf_ipheader'},
                   14558:                        trusted  => $domdefaults{'waf_trusted'},
                   14559:                        vpnint   => $domdefaults{'waf_vpnint'},
                   14560:                        vpnext   => $domdefaults{'waf_vpnext'},
                   14561:                        sslopt   => $domdefaults{'waf_sslopt'},
                   14562:                     };
                   14563:     return $proxyinfo;
                   14564: }
                   14565: 
                   14566: sub ip_match {
                   14567:     my ($ip,$pattern_str) = @_;
                   14568:     $ip=Net::CIDR::cidrvalidate($ip);
                   14569:     if ($ip) {
                   14570:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
                   14571:     }
                   14572:     return;
                   14573: }
                   14574: 
                   14575: sub get_proxy_alias {
                   14576:     my ($lonid) = @_;
                   14577:     if ($lonid eq '') {
                   14578:         $lonid = $perlvar{'lonHostID'};
                   14579:     }
                   14580:     if (!defined(&hostname($lonid))) {
                   14581:         return;
                   14582:     }
                   14583:     if ($lonid ne '') {
                   14584:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
                   14585:         if ($cached) {
                   14586:             return $alias;
                   14587:         }
                   14588:         my $dom = &Apache::lonnet::host_domain($lonid);
                   14589:         if ($dom ne '') {
                   14590:             my $cachetime = 60*60*24;
                   14591:             my %domconfig =
                   14592:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14593:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14594:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
                   14595:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
                   14596:                 }
                   14597:             }
                   14598:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
                   14599:         }
                   14600:     }
                   14601:     return;
                   14602: }
                   14603: 
                   14604: sub use_proxy_alias {
                   14605:     my ($r,$lonid) = @_;
                   14606:     my $alias = &get_proxy_alias($lonid);
                   14607:     if ($alias) {
                   14608:         my $dom = &host_domain($lonid);
                   14609:         if ($dom ne '') {
                   14610:             my $proxyinfo = &get_proxy_settings($dom);
                   14611:             my ($vpnint,$remote_ip);
                   14612:             if (ref($proxyinfo) eq 'HASH') {
                   14613:                 $vpnint = $proxyinfo->{'vpnint'};
                   14614:                 if ($vpnint) {
                   14615:                     $remote_ip = &get_requestor_ip($r,1,1);
                   14616:                 }
                   14617:             }
                   14618:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
                   14619:                 return $alias;
                   14620:             }
                   14621:         }
                   14622:     }
                   14623:     return;
                   14624: }
                   14625: 
                   14626: sub alias_sso {
                   14627:     my ($lonid) = @_;
                   14628:     if ($lonid eq '') {
                   14629:         $lonid = $perlvar{'lonHostID'};
                   14630:     }
                   14631:     if (!defined(&hostname($lonid))) {
                   14632:         return;
                   14633:     }
                   14634:     if ($lonid ne '') {
                   14635:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
                   14636:         if ($cached) {
                   14637:             return $use_alias;
                   14638:         }
                   14639:         my $dom = &Apache::lonnet::host_domain($lonid);
                   14640:         if ($dom ne '') {
                   14641:             my $cachetime = 60*60*24;
                   14642:             my %domconfig =
                   14643:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14644:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14645:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
                   14646:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
                   14647:                 }
                   14648:             }
                   14649:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
                   14650:         }
                   14651:     }
                   14652:     return;
                   14653: }
                   14654: 
                   14655: sub get_saml_landing {
                   14656:     my ($lonid) = @_;
                   14657:     if ($lonid eq '') {
                   14658:         my $defdom = &default_login_domain();
                   14659:         my @hosts = &current_machine_ids();
                   14660:         if (@hosts > 1) {
                   14661:             foreach my $hostid (@hosts) {
                   14662:                 if (&host_domain($hostid) eq $defdom) {
                   14663:                     $lonid = $hostid;
                   14664:                     last;
                   14665:                 }
                   14666:             }
                   14667:         } else {
                   14668:             $lonid = $perlvar{'lonHostID'};
                   14669:         }
                   14670:         if ($lonid) {
                   14671:             unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
                   14672:                 return;
                   14673:             }
                   14674:         } else {
                   14675:             return;
                   14676:         }
                   14677:     } elsif (!defined(&hostname($lonid))) {
                   14678:         return;
                   14679:     }
                   14680:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
                   14681:     if ($cached) {
                   14682:         return $landing;
                   14683:     }
                   14684:     my $dom = &Apache::lonnet::host_domain($lonid);
                   14685:     if ($dom ne '') {
                   14686:         my $cachetime = 60*60*24;
                   14687:         my %domconfig =
                   14688:             &Apache::lonnet::get_dom('configuration',['login'],$dom);
                   14689:         if (ref($domconfig{'login'}) eq 'HASH') {
                   14690:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
                   14691:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
                   14692:                     $landing = 1;
                   14693:                 }
                   14694:             }
                   14695:         }
                   14696:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
                   14697:     }
                   14698:     return;
                   14699: }
                   14700: 
1.31      www      14701: # ------------------------------------------------------------- Declutters URLs
                   14702: 
                   14703: sub declutter {
                   14704:     my $thisfn=shift;
1.569     albertel 14705:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  14706:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   14707:         $thisfn=~s{^/home/httpd/html}{};
                   14708:     }
1.31      www      14709:     $thisfn=~s/^\///;
1.697     albertel 14710:     $thisfn=~s|^adm/wrapper/||;
                   14711:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      14712:     $thisfn=~s/^res\///;
1.1172    bisitz   14713:     $thisfn=~s/^priv\///;
1.1032    raeburn  14714:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   14715:         $thisfn=~s/\?.+$//;
                   14716:     }
1.268     www      14717:     return $thisfn;
                   14718: }
                   14719: 
                   14720: # ------------------------------------------------------------- Clutter up URLs
                   14721: 
                   14722: sub clutter {
                   14723:     my $thisfn='/'.&declutter(shift);
1.887     albertel 14724:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 14725: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      14726:        $thisfn='/res'.$thisfn; 
                   14727:     }
1.1031    raeburn  14728:     if ($thisfn !~m|^/adm|) {
                   14729: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 14730: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 14731: 	} else {
                   14732: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   14733: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 14734: 	    if ($embstyle eq 'ssi'
                   14735: 		|| ($embstyle eq 'hdn')
                   14736: 		|| ($embstyle eq 'rat')
                   14737: 		|| ($embstyle eq 'prv')
                   14738: 		|| ($embstyle eq 'ign')) {
                   14739: 		#do nothing with these
                   14740: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 14741: 		|| ($embstyle eq 'emb')
                   14742: 		|| ($embstyle eq 'wrp')) {
                   14743: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 14744: 	    } elsif ($embstyle eq 'unk'
                   14745: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 14746: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 14747: 	    } else {
1.718     www      14748: #		&logthis("Got a blank emb style");
1.695     albertel 14749: 	    }
1.694     albertel 14750: 	}
1.1172.2.146.  .1(raebu 14751:22):     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
                   14752:22):         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 14753:     }
1.31      www      14754:     return $thisfn;
1.12      www      14755: }
                   14756: 
1.787     albertel 14757: sub clutter_with_no_wrapper {
                   14758:     my $uri = &clutter(shift);
                   14759:     if ($uri =~ m-^/adm/-) {
                   14760: 	$uri =~ s-^/adm/wrapper/-/-;
                   14761: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   14762:     }
                   14763:     return $uri;
                   14764: }
                   14765: 
1.557     albertel 14766: sub freeze_escape {
                   14767:     my ($value)=@_;
                   14768:     if (ref($value)) {
                   14769: 	$value=&nfreeze($value);
                   14770: 	return '__FROZEN__'.&escape($value);
                   14771:     }
                   14772:     return &escape($value);
                   14773: }
                   14774: 
1.11      www      14775: 
1.557     albertel 14776: sub thaw_unescape {
                   14777:     my ($value)=@_;
                   14778:     if ($value =~ /^__FROZEN__/) {
                   14779: 	substr($value,0,10,undef);
                   14780: 	$value=&unescape($value);
                   14781: 	return &thaw($value);
                   14782:     }
                   14783:     return &unescape($value);
                   14784: }
                   14785: 
1.436     albertel 14786: sub correct_line_ends {
                   14787:     my ($result)=@_;
                   14788:     $$result =~s/\r\n/\n/mg;
                   14789:     $$result =~s/\r/\n/mg;
1.415     albertel 14790: }
1.1       albertel 14791: # ================================================================ Main Program
                   14792: 
1.184     www      14793: sub goodbye {
1.204     albertel 14794:    &logthis("Starting Shut down");
1.443     albertel 14795: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 14796:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 14797: #converted
1.599     albertel 14798: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 14799:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   14800: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   14801: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 14802: #1.1 only
1.870     albertel 14803: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   14804: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   14805: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   14806: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   14807:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 14808:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   14809:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      14810:    &flushcourselogs();
                   14811:    &logthis("Shutting down");
                   14812: }
                   14813: 
1.852     albertel 14814: sub get_dns {
1.1172.2.17  raeburn  14815:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 14816:     if (!$ignore_cache) {
                   14817: 	my ($content,$cached)=
                   14818: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   14819: 	if ($cached) {
1.1172.2.17  raeburn  14820: 	    &$func($content,$hashref);
1.869     albertel 14821: 	    return;
                   14822: 	}
                   14823:     }
                   14824: 
                   14825:     my %alldns;
1.1172.2.96  raeburn  14826:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   14827:         foreach my $dns (<$config>) {
                   14828: 	    next if ($dns !~ /^\^(\S*)/x);
                   14829:             my $line = $1;
                   14830:             my ($host,$protocol) = split(/:/,$line);
                   14831:             if ($protocol ne 'https') {
                   14832:                 $protocol = 'http';
                   14833:             }
                   14834: 	    $alldns{$host} = $protocol;
1.979     raeburn  14835:         }
1.1172.2.96  raeburn  14836:         close($config);
1.869     albertel 14837:     }
                   14838:     while (%alldns) {
1.1172.2.52  raeburn  14839: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1172.2.142  raeburn  14840:         my @content;
                   14841:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
                   14842:             my $command = (split('/',$url))[3];
                   14843:             my ($dir,$file) = &parse_getdns_url($command,$url);
                   14844:             delete($alldns{$dns});
                   14845:             next if (($dir eq '') || ($file eq ''));
                   14846:             if (open(my $config,'<',"$dir/$file")) {
                   14847:                 @content = <$config>;
                   14848:                 close($config);
                   14849:             }
                   14850:         } else {
                   14851: 	    my $ua=new LWP::UserAgent;
                   14852:             $ua->timeout(30);
                   14853: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
                   14854: 	    my $response=$ua->request($request);
                   14855:             delete($alldns{$dns});
                   14856: 	    next if ($response->is_error());
                   14857: 	    @content = split("\n",$response->content);
                   14858:         }
1.1172.2.17  raeburn  14859:         unless ($nocache) {
1.1172.2.23  raeburn  14860: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  14861:         }
                   14862: 	&$func(\@content,$hashref);
1.869     albertel 14863: 	return;
1.852     albertel 14864:     }
1.871     albertel 14865:     my $which = (split('/',$url))[3];
                   14866:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  14867:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   14868:         my @content = <$config>;
                   14869:         &$func(\@content,$hashref);
                   14870:     }
1.1172.2.17  raeburn  14871:     return;
                   14872: }
                   14873: 
                   14874: # ------------------------------------------------------Get DNS checksums file
                   14875: sub parse_dns_checksums_tab {
                   14876:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  14877:     my $lonhost = $perlvar{'lonHostID'};
                   14878:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  14879:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  14880:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   14881:     my $webconfdir = '/etc/httpd/conf';
                   14882:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   14883:         $webconfdir = '/etc/apache2';
                   14884:     } elsif ($distro =~ /^sles(\d+)$/) {
                   14885:         if ($1 >= 10) {
                   14886:             $webconfdir = '/etc/apache2';
                   14887:         }
                   14888:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   14889:         if ($1 >= 10.0) {
                   14890:             $webconfdir = '/etc/apache2';
                   14891:         }
                   14892:     }
1.1172.2.17  raeburn  14893:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14894:     my (%chksum,%revnum);
                   14895:     if (ref($lines) eq 'ARRAY') {
                   14896:         chomp(@{$lines});
1.1172.2.34  raeburn  14897:         my $version = shift(@{$lines});
                   14898:         if ($version eq $release) {
1.1172.2.17  raeburn  14899:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  14900:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  14901:                 if ($file =~ m{^/etc/httpd/conf}) {
                   14902:                     if ($webconfdir eq '/etc/apache2') {
                   14903:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   14904:                     }
                   14905:                 }
1.1172.2.34  raeburn  14906:                 $chksum{$file} = $shasum;
                   14907:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  14908:             }
                   14909:             if (ref($hashref) eq 'HASH') {
                   14910:                 %{$hashref} = (
                   14911:                                 sums     => \%chksum,
                   14912:                                 versions => \%revnum,
                   14913:                               );
                   14914:             }
                   14915:         }
                   14916:     }
1.869     albertel 14917:     return;
1.852     albertel 14918: }
1.1172.2.17  raeburn  14919: 
                   14920: sub fetch_dns_checksums {
                   14921:     my %checksums;
1.1172.2.34  raeburn  14922:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  14923:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  14924:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14925:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  14926:              \%checksums);
                   14927:     return \%checksums;
                   14928: }
                   14929: 
1.1172.2.142  raeburn  14930: sub parse_getdns_url {
                   14931:     my ($command,$url) = @_;
                   14932:     my $dir = $perlvar{'lonTabDir'};
                   14933:     my $file;
                   14934:     if ($command eq 'hosts') {
                   14935:         $file = 'dns_hosts.tab';
                   14936:     } elsif ($command eq 'domain') {
                   14937:         $file = 'dns_domain.tab';
                   14938:     } elsif ($command eq 'checksums') {
                   14939:         my $version = (split('/',$url))[4];
                   14940:         $file = "dns_checksums/$version.tab",
                   14941:     }
                   14942:     return ($dir,$file);
                   14943: }
                   14944: 
1.327     albertel 14945: # ------------------------------------------------------------ Read domain file
                   14946: {
1.852     albertel 14947:     my $loaded;
1.846     albertel 14948:     my %domain;
                   14949: 
1.852     albertel 14950:     sub parse_domain_tab {
                   14951: 	my ($lines) = @_;
                   14952: 	foreach my $line (@$lines) {
                   14953: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      14954: 
1.846     albertel 14955: 	    chomp($line);
1.852     albertel 14956: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 14957: 	    my %this_domain;
                   14958: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   14959: 			       'lang_def', 'city', 'longi', 'lati',
                   14960: 			       'primary') {
                   14961: 		$this_domain{$field} = shift(@elements);
                   14962: 	    }
                   14963: 	    $domain{$name} = \%this_domain;
1.852     albertel 14964: 	}
                   14965:     }
1.864     albertel 14966: 
                   14967:     sub reset_domain_info {
                   14968: 	undef($loaded);
                   14969: 	undef(%domain);
                   14970:     }
                   14971: 
1.852     albertel 14972:     sub load_domain_tab {
1.1172.2.70  raeburn  14973: 	my ($ignore_cache,$nocache) = @_;
                   14974: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 14975: 	my $fh;
1.1172.2.96  raeburn  14976: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 14977: 	    my @lines = <$fh>;
                   14978: 	    &parse_domain_tab(\@lines);
1.448     albertel 14979: 	}
1.852     albertel 14980: 	close($fh);
                   14981: 	$loaded = 1;
1.327     albertel 14982:     }
1.846     albertel 14983: 
                   14984:     sub domain {
1.852     albertel 14985: 	&load_domain_tab() if (!$loaded);
                   14986: 
1.846     albertel 14987: 	my ($name,$what) = @_;
                   14988: 	return if ( !exists($domain{$name}) );
                   14989: 
                   14990: 	if (!$what) {
                   14991: 	    return $domain{$name}{'description'};
                   14992: 	}
                   14993: 	return $domain{$name}{$what};
                   14994:     }
1.974     raeburn  14995: 
                   14996:     sub domain_info {
                   14997:         &load_domain_tab() if (!$loaded);
                   14998:         return %domain;
                   14999:     }
                   15000: 
1.327     albertel 15001: }
                   15002: 
                   15003: 
1.1       albertel 15004: # ------------------------------------------------------------- Read hosts file
                   15005: {
1.838     albertel 15006:     my %hostname;
1.844     albertel 15007:     my %hostdom;
1.845     albertel 15008:     my %libserv;
1.852     albertel 15009:     my $loaded;
1.888     albertel 15010:     my %name_to_host;
1.1074    raeburn  15011:     my %internetdom;
1.1107    raeburn  15012:     my %LC_dns_serv;
1.852     albertel 15013: 
                   15014:     sub parse_hosts_tab {
                   15015: 	my ($file) = @_;
                   15016: 	foreach my $configline (@$file) {
                   15017: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  15018:             chomp($configline);
                   15019: 	    if ($configline =~ /^\^/) {
                   15020:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   15021:                     $LC_dns_serv{$1} = 1;
                   15022:                 }
                   15023:                 next;
                   15024:             }
1.1074    raeburn  15025: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 15026: 	    $name=~s/\s//g;
                   15027: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  15028:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   15029:                     my $curr = $hostname{$id};
                   15030:                     my $skip;
                   15031:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   15032:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   15033:                             $skip = 1;
                   15034:                         } else {
                   15035:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   15036:                         }
                   15037:                     }
                   15038:                     unless ($skip) {
                   15039:                         push(@{$name_to_host{$name}},$id);
                   15040:                     }
                   15041:                 } else {
                   15042:                     push(@{$name_to_host{$name}},$id);
                   15043:                 }
1.852     albertel 15044: 		$hostname{$id}=$name;
                   15045: 		$hostdom{$id}=$domain;
                   15046: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  15047:                 if (defined($protocol)) {
                   15048:                     if ($protocol eq 'https') {
                   15049:                         $protocol{$id} = $protocol;
                   15050:                     } else {
                   15051:                         $protocol{$id} = 'http'; 
                   15052:                     }
1.968     raeburn  15053:                 } else {
1.969     raeburn  15054:                     $protocol{$id} = 'http';
1.968     raeburn  15055:                 }
1.1074    raeburn  15056:                 if (defined($intdom)) {
                   15057:                     $internetdom{$id} = $intdom;
                   15058:                 }
1.852     albertel 15059: 	    }
                   15060: 	}
                   15061:     }
1.864     albertel 15062:     
                   15063:     sub reset_hosts_info {
1.897     albertel 15064: 	&purge_remembered();
1.864     albertel 15065: 	&reset_domain_info();
                   15066: 	&reset_hosts_ip_info();
1.892     albertel 15067: 	undef(%name_to_host);
1.864     albertel 15068: 	undef(%hostname);
                   15069: 	undef(%hostdom);
                   15070: 	undef(%libserv);
                   15071: 	undef($loaded);
                   15072:     }
1.1       albertel 15073: 
1.852     albertel 15074:     sub load_hosts_tab {
1.1172.2.70  raeburn  15075: 	my ($ignore_cache,$nocache) = @_;
                   15076: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  15077: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 15078: 	my @config = <$config>;
                   15079: 	&parse_hosts_tab(\@config);
                   15080: 	close($config);
                   15081: 	$loaded=1;
1.1       albertel 15082:     }
1.852     albertel 15083: 
1.838     albertel 15084:     sub hostname {
1.852     albertel 15085: 	&load_hosts_tab() if (!$loaded);
                   15086: 
1.838     albertel 15087: 	my ($lonid) = @_;
                   15088: 	return $hostname{$lonid};
                   15089:     }
1.845     albertel 15090: 
1.838     albertel 15091:     sub all_hostnames {
1.852     albertel 15092: 	&load_hosts_tab() if (!$loaded);
                   15093: 
1.838     albertel 15094: 	return %hostname;
                   15095:     }
1.845     albertel 15096: 
1.888     albertel 15097:     sub all_names {
1.1172.2.70  raeburn  15098:         my ($ignore_cache,$nocache) = @_;
                   15099: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 15100: 
                   15101: 	return %name_to_host;
                   15102:     }
                   15103: 
1.974     raeburn  15104:     sub all_host_domain {
                   15105:         &load_hosts_tab() if (!$loaded);
                   15106:         return %hostdom;
                   15107:     }
                   15108: 
1.845     albertel 15109:     sub is_library {
1.852     albertel 15110: 	&load_hosts_tab() if (!$loaded);
                   15111: 
1.845     albertel 15112: 	return exists($libserv{$_[0]});
                   15113:     }
                   15114: 
                   15115:     sub all_library {
1.852     albertel 15116: 	&load_hosts_tab() if (!$loaded);
                   15117: 
1.845     albertel 15118: 	return %libserv;
                   15119:     }
                   15120: 
1.1062    droeschl 15121:     sub unique_library {
                   15122: 	#2x reverse removes all hostnames that appear more than once
                   15123:         my %unique = reverse &all_library();
                   15124:         return reverse %unique;
                   15125:     }
                   15126: 
1.841     albertel 15127:     sub get_servers {
1.852     albertel 15128: 	&load_hosts_tab() if (!$loaded);
                   15129: 
1.841     albertel 15130: 	my ($domain,$type) = @_;
                   15131: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   15132: 	                                          : %hostname;
                   15133: 	my %result;
1.842     albertel 15134: 	if (ref($domain) eq 'ARRAY') {
                   15135: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 15136: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 15137: 		    $result{$host} = $hostname;
                   15138: 		}
                   15139: 	    }
                   15140: 	} else {
                   15141: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   15142: 		if ($hostdom{$host} eq $domain) {
                   15143: 		    $result{$host} = $hostname;
                   15144: 		}
1.841     albertel 15145: 	    }
                   15146: 	}
                   15147: 	return %result;
                   15148:     }
1.845     albertel 15149: 
1.1062    droeschl 15150:     sub get_unique_servers {
                   15151:         my %unique = reverse &get_servers(@_);
                   15152: 	return reverse %unique;
                   15153:     }
                   15154: 
1.844     albertel 15155:     sub host_domain {
1.852     albertel 15156: 	&load_hosts_tab() if (!$loaded);
                   15157: 
1.844     albertel 15158: 	my ($lonid) = @_;
                   15159: 	return $hostdom{$lonid};
                   15160:     }
                   15161: 
1.841     albertel 15162:     sub all_domains {
1.852     albertel 15163: 	&load_hosts_tab() if (!$loaded);
                   15164: 
1.841     albertel 15165: 	my %seen;
                   15166: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   15167: 	return @uniq;
                   15168:     }
1.1074    raeburn  15169: 
                   15170:     sub internet_dom {
                   15171:         &load_hosts_tab() if (!$loaded);
                   15172: 
                   15173:         my ($lonid) = @_;
                   15174:         return $internetdom{$lonid};
                   15175:     }
1.1107    raeburn  15176: 
                   15177:     sub is_LC_dns {
                   15178:         &load_hosts_tab() if (!$loaded);
                   15179: 
                   15180:         my ($hostname) = @_;
                   15181:         return exists($LC_dns_serv{$hostname});
                   15182:     }
                   15183: 
1.1       albertel 15184: }
                   15185: 
1.847     albertel 15186: { 
                   15187:     my %iphost;
1.856     albertel 15188:     my %name_to_ip;
                   15189:     my %lonid_to_ip;
1.869     albertel 15190: 
1.847     albertel 15191:     sub get_hosts_from_ip {
                   15192: 	my ($ip) = @_;
                   15193: 	my %iphosts = &get_iphost();
                   15194: 	if (ref($iphosts{$ip})) {
                   15195: 	    return @{$iphosts{$ip}};
                   15196: 	}
                   15197: 	return;
1.839     albertel 15198:     }
1.864     albertel 15199:     
                   15200:     sub reset_hosts_ip_info {
                   15201: 	undef(%iphost);
                   15202: 	undef(%name_to_ip);
                   15203: 	undef(%lonid_to_ip);
                   15204:     }
1.856     albertel 15205: 
                   15206:     sub get_host_ip {
                   15207: 	my ($lonid) = @_;
                   15208: 	if (exists($lonid_to_ip{$lonid})) {
                   15209: 	    return $lonid_to_ip{$lonid};
                   15210: 	}
                   15211: 	my $name=&hostname($lonid);
                   15212:    	my $ip = gethostbyname($name);
                   15213: 	return if (!$ip || length($ip) ne 4);
                   15214: 	$ip=inet_ntoa($ip);
                   15215: 	$name_to_ip{$name}   = $ip;
                   15216: 	$lonid_to_ip{$lonid} = $ip;
                   15217: 	return $ip;
                   15218:     }
1.847     albertel 15219:     
                   15220:     sub get_iphost {
1.1172.2.70  raeburn  15221: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 15222: 
1.869     albertel 15223: 	if (!$ignore_cache) {
                   15224: 	    if (%iphost) {
                   15225: 		return %iphost;
                   15226: 	    }
                   15227: 	    my ($ip_info,$cached)=
                   15228: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   15229: 	    if ($cached) {
                   15230: 		%iphost      = %{$ip_info->[0]};
                   15231: 		%name_to_ip  = %{$ip_info->[1]};
                   15232: 		%lonid_to_ip = %{$ip_info->[2]};
                   15233: 		return %iphost;
                   15234: 	    }
                   15235: 	}
1.894     albertel 15236: 
                   15237: 	# get yesterday's info for fallback
                   15238: 	my %old_name_to_ip;
                   15239: 	my ($ip_info,$cached)=
                   15240: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   15241: 	if ($cached) {
                   15242: 	    %old_name_to_ip = %{$ip_info->[1]};
                   15243: 	}
                   15244: 
1.1172.2.70  raeburn  15245: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 15246: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 15247: 	    my $ip;
                   15248: 	    if (!exists($name_to_ip{$name})) {
                   15249: 		$ip = gethostbyname($name);
                   15250: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 15251: 		    if (defined($old_name_to_ip{$name})) {
                   15252: 			$ip = $old_name_to_ip{$name};
                   15253: 			&logthis("Can't find $name defaulting to old $ip");
                   15254: 		    } else {
                   15255: 			&logthis("Name $name no IP found");
                   15256: 			next;
                   15257: 		    }
                   15258: 		} else {
                   15259: 		    $ip=inet_ntoa($ip);
1.847     albertel 15260: 		}
                   15261: 		$name_to_ip{$name} = $ip;
                   15262: 	    } else {
                   15263: 		$ip = $name_to_ip{$name};
1.653     albertel 15264: 	    }
1.888     albertel 15265: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   15266: 		$lonid_to_ip{$id} = $ip;
                   15267: 	    }
                   15268: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 15269: 	}
1.1172.2.70  raeburn  15270:         unless ($nocache) {
                   15271: 	    &do_cache_new('iphost','iphost',
                   15272: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   15273: 		          48*60*60);
                   15274:         }
1.869     albertel 15275: 
1.847     albertel 15276: 	return %iphost;
1.598     albertel 15277:     }
                   15278: 
1.992     raeburn  15279:     #
                   15280:     #  Given a DNS returns the loncapa host name for that DNS 
                   15281:     # 
                   15282:     sub host_from_dns {
                   15283:         my ($dns) = @_;
                   15284:         my @hosts;
                   15285:         my $ip;
                   15286: 
1.993     raeburn  15287:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  15288:             $ip = $name_to_ip{$dns};
                   15289:         }
                   15290:         if (!$ip) {
                   15291:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   15292:             if (length($ip) == 4) { 
                   15293: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   15294:             }
                   15295:         }
                   15296:         if ($ip) {
                   15297: 	    @hosts = get_hosts_from_ip($ip);
                   15298: 	    return $hosts[0];
                   15299:         }
                   15300:         return undef;
1.986     foxr     15301:     }
1.992     raeburn  15302: 
1.1074    raeburn  15303:     sub get_internet_names {
                   15304:         my ($lonid) = @_;
                   15305:         return if ($lonid eq '');
                   15306:         my ($idnref,$cached)=
                   15307:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   15308:         if ($cached) {
                   15309:             return $idnref;
                   15310:         }
                   15311:         my $ip = &get_host_ip($lonid);
                   15312:         my @hosts = &get_hosts_from_ip($ip);
                   15313:         my %iphost = &get_iphost();
                   15314:         my (@idns,%seen);
                   15315:         foreach my $id (@hosts) {
                   15316:             my $dom = &host_domain($id);
                   15317:             my $prim_id = &domain($dom,'primary');
                   15318:             my $prim_ip = &get_host_ip($prim_id);
                   15319:             next if ($seen{$prim_ip});
                   15320:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   15321:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   15322:                     my $intdom = &internet_dom($id);
                   15323:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   15324:                         push(@idns,$intdom);
                   15325:                     }
                   15326:                 }
                   15327:             }
                   15328:             $seen{$prim_ip} = 1;
                   15329:         }
1.1172.2.23  raeburn  15330:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  15331:     }
                   15332: 
1.986     foxr     15333: }
                   15334: 
1.1079    raeburn  15335: sub all_loncaparevs {
1.1172.2.39  raeburn  15336:     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  15337: }
                   15338: 
1.1172.2.27  raeburn  15339: # ------------------------------------------------------- Read loncaparev table
                   15340: {
                   15341:     sub load_loncaparevs {
                   15342:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  15343:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  15344:                 while (my $configline=<$config>) {
                   15345:                     chomp($configline);
                   15346:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   15347:                     $loncaparevs{$hostid}=$loncaparev;
                   15348:                 }
                   15349:                 close($config);
                   15350:             }
                   15351:         }
                   15352:     }
                   15353: }
                   15354: 
                   15355: # ----------------------------------------------------- Read serverhostID table
                   15356: {
                   15357:     sub load_serverhomeIDs {
                   15358:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  15359:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  15360:                 while (my $configline=<$config>) {
                   15361:                     chomp($configline);
                   15362:                     my ($name,$id)=split(/:/,$configline);
                   15363:                     $serverhomeIDs{$name}=$id;
                   15364:                 }
                   15365:                 close($config);
                   15366:             }
                   15367:         }
                   15368:     }
                   15369: }
                   15370: 
                   15371: 
1.862     albertel 15372: BEGIN {
                   15373: 
                   15374: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   15375:     unless ($readit) {
                   15376: {
                   15377:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   15378:     %perlvar = (%perlvar,%{$configvars});
                   15379: }
                   15380: 
                   15381: 
1.1       albertel 15382: # ------------------------------------------------------ Read spare server file
                   15383: {
1.1172.2.96  raeburn  15384:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 15385: 
                   15386:     while (my $configline=<$config>) {
                   15387:        chomp($configline);
1.284     matthew  15388:        if ($configline) {
1.784     albertel 15389: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 15390: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 15391: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 15392:        }
                   15393:     }
1.448     albertel 15394:     close($config);
1.1       albertel 15395: }
1.11      www      15396: # ------------------------------------------------------------ Read permissions
                   15397: {
1.1172.2.96  raeburn  15398:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      15399: 
                   15400:     while (my $configline=<$config>) {
1.448     albertel 15401: 	chomp($configline);
                   15402: 	if ($configline) {
                   15403: 	    my ($role,$perm)=split(/ /,$configline);
                   15404: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   15405: 	}
1.11      www      15406:     }
1.448     albertel 15407:     close($config);
1.11      www      15408: }
                   15409: 
                   15410: # -------------------------------------------- Read plain texts for permissions
                   15411: {
1.1172.2.96  raeburn  15412:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      15413: 
                   15414:     while (my $configline=<$config>) {
1.448     albertel 15415: 	chomp($configline);
                   15416: 	if ($configline) {
1.742     raeburn  15417: 	    my ($short,@plain)=split(/:/,$configline);
                   15418:             %{$prp{$short}} = ();
                   15419: 	    if (@plain > 0) {
                   15420:                 $prp{$short}{'std'} = $plain[0];
                   15421:                 for (my $i=1; $i<@plain; $i++) {
                   15422:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   15423:                 }
                   15424:             }
1.448     albertel 15425: 	}
1.135     www      15426:     }
1.448     albertel 15427:     close($config);
1.135     www      15428: }
                   15429: 
                   15430: # ---------------------------------------------------------- Read package table
                   15431: {
1.1172.2.96  raeburn  15432:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      15433: 
                   15434:     while (my $configline=<$config>) {
1.483     albertel 15435: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 15436: 	chomp($configline);
                   15437: 	my ($short,$plain)=split(/:/,$configline);
                   15438: 	my ($pack,$name)=split(/\&/,$short);
                   15439: 	if ($plain ne '') {
                   15440: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   15441: 	    $packagetab{$short}=$plain; 
                   15442: 	}
1.11      www      15443:     }
1.448     albertel 15444:     close($config);
1.329     matthew  15445: }
                   15446: 
1.1172.2.27  raeburn  15447: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  15448: 
1.1172.2.27  raeburn  15449: &load_loncaparevs();
                   15450: 
                   15451: # ------------------------------------------------------- Read serverhostID table
                   15452: 
                   15453: &load_serverhomeIDs();
1.1074    raeburn  15454: 
1.1172.2.27  raeburn  15455: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  15456: {
                   15457:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   15458:     if (-e $file) {
                   15459:         my $parser = HTML::LCParser->new($file);
                   15460:         while (my $token = $parser->get_token()) {
                   15461:             if ($token->[0] eq 'S') {
                   15462:                 my $item = $token->[1];
                   15463:                 my $name = $token->[2]{'name'};
                   15464:                 my $value = $token->[2]{'value'};
                   15465:                 if ($item ne '' && $name ne '' && $value ne '') {
                   15466:                     my $release = $parser->get_text();
                   15467:                     $release =~ s/(^\s*|\s*$ )//gx;
                   15468:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   15469:                 }
                   15470:             }
                   15471:         }
                   15472:     }
1.1073    raeburn  15473: }
                   15474: 
1.1138    raeburn  15475: # ---------------------------------------------------------- Read managers table
                   15476: {
                   15477:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  15478:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  15479:             while (my $configline=<$config>) {
                   15480:                 chomp($configline);
                   15481:                 next if ($configline =~ /^\#/);
                   15482:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   15483:                     $managerstab{$configline} = 1;
                   15484:                 }
                   15485:             }
                   15486:             close($config);
                   15487:         }
                   15488:     }
                   15489: }
                   15490: 
1.329     matthew  15491: # ------------- set up temporary directory
                   15492: {
1.1117    foxr     15493:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  15494: 
1.11      www      15495: }
                   15496: 
1.1172.2.104  raeburn  15497: # ------------- set default texengine (domain default overrides this)
                   15498: {
                   15499:     $deftex = LONCAPA::texengine();
                   15500: }
                   15501: 
1.1172.2.114  raeburn  15502: # ------------- set default minimum length for passwords for internal auth users
                   15503: {
                   15504:     $passwdmin = LONCAPA::passwd_min();
                   15505: }
                   15506: 
1.794     albertel 15507: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   15508: 				'compress_threshold'=> 20_000,
                   15509:  			        });
1.185     www      15510: 
1.281     www      15511: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      15512: $dumpcount=0;
1.958     www      15513: $locknum=0;
1.22      www      15514: 
1.163     harris41 15515: &logtouch();
1.672     albertel 15516: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      15517: $readit=1;
1.564     albertel 15518:     {
                   15519: 	use integer;
                   15520: 	my $test=(2**32)+1;
1.568     albertel 15521: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 15522: 	&logthis(" Detected 64bit platform ($_64bit)");
                   15523:     }
1.195     www      15524: }
1.1       albertel 15525: }
1.179     www      15526: 
1.1       albertel 15527: 1;
1.191     harris41 15528: __END__
                   15529: 
1.243     albertel 15530: =pod
                   15531: 
1.191     harris41 15532: =head1 NAME
                   15533: 
1.243     albertel 15534: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 15535: 
                   15536: =head1 SYNOPSIS
                   15537: 
1.243     albertel 15538: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 15539: 
                   15540:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   15541: 
1.243     albertel 15542: Common parameters:
                   15543: 
                   15544: =over 4
                   15545: 
                   15546: =item *
                   15547: 
                   15548: $uname : an internal username (if $cname expecting a course Id specifically)
                   15549: 
                   15550: =item *
                   15551: 
                   15552: $udom : a domain (if $cdom expecting a course's domain specifically)
                   15553: 
                   15554: =item *
                   15555: 
                   15556: $symb : a resource instance identifier
                   15557: 
                   15558: =item *
                   15559: 
                   15560: $namespace : the name of a .db file that contains the data needed or
                   15561: being set.
                   15562: 
                   15563: =back
                   15564: 
1.394     bowersj2 15565: =head1 OVERVIEW
1.191     harris41 15566: 
1.394     bowersj2 15567: lonnet provides subroutines which interact with the
                   15568: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   15569: about classes, users, and resources.
1.243     albertel 15570: 
                   15571: For many of these objects you can also use this to store data about
                   15572: them or modify them in various ways.
1.191     harris41 15573: 
1.394     bowersj2 15574: =head2 Symbs
1.191     harris41 15575: 
1.394     bowersj2 15576: To identify a specific instance of a resource, LON-CAPA uses symbols
                   15577: or "symbs"X<symb>. These identifiers are built from the URL of the
                   15578: map, the resource number of the resource in the map, and the URL of
                   15579: the resource itself. The latter is somewhat redundant, but might help
                   15580: if maps change.
                   15581: 
                   15582: An example is
                   15583: 
                   15584:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   15585: 
                   15586: The respective map entry is
                   15587: 
                   15588:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   15589:   title="Problem 2">
                   15590:  </resource>
                   15591: 
                   15592: Symbs are used by the random number generator, as well as to store and
                   15593: restore data specific to a certain instance of for example a problem.
                   15594: 
                   15595: =head2 Storing And Retrieving Data
                   15596: 
                   15597: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   15598: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   15599: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   15600: is is the non-critical message twin of cstore. These functions are for
                   15601: handlers to store a perl hash to a user's permanent data space in an
                   15602: easy manner, and to retrieve it again on another call. It is expected
                   15603: that a handler would use this once at the beginning to retrieve data,
                   15604: and then again once at the end to send only the new data back.
                   15605: 
                   15606: The data is stored in the user's data directory on the user's
                   15607: homeserver under the ID of the course.
                   15608: 
                   15609: The hash that is returned by restore will have all of the previous
                   15610: value for all of the elements of the hash.
                   15611: 
                   15612: Example:
                   15613: 
                   15614:  #creating a hash
                   15615:  my %hash;
                   15616:  $hash{'foo'}='bar';
                   15617: 
                   15618:  #storing it
                   15619:  &Apache::lonnet::cstore(\%hash);
                   15620: 
                   15621:  #changing a value
                   15622:  $hash{'foo'}='notbar';
                   15623: 
                   15624:  #adding a new value
                   15625:  $hash{'bar'}='foo';
                   15626:  &Apache::lonnet::cstore(\%hash);
                   15627: 
                   15628:  #retrieving the hash
                   15629:  my %history=&Apache::lonnet::restore();
                   15630: 
                   15631:  #print the hash
                   15632:  foreach my $key (sort(keys(%history))) {
                   15633:    print("\%history{$key} = $history{$key}");
                   15634:  }
                   15635: 
                   15636: Will print out:
1.191     harris41 15637: 
1.394     bowersj2 15638:  %history{1:foo} = bar
                   15639:  %history{1:keys} = foo:timestamp
                   15640:  %history{1:timestamp} = 990455579
                   15641:  %history{2:bar} = foo
                   15642:  %history{2:foo} = notbar
                   15643:  %history{2:keys} = foo:bar:timestamp
                   15644:  %history{2:timestamp} = 990455580
                   15645:  %history{bar} = foo
                   15646:  %history{foo} = notbar
                   15647:  %history{timestamp} = 990455580
                   15648:  %history{version} = 2
                   15649: 
                   15650: Note that the special hash entries C<keys>, C<version> and
                   15651: C<timestamp> were added to the hash. C<version> will be equal to the
                   15652: total number of versions of the data that have been stored. The
                   15653: C<timestamp> attribute will be the UNIX time the hash was
                   15654: stored. C<keys> is available in every historical section to list which
                   15655: keys were added or changed at a specific historical revision of a
                   15656: hash.
                   15657: 
                   15658: B<Warning>: do not store the hash that restore returns directly. This
                   15659: will cause a mess since it will restore the historical keys as if the
                   15660: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 15661: 
1.394     bowersj2 15662: Calling convention:
1.191     harris41 15663: 
1.1172.2.27  raeburn  15664:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  15665:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 15666: 
1.394     bowersj2 15667: For more detailed information, see lonnet specific documentation.
1.191     harris41 15668: 
1.394     bowersj2 15669: =head1 RETURN MESSAGES
1.191     harris41 15670: 
1.394     bowersj2 15671: =over 4
1.191     harris41 15672: 
1.394     bowersj2 15673: =item * B<con_lost>: unable to contact remote host
1.191     harris41 15674: 
1.394     bowersj2 15675: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   15676: when the connection is brought back up
1.191     harris41 15677: 
1.394     bowersj2 15678: =item * B<con_failed>: unable to contact remote host and unable to save message
                   15679: for later delivery
1.191     harris41 15680: 
1.967     bisitz   15681: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 15682: 
1.394     bowersj2 15683: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 15684: that was requested
1.191     harris41 15685: 
1.243     albertel 15686: =back
1.191     harris41 15687: 
1.243     albertel 15688: =head1 PUBLIC SUBROUTINES
1.191     harris41 15689: 
1.243     albertel 15690: =head2 Session Environment Functions
1.191     harris41 15691: 
1.243     albertel 15692: =over 4
1.191     harris41 15693: 
1.394     bowersj2 15694: =item * 
                   15695: X<appenv()>
1.949     raeburn  15696: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 15697: the user envirnoment file, and will be restored for each access this
1.620     albertel 15698: user makes during this session, also modifies the %env for the current
1.949     raeburn  15699: process. Optional rolesarrayref - if defined contains a reference to an array
                   15700: of roles which are exempt from the restriction on modifying user.role entries 
                   15701: in the user's environment.db and in %env.    
1.191     harris41 15702: 
                   15703: =item *
1.394     bowersj2 15704: X<delenv()>
1.987     raeburn  15705: B<delenv($delthis,$regexp)>: removes all items from the session
                   15706: environment file that begin with $delthis. If the 
                   15707: optional second arg - $regexp - is true, $delthis is treated as a 
                   15708: regular expression, otherwise \Q$delthis\E is used. 
                   15709: The values are also deleted from the current processes %env.
1.191     harris41 15710: 
1.795     albertel 15711: =item * get_env_multiple($name) 
                   15712: 
                   15713: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   15714: values may be defined and end up as an array ref.
                   15715: 
                   15716: returns an array of values
                   15717: 
1.243     albertel 15718: =back
                   15719: 
                   15720: =head2 User Information
1.191     harris41 15721: 
1.243     albertel 15722: =over 4
1.191     harris41 15723: 
                   15724: =item *
1.394     bowersj2 15725: X<queryauthenticate()>
                   15726: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 15727: authentication scheme
                   15728: 
                   15729: =item *
1.394     bowersj2 15730: X<authenticate()>
1.1073    raeburn  15731: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 15732: authenticate user from domain's lib servers (first use the current
                   15733: one). C<$upass> should be the users password.
1.1073    raeburn  15734: $checkdefauth is optional (value is 1 if a check should be made to
                   15735:    authenticate user using default authentication method, and allow
                   15736:    account creation if username does not have account in the domain).
                   15737: $clientcancheckhost is optional (value is 1 if checking whether the
                   15738:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 15739: 
                   15740: =item *
1.394     bowersj2 15741: X<homeserver()>
                   15742: B<homeserver($uname,$udom)>: find the server which has
                   15743: the user's directory and files (there must be only one), this caches
                   15744: the answer, and also caches if there is a borken connection.
1.191     harris41 15745: 
                   15746: =item *
1.394     bowersj2 15747: X<idget()>
                   15748: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   15749: (IDs are a unique resource in a domain, there must be only 1 ID per
                   15750: username, and only 1 username per ID in a specific domain) (returns
                   15751: hash: id=>name,id=>name)
1.191     harris41 15752: 
                   15753: =item *
1.394     bowersj2 15754: X<idrget()>
                   15755: B<idrget($udom,@unames)>: find the IDs behind a list of
                   15756: usernames (returns hash: name=>id,name=>id)
1.191     harris41 15757: 
                   15758: =item *
1.394     bowersj2 15759: X<idput()>
                   15760: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 15761: 
                   15762: =item *
1.394     bowersj2 15763: X<rolesinit()>
1.1169    droeschl 15764: B<rolesinit($udom,$username)>: get user privileges.
                   15765: returns user role, first access and timer interval hashes
1.243     albertel 15766: 
                   15767: =item *
1.1171    droeschl 15768: X<privileged()>
                   15769: B<privileged($username,$domain)>: returns a true if user has a
                   15770: privileged and active role (i.e. su or dc), false otherwise.
                   15771: 
                   15772: =item *
1.551     albertel 15773: X<getsection()>
                   15774: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 15775: course $cname, return section name/number or '' for "not in course"
                   15776: and '-1' for "no section"
                   15777: 
                   15778: =item *
1.394     bowersj2 15779: X<userenvironment()>
                   15780: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 15781: passed in @what from the requested user's environment, returns a hash
                   15782: 
1.858     raeburn  15783: =item * 
                   15784: X<userlog_query()>
1.859     albertel 15785: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   15786: activity.log file. %filters defines filters applied when parsing the
                   15787: log file. These can be start or end timestamps, or the type of action
                   15788: - log to look for Login or Logout events, check for Checkin or
                   15789: Checkout, role for role selection. The response is in the form
                   15790: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   15791: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  15792: 
1.243     albertel 15793: =back
                   15794: 
                   15795: =head2 User Roles
                   15796: 
                   15797: =over 4
                   15798: 
                   15799: =item *
                   15800: 
1.1172.2.65  raeburn  15801: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   15802: returns codes for allowed actions.
                   15803: 
                   15804: The first argument is required, all others are optional.
                   15805: 
                   15806: $priv is the privilege being checked.
                   15807: $uri contains additional information about what is being checked for access (e.g.,
                   15808: URL, course ID etc.).
                   15809: $symb is the unique resource instance identifier in a course; if needed,
                   15810: but not provided, it will be retrieved via a call to &symbread().
                   15811: $role is the role for which a priv is being checked (only used if priv is evb).
                   15812: $clientip is the user's IP address (only used when checking for access to portfolio
                   15813: files).
                   15814: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   15815: prevents recursive calls to &allowed.
                   15816: 
1.243     albertel 15817:  F: full access
                   15818:  U,I,K: authentication modes (cxx only)
                   15819:  '': forbidden
                   15820:  1: user needs to choose course
                   15821:  2: browse allowed
1.766     albertel 15822:  A: passphrase authentication needed
1.1172.2.65  raeburn  15823:  B: access temporarily blocked because of a blocking event in a course.
1.1172.2.146.  .1(raebu 15824:22):  D: access blocked because access is required via session initiated via deep-link
1.243     albertel 15825: 
                   15826: =item *
                   15827: 
1.1172.2.13  raeburn  15828: constructaccess($url,$setpriv) : check for access to construction space URL
                   15829: 
                   15830: See if the owner domain and name in the URL match those in the
                   15831: expected environment.  If so, return three element list
                   15832: ($ownername,$ownerdomain,$ownerhome).
                   15833: 
                   15834: Otherwise return the null string.
                   15835: 
                   15836: If second argument 'setpriv' is true, it assigns the privileges,
                   15837: and returns the same three element list, unless the owner has
                   15838: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   15839: in which case the null string is returned.
                   15840: 
                   15841: =item *
                   15842: 
1.1172.2.84  raeburn  15843: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   15844: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   15845: for system, domain, and course level. $uname and $udom are optional (current
                   15846: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 15847: 
                   15848: =item *
                   15849: 
1.988     raeburn  15850: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   15851: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  15852: $type is Course (default) or Community.
1.988     raeburn  15853: If $forcedefault evaluates to true, text returned will be default 
                   15854: text for $type. Otherwise, if this is a course, the text returned 
                   15855: will be a custom name for the role (if defined in the course's 
                   15856: environment).  If no custom name is defined the default is returned.
                   15857:    
1.832     raeburn  15858: =item *
                   15859: 
1.1172.2.23  raeburn  15860: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  15861: All arguments are optional. Returns a hash of a roles, either for
                   15862: co-author/assistant author roles for a user's Construction Space
1.906     albertel 15863: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  15864: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   15865: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   15866: For each key, value is set to colon-separated start and end times for
                   15867: the role.  If no username and domain are specified, will default to
1.934     raeburn  15868: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  15869: of role statuses (active, future or previous), roles 
                   15870: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   15871: to restrict the list of roles reported. If no array ref is 
                   15872: provided for types, will default to return only active roles.
1.834     albertel 15873: 
1.1172.2.13  raeburn  15874: =item *
                   15875: 
                   15876: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   15877: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   15878: 
                   15879: Additional optional arguments are: $type (if role checking is to be restricted
                   15880: to certain user status types -- previous (expired roles), active (currently
                   15881: available roles) or future (roles available in the future), and
                   15882: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  15883: have active Domain Coordinator role in course's domain or in additional
                   15884: domains (specified in 'Domains to check for privileged users' in course
                   15885: environment -- set via:  Course Settings -> Classlists and staff listing).
                   15886: 
                   15887: =item *
                   15888: 
                   15889: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   15890: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   15891: $possdomains and $possroles are optional array refs -- to domains to check and
                   15892: roles to check.  If $possdomains is not specified, a dump will be done of the
                   15893: users' roles.db to check for a dc or su role in any domain. This can be
                   15894: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   15895: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   15896: this then allows &privileged_by_domain() to be used, which caches the identity
                   15897: of privileged users, eliminating the need for repeated calls to &dump().
                   15898: 
                   15899: =item *
                   15900: 
                   15901: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   15902: where the outer hash keys are domains specified in the $possdomains array ref,
                   15903: next inner hash keys are privileged roles specified in the $roles array ref,
                   15904: and the innermost hash contains key = value pairs for username:domain = end:start
                   15905: for active or future "privileged" users with that role in that domain. To avoid
                   15906: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   15907: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  15908: 
1.243     albertel 15909: =back
                   15910: 
                   15911: =head2 User Modification
                   15912: 
                   15913: =over 4
                   15914: 
                   15915: =item *
                   15916: 
1.957     raeburn  15917: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 15918: user for the level given by URL.  Optional start and end dates (leave empty
                   15919: string or zero for "no date")
1.191     harris41 15920: 
                   15921: =item *
                   15922: 
1.243     albertel 15923: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   15924: change a users, password, possible return values are: ok,
                   15925: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   15926: refused
1.191     harris41 15927: 
                   15928: =item *
                   15929: 
1.243     albertel 15930: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 15931: 
                   15932: =item *
                   15933: 
1.1058    raeburn  15934: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   15935:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   15936: 
                   15937: will update user information (firstname,middlename,lastname,generation,
                   15938: permanentemail), and if forceid is true, student/employee ID also.
                   15939: A user's institutional affiliation(s) can also be updated.
                   15940: User information fields will not be overwritten with empty entries 
                   15941: unless the field is included in the $candelete array reference.
                   15942: This array is included when a single user is modified via "Manage Users",
                   15943: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 15944: 
                   15945: =item *
                   15946: 
1.286     matthew  15947: modifystudent
                   15948: 
1.957     raeburn  15949: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  15950: The course id is resolved based on the current user's environment.  
                   15951: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  15952: associated with a course.
                   15953: 
1.297     matthew  15954: This call is essentially a wrapper for lonnet::modifyuser and
                   15955: lonnet::modify_student_enrollment
1.286     matthew  15956: 
                   15957: Inputs: 
                   15958: 
                   15959: =over 4
                   15960: 
1.957     raeburn  15961: =item B<$udom> Student's loncapa domain
1.286     matthew  15962: 
1.957     raeburn  15963: =item B<$uname> Student's loncapa login name
1.286     matthew  15964: 
1.964     bisitz   15965: =item B<$uid> Student/Employee ID
1.286     matthew  15966: 
1.957     raeburn  15967: =item B<$umode> Student's authentication mode
1.286     matthew  15968: 
1.957     raeburn  15969: =item B<$upass> Student's password
1.286     matthew  15970: 
1.957     raeburn  15971: =item B<$first> Student's first name
1.286     matthew  15972: 
1.957     raeburn  15973: =item B<$middle> Student's middle name
1.286     matthew  15974: 
1.957     raeburn  15975: =item B<$last> Student's last name
1.286     matthew  15976: 
1.957     raeburn  15977: =item B<$gene> Student's generation
1.286     matthew  15978: 
1.957     raeburn  15979: =item B<$usec> Student's section in course
1.286     matthew  15980: 
                   15981: =item B<$end> Unix time of the roles expiration
                   15982: 
                   15983: =item B<$start> Unix time of the roles start date
                   15984: 
                   15985: =item B<$forceid> If defined, allow $uid to be changed
                   15986: 
                   15987: =item B<$desiredhome> server to use as home server for student
                   15988: 
1.957     raeburn  15989: =item B<$email> Student's permanent e-mail address
                   15990: 
                   15991: =item B<$type> Type of enrollment (auto or manual)
                   15992: 
1.963     raeburn  15993: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   15994: 
                   15995: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  15996: 
1.963     raeburn  15997: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  15998: 
1.963     raeburn  15999: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  16000: 
1.1172.2.19  raeburn  16001: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   16002: 
                   16003: =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  16004: 
1.286     matthew  16005: =back
1.297     matthew  16006: 
                   16007: =item *
                   16008: 
                   16009: modify_student_enrollment
                   16010: 
1.1172.2.31  raeburn  16011: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  16012: 'role.request.course' must be defined for this function to proceed.
                   16013: 
                   16014: Inputs:
                   16015: 
                   16016: =over 4
                   16017: 
1.1172.2.31  raeburn  16018: =item $udom, student's domain
1.297     matthew  16019: 
1.1172.2.31  raeburn  16020: =item $uname, student's name
1.297     matthew  16021: 
1.1172.2.31  raeburn  16022: =item $uid, student's user id
1.297     matthew  16023: 
1.1172.2.31  raeburn  16024: =item $first, student's first name
1.297     matthew  16025: 
                   16026: =item $middle
                   16027: 
                   16028: =item $last
                   16029: 
                   16030: =item $gene
                   16031: 
                   16032: =item $usec
                   16033: 
                   16034: =item $end
                   16035: 
                   16036: =item $start
                   16037: 
1.957     raeburn  16038: =item $type
                   16039: 
                   16040: =item $locktype
                   16041: 
                   16042: =item $cid
                   16043: 
                   16044: =item $selfenroll
                   16045: 
                   16046: =item $context
                   16047: 
1.1172.2.19  raeburn  16048: =item $credits, number of credits student will earn from this class
                   16049: 
1.1172.2.76  raeburn  16050: =item $instsec, institutional course section code for student
                   16051: 
1.297     matthew  16052: =back
                   16053: 
1.191     harris41 16054: 
                   16055: =item *
                   16056: 
1.243     albertel 16057: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   16058: custom role; give a custom role to a user for the level given by URL.  Specify
                   16059: name and domain of role author, and role name
1.191     harris41 16060: 
                   16061: =item *
                   16062: 
1.243     albertel 16063: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 16064: 
                   16065: =item *
                   16066: 
1.243     albertel 16067: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   16068: 
                   16069: =back
                   16070: 
                   16071: =head2 Course Infomation
                   16072: 
                   16073: =over 4
1.191     harris41 16074: 
                   16075: =item *
                   16076: 
1.1118    foxr     16077: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 16078: specified course id, including all environment settings for the
                   16079: course, the description of the course will be in the hash under the
                   16080: key 'description'
1.191     harris41 16081: 
1.1118    foxr     16082: $options is an optional parameter that if supplied is a hash reference that controls
                   16083: what how this function works.  It has the following key/values:
                   16084: 
                   16085: =over 4
                   16086: 
                   16087: =item freshen_cache
                   16088: 
                   16089: If defined, and the environment cache for the course is valid, it is 
                   16090: returned in the returned hash.
                   16091: 
                   16092: =item one_time
                   16093: 
                   16094: If defined, the last cache time is set to _now_
                   16095: 
                   16096: =item user
                   16097: 
                   16098: If defined, the supplied username is used instead of the current user.
                   16099: 
                   16100: 
                   16101: =back
                   16102: 
1.191     harris41 16103: =item *
                   16104: 
1.624     albertel 16105: resdata($name,$domain,$type,@which) : request for current parameter
                   16106: setting for a specific $type, where $type is either 'course' or 'user',
                   16107: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  16108: answers for 10 minutes.
1.243     albertel 16109: 
1.877     foxr     16110: =item *
                   16111: 
                   16112: get_courseresdata($courseid, $domain) : dump the entire course resource
                   16113: data base, returning a hash that is keyed by the resource name and has
                   16114: values that are the resource value.  I believe that the timestamps and
                   16115: versions are also returned.
                   16116: 
1.243     albertel 16117: =back
                   16118: 
                   16119: =head2 Course Modification
                   16120: 
                   16121: =over 4
1.191     harris41 16122: 
                   16123: =item *
                   16124: 
1.243     albertel 16125: writecoursepref($courseid,%prefs) : write preferences (environment
                   16126: database) for a course
1.191     harris41 16127: 
                   16128: =item *
                   16129: 
1.1011    raeburn  16130: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   16131: 
                   16132: =item *
                   16133: 
1.1038    raeburn  16134: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 16135: 
1.1167    droeschl 16136: =item *
                   16137: 
                   16138: is_course($courseid), is_course($cdom, $cnum)
                   16139: 
                   16140: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   16141: two component version $cdom, $cnum. It checks if the specified course exists.
                   16142: 
                   16143: Returns:
                   16144:     undef if the course doesn't exist, otherwise
                   16145:     in scalar context the combined courseid.
                   16146:     in list context the two components of the course identifier, domain and 
                   16147:     courseid.    
                   16148: 
1.243     albertel 16149: =back
                   16150: 
1.1172.2.109  raeburn  16151: =head2 Bubblesheet Configuration
                   16152: 
                   16153: =over 4
                   16154: 
                   16155: =item *
                   16156: 
                   16157: get_scantron_config($which)
                   16158: 
                   16159: $which - the name of the configuration to parse from the file.
                   16160: 
                   16161: Parses and returns the bubblesheet configuration line selected as a
                   16162: hash of configuration file fields.
                   16163: 
                   16164: 
                   16165: Returns:
                   16166:     If the named configuration is not in the file, an empty
                   16167:     hash is returned.
                   16168: 
                   16169:     a hash with the fields
                   16170:       name         - internal name for the this configuration setup
                   16171:       description  - text to display to operator that describes this config
                   16172:       CODElocation - if 0 or the string 'none'
                   16173:                           - no CODE exists for this config
                   16174:                      if -1 || the string 'letter'
                   16175:                           - a CODE exists for this config and is
                   16176:                             a string of letters
                   16177:                      Unsupported value (but planned for future support)
                   16178:                           if a positive integer
                   16179:                                - The CODE exists as the first n items from
                   16180:                                  the question section of the form
                   16181:                           if the string 'number'
                   16182:                                - The CODE exists for this config and is
                   16183:                                  a string of numbers
                   16184:       CODEstart   - (only matter if a CODE exists) column in the line where
                   16185:                      the CODE starts
                   16186:       CODElength  - length of the CODE
                   16187:       IDstart     - column where the student/employee ID starts
                   16188:       IDlength    - length of the student/employee ID info
                   16189:       Qstart      - column where the information from the bubbled
                   16190:                     'questions' start
                   16191:       Qlength     - number of columns comprising a single bubble line from
                   16192:                     the sheet. (usually either 1 or 10)
                   16193:       Qon         - either a single character representing the character used
                   16194:                     to signal a bubble was chosen in the positional setup, or
                   16195:                     the string 'letter' if the letter of the chosen bubble is
                   16196:                     in the final, or 'number' if a number representing the
                   16197:                     chosen bubble is in the file (1->A 0->J)
                   16198:       Qoff        - the character used to represent that a bubble was
                   16199:                     left blank
                   16200:       PaperID     - if the scanning process generates a unique number for each
                   16201:                     sheet scanned the column that this ID number starts in
                   16202:       PaperIDlength - number of columns that comprise the unique ID number
                   16203:                       for the sheet of paper
                   16204:       FirstName   - column that the first name starts in
                   16205:       FirstNameLength - number of columns that the first name spans
                   16206:       LastName    - column that the last name starts in
                   16207:       LastNameLength - number of columns that the last name spans
                   16208:       BubblesPerRow - number of bubbles available in each row used to
                   16209:                       bubble an answer. (If not specified, 10 assumed).
                   16210: 
                   16211: 
                   16212: =item *
                   16213: 
                   16214: get_scantronformat_file($cdom)
                   16215: 
                   16216: $cdom - the course's domain (optional); if not supplied, uses
                   16217: domain for current $env{'request.course.id'}.
                   16218: 
                   16219: Returns an array containing lines from the scantron format file for
                   16220: the domain of the course.
                   16221: 
                   16222: If a url for a custom.tab file is listed in domain's configuration.db,
                   16223: lines are from this file.
                   16224: 
                   16225: Otherwise, if a default.tab has been published in RES space by the
                   16226: domainconfig user, lines are from this file.
                   16227: 
                   16228: Otherwise, fall back to getting lines from the legacy file on the
                   16229: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   16230: 
                   16231: =back
                   16232: 
1.243     albertel 16233: =head2 Resource Subroutines
                   16234: 
                   16235: =over 4
1.191     harris41 16236: 
                   16237: =item *
                   16238: 
1.243     albertel 16239: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 16240: 
                   16241: =item *
                   16242: 
1.243     albertel 16243: repcopy($filename) : subscribes to the requested file, and attempts to
                   16244: replicate from the owning library server, Might return
1.607     raeburn  16245: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   16246: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 16247: resource. Expects the local filesystem pathname
                   16248: (/home/httpd/html/res/....)
                   16249: 
                   16250: =back
                   16251: 
                   16252: =head2 Resource Information
                   16253: 
                   16254: =over 4
1.191     harris41 16255: 
                   16256: =item *
                   16257: 
1.1172.2.28  raeburn  16258: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   16259: and returns the value of a variety of different possible values,
                   16260: $varname should be a request string, and the other parameters can be
                   16261: used to specify who and what one is asking about. Ordinarily, $cid 
                   16262: does not need to be specified, as it is retrived from 
                   16263: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   16264: within lonuserstate::loadmap() when initializing a course, before
                   16265: $env{'request.course.id'} has been set, so it needs to be provided
                   16266: in that one case.
1.243     albertel 16267: 
                   16268: Possible values for $varname are environment.lastname (or other item
                   16269: from the envirnment hash), user.name (or someother aspect about the
                   16270: user), resource.0.maxtries (or some other part and parameter of a
                   16271: resource)
1.204     albertel 16272: 
                   16273: =item *
                   16274: 
1.243     albertel 16275: directcondval($number) : get current value of a condition; reads from a state
                   16276: string
1.204     albertel 16277: 
                   16278: =item *
                   16279: 
1.243     albertel 16280: condval($condidx) : value of condition index based on state
1.204     albertel 16281: 
                   16282: =item *
                   16283: 
1.1172.2.146.  .13(raeb 16284:-23): metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 16285: resource's metadata, $what should be either a specific key, or either
                   16286: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1172.2.146.  .13(raeb 16287:-23): packages that this resource currently uses, the last 3 arguments are
                   16288:-23): only used internally for recursive metadata.
                   16289:-23): 
                   16290:-23): the toolsymb is only used where the uri is for an external tool (for which
                   16291:-23): the uri as well as the symb are guaranteed to be unique).
1.243     albertel 16292: 
                   16293: this function automatically caches all requests
1.191     harris41 16294: 
                   16295: =item *
                   16296: 
1.243     albertel 16297: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   16298: network of library servers; returns file handle of where SQL and regex results
                   16299: will be stored for query
1.191     harris41 16300: 
                   16301: =item *
                   16302: 
1.1172.2.66  raeburn  16303: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   16304: return symbolic list entry (all arguments optional).
                   16305: 
                   16306: Args: filename is the filename (including path) for the file for which a symb
                   16307: is required; donotrecurse, if true will prevent calls to allowed() being made
                   16308: to check access status if more than one resource was found in the bighash
                   16309: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   16310: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   16311: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   16312: cause possible symbs to be checked to determine if they are subject to content
                   16313: blocking, if so they will not be included as possible symbs; possibles is a
                   16314: ref to a hash, which, as a side effect, will be populated with all possible
                   16315: symbs (content blocking not tested).
                   16316: 
1.243     albertel 16317: returns the data handle
1.191     harris41 16318: 
                   16319: =item *
                   16320: 
1.1172.2.17  raeburn  16321: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  16322: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 16323: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  16324: on failure, user must be in a course, as it assumes the existence of
                   16325: the course initial hash, and uses $env('request.course.id'}.  The third
                   16326: arg is an optional reference to a scalar.  If this arg is passed in the
                   16327: call to symbverify, it will be set to 1 if the symb has been set to be 
                   16328: encrypted; otherwise it will be null.
1.243     albertel 16329: 
1.191     harris41 16330: =item *
                   16331: 
1.243     albertel 16332: symbclean($symb) : removes versions numbers from a symb, returns the
                   16333: cleaned symb
1.191     harris41 16334: 
                   16335: =item *
                   16336: 
1.243     albertel 16337: is_on_map($uri) : checks if the $uri is somewhere on the current
                   16338: course map, user must be in a course for it to work.
1.191     harris41 16339: 
                   16340: =item *
                   16341: 
1.243     albertel 16342: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 16343: 
                   16344: =item *
                   16345: 
1.243     albertel 16346: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   16347: a random seed, all arguments are optional, if they aren't sent it uses the
                   16348: environment to derive them. Note: if symb isn't sent and it can't get one
                   16349: from &symbread it will use the current time as its return value
1.191     harris41 16350: 
                   16351: =item *
                   16352: 
1.243     albertel 16353: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   16354: unfakeable, receipt
1.191     harris41 16355: 
                   16356: =item *
                   16357: 
1.620     albertel 16358: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 16359: 
                   16360: =item *
                   16361: 
1.243     albertel 16362: countacc($url) : count the number of accesses to a given URL
1.191     harris41 16363: 
                   16364: =item *
                   16365: 
1.243     albertel 16366: 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 16367: 
                   16368: =item *
                   16369: 
1.243     albertel 16370: 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 16371: 
                   16372: =item *
                   16373: 
1.243     albertel 16374: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 16375: 
                   16376: =item *
                   16377: 
1.243     albertel 16378: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   16379: forcing spreadsheet to reevaluate the resource scores next time.
                   16380: 
1.1172.2.13  raeburn  16381: =item *
                   16382: 
                   16383: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   16384: when viewing in course context.
                   16385: 
                   16386:  input: six args -- filename (decluttered), course number, course domain,
                   16387:                     url, symb (if registered) and group (if this is a
                   16388:                     group item -- e.g., bulletin board, group page etc.).
                   16389: 
                   16390:  output: array of five scalars --
                   16391:          $cfile -- url for file editing if editable on current server
                   16392:          $home -- homeserver of resource (i.e., for author if published,
                   16393:                                           or course if uploaded.).
                   16394:          $switchserver --  1 if server switch will be needed.
                   16395:          $forceedit -- 1 if icon/link should be to go to edit mode
                   16396:          $forceview -- 1 if icon/link should be to go to view mode
                   16397: 
                   16398: =item *
                   16399: 
                   16400: is_course_upload($file,$cnum,$cdom)
                   16401: 
                   16402: Used in course context to determine if current file was uploaded to
                   16403: the course (i.e., would be found in /userfiles/docs on the course's
                   16404: homeserver.
                   16405: 
                   16406:   input: 3 args -- filename (decluttered), course number and course domain.
                   16407:   output: boolean -- 1 if file was uploaded.
                   16408: 
1.243     albertel 16409: =back
                   16410: 
                   16411: =head2 Storing/Retreiving Data
                   16412: 
                   16413: =over 4
1.191     harris41 16414: 
                   16415: =item *
                   16416: 
1.1172.2.64  raeburn  16417: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   16418: permanently for this url; hashref needs to be given and should be a \%hashname;
                   16419: the remaining args aren't required and if they aren't passed or are '' they will
                   16420: be derived from the env (with the exception of $laststore, which is an
                   16421: optional arg used when a user's submission is stored in grading).
                   16422: $laststore is $version=$timestamp, where $version is the most recent version
                   16423: number retrieved for the corresponding $symb in the $namespace db file, and
                   16424: $timestamp is the timestamp for that transaction (UNIX time).
                   16425: $laststore is currently only passed when cstore() is called by
                   16426: structuretags::finalize_storage().
1.191     harris41 16427: 
                   16428: =item *
                   16429: 
1.1172.2.64  raeburn  16430: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   16431: but uses critical subroutine
1.191     harris41 16432: 
                   16433: =item *
                   16434: 
1.243     albertel 16435: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   16436: all args are optional
1.191     harris41 16437: 
                   16438: =item *
                   16439: 
1.717     albertel 16440: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   16441: dumps the complete (or key matching regexp) namespace into a hash
                   16442: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   16443: normally &store()ed into
                   16444: 
                   16445: $range should be either an integer '100' (give me the first 100
                   16446:                                            matching records)
                   16447:               or be  two integers sperated by a - with no spaces
                   16448:                  '30-50' (give me the 30th through the 50th matching
                   16449:                           records)
                   16450: 
                   16451: 
                   16452: =item *
                   16453: 
1.1172.2.59  raeburn  16454: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 16455: replaces a &store() version of data with a replacement set of data
                   16456: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  16457: reference. If $tolog is true, the transaction is logged in the courselog
                   16458: with an action=PUTSTORE.
1.717     albertel 16459: 
                   16460: =item *
                   16461: 
1.243     albertel 16462: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   16463: works very similar to store/cstore, but all data is stored in a
                   16464: temporary location and can be reset using tmpreset, $storehash should
                   16465: be a hash reference, returns nothing on success
1.191     harris41 16466: 
                   16467: =item *
                   16468: 
1.243     albertel 16469: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   16470: similar to restore, but all data is stored in a temporary location and
                   16471: can be reset using tmpreset. Returns a hash of values on success,
                   16472: error string otherwise.
1.191     harris41 16473: 
                   16474: =item *
                   16475: 
1.243     albertel 16476: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   16477: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 16478: 
                   16479: =item *
                   16480: 
1.243     albertel 16481: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16482: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 16483: 
                   16484: =item *
                   16485: 
1.243     albertel 16486: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   16487: namesp ($udom and $uname are optional)
1.191     harris41 16488: 
                   16489: =item *
                   16490: 
1.702     albertel 16491: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 16492: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 16493: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  16494: 
1.702     albertel 16495: $range should be either an integer '100' (give me the first 100
                   16496:                                            matching records)
                   16497:               or be  two integers sperated by a - with no spaces
                   16498:                  '30-50' (give me the 30th through the 50th matching
                   16499:                           records)
1.449     matthew  16500: =item *
                   16501: 
                   16502: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   16503: $store can be a scalar, an array reference, or if the amount to be 
                   16504: incremented is > 1, a hash reference.
                   16505: 
                   16506: ($udom and $uname are optional)
1.191     harris41 16507: 
                   16508: =item *
                   16509: 
1.243     albertel 16510: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   16511: ($udom and $uname are optional)
1.191     harris41 16512: 
                   16513: =item *
                   16514: 
1.243     albertel 16515: cput($namespace,$storehash,$udom,$uname) : critical put
                   16516: ($udom and $uname are optional)
1.191     harris41 16517: 
                   16518: =item *
                   16519: 
1.748     albertel 16520: newput($namespace,$storehash,$udom,$uname) :
                   16521: 
                   16522: Attempts to store the items in the $storehash, but only if they don't
                   16523: currently exist, if this succeeds you can be certain that you have 
                   16524: successfully created a new key value pair in the $namespace db.
                   16525: 
                   16526: 
                   16527: Args:
                   16528:  $namespace: name of database to store values to
                   16529:  $storehash: hashref to store to the db
                   16530:  $udom: (optional) domain of user containing the db
                   16531:  $uname: (optional) name of user caontaining the db
                   16532: 
                   16533: Returns:
                   16534:  'ok' -> succeeded in storing all keys of $storehash
                   16535:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   16536:                         least <key> already existed in the db (other
                   16537:                         requested keys may also already exist)
1.967     bisitz   16538:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 16539:  'con_lost' -> unable to contact request server
                   16540:  'refused' -> action was not allowed by remote machine
                   16541: 
                   16542: 
                   16543: =item *
                   16544: 
1.243     albertel 16545: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16546: reference filled in from namesp (encrypts the return communication)
                   16547: ($udom and $uname are optional)
1.191     harris41 16548: 
                   16549: =item *
                   16550: 
1.243     albertel 16551: log($udom,$name,$home,$message) : write to permanent log for user; use
                   16552: critical subroutine
                   16553: 
1.806     raeburn  16554: =item *
                   16555: 
1.860     raeburn  16556: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   16557: array reference filled in from namespace found in domain level on either
                   16558: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  16559: 
                   16560: =item *
                   16561: 
1.860     raeburn  16562: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   16563: domain level either on specified domain server ($uhome) or primary domain 
                   16564: server ($udom and $uhome are optional)
1.806     raeburn  16565: 
1.943     raeburn  16566: =item * 
                   16567: 
1.1172.2.35  raeburn  16568: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   16569: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   16570: the target domain.
                   16571: 
                   16572: May also include additional key => value pairs for the following groups:
                   16573: 
                   16574: =over
                   16575: 
                   16576: =item
                   16577: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   16578: 
                   16579: =over
                   16580: 
                   16581: =item defaultquota, authorquota
                   16582: 
                   16583: =back
                   16584: 
                   16585: =item
                   16586: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   16587: portfolio for users).
                   16588: 
                   16589: =over
                   16590: 
                   16591: =item
                   16592: aboutme, blog, webdav, portfolio
                   16593: 
                   16594: =back
                   16595: 
                   16596: =item
                   16597: requestcourses: ability to request courses, and how requests are processed.
                   16598: 
                   16599: =over
                   16600: 
                   16601: =item
1.1172.2.37  raeburn  16602: official, unofficial, community, textbook
1.1172.2.35  raeburn  16603: 
                   16604: =back
                   16605: 
                   16606: =item
                   16607: inststatus: types of institutional affiliation, and order in which they are displayed.
                   16608: 
                   16609: =over
                   16610: 
                   16611: =item
1.1172.2.44  raeburn  16612: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  16613: 
                   16614: =back
                   16615: 
                   16616: =item
                   16617: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   16618: for course's uploaded content.
                   16619: 
                   16620: =over
                   16621: 
                   16622: =item
1.1172.2.68  raeburn  16623: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   16624: communityquota, textbookquota
1.1172.2.35  raeburn  16625: 
                   16626: =back
                   16627: 
                   16628: =item
                   16629: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   16630: on your servers.
                   16631: 
                   16632: =over
                   16633: 
                   16634: =item
                   16635: remotesessions, hostedsessions
                   16636: 
                   16637: =back
                   16638: 
                   16639: =back
                   16640: 
                   16641: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   16642: utility to create a configuration.db file on a domain's primary library server
                   16643: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   16644: -- corresponding values are authentication type (internal, krb4, krb5,
                   16645: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   16646: will be available. Values are retrieved from cache (if current), unless the
                   16647: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   16648: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   16649: 
                   16650: Typical usage:
1.943     raeburn  16651: 
1.1172.2.35  raeburn  16652: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  16653: 
1.243     albertel 16654: =back
                   16655: 
                   16656: =head2 Network Status Functions
                   16657: 
                   16658: =over 4
1.191     harris41 16659: 
                   16660: =item *
                   16661: 
1.1137    raeburn  16662: dirlist() : return directory list based on URI (first arg).
                   16663: 
                   16664: Inputs: 1 required, 5 optional.
                   16665: 
                   16666: =over
                   16667: 
                   16668: =item 
                   16669: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   16670: 
                   16671: =item
                   16672: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   16673: 
                   16674: =item
                   16675: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   16676: 
                   16677: =item
                   16678: $getpropath - boolean: 1 if prepend path using &propath(). 
                   16679: 
                   16680: =item
                   16681: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   16682: 
                   16683: =item 
                   16684: $alternateRoot - path to prepend in place of path from $uri.
                   16685: 
                   16686: =back
                   16687: 
                   16688: Returns: Array of up to two items.
                   16689: 
                   16690: =over
                   16691: 
                   16692: a reference to an array of files/subdirectories
                   16693: 
                   16694: =over
                   16695: 
                   16696: Each element in the array of files/subdirectories is a & separated list of
                   16697: item name and the result of running stat on the item.  If dirlist was requested
                   16698: for a file instead of a directory, the item name will be ''. For a directory 
                   16699: listing, if the item is a metadata file, the element will end &N&M 
                   16700: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   16701: default copyright set (1).  
                   16702: 
                   16703: =back
                   16704: 
                   16705: a scalar containing error condition (if encountered).
                   16706: 
                   16707: =over
                   16708: 
                   16709: =item 
                   16710: no_host (no homeserver identified for $username:$domain).
                   16711: 
                   16712: =item 
                   16713: no_such_host (server contacted for listing not identified as valid host).
                   16714: 
                   16715: =item 
                   16716: con_lost (connection to remote server failed).
                   16717: 
                   16718: =item 
                   16719: refused (invalid $username:$domain received on lond side).
                   16720: 
                   16721: =item 
                   16722: no_such_dir (directory at specified path on lond side does not exist). 
                   16723: 
                   16724: =item 
                   16725: empty (directory at specified path on lond side is empty).
                   16726: 
                   16727: =over
                   16728: 
                   16729: This is currently not encountered because the &ls3, &ls2, 
                   16730: &ls (_handler) routines on the lond side do not filter out
                   16731: . and .. from a directory listing. 
                   16732: 
                   16733: =back
                   16734: 
                   16735: =back
                   16736: 
                   16737: =back
1.191     harris41 16738: 
                   16739: =item *
                   16740: 
1.243     albertel 16741: spareserver() : find server with least workload from spare.tab
                   16742: 
1.986     foxr     16743: 
                   16744: =item *
                   16745: 
                   16746: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   16747: if there is no corresponding loncapa host.
                   16748: 
1.243     albertel 16749: =back
                   16750: 
1.986     foxr     16751: 
1.243     albertel 16752: =head2 Apache Request
                   16753: 
                   16754: =over 4
1.191     harris41 16755: 
                   16756: =item *
                   16757: 
1.243     albertel 16758: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   16759: localhost, posts hash
                   16760: 
                   16761: =back
                   16762: 
                   16763: =head2 Data to String to Data
                   16764: 
                   16765: =over 4
1.191     harris41 16766: 
                   16767: =item *
                   16768: 
1.243     albertel 16769: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   16770: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 16771: 
                   16772: =item *
                   16773: 
1.243     albertel 16774: hashref2str($hashref) : convert a hashref into a string complete with
                   16775: escaping and '=' and '&' separators, supports elements that are
                   16776: arrayrefs and hashrefs
1.191     harris41 16777: 
                   16778: =item *
                   16779: 
1.243     albertel 16780: arrayref2str($arrayref) : convert an arrayref into a string complete
                   16781: with escaping and '&' separators, supports elements that are arrayrefs
                   16782: and hashrefs
1.191     harris41 16783: 
                   16784: =item *
                   16785: 
1.243     albertel 16786: str2hash($string) : convert string to hash using unescaping and
                   16787: splitting on '=' and '&', supports elements that are arrayrefs and
                   16788: hashrefs
1.191     harris41 16789: 
                   16790: =item *
                   16791: 
1.243     albertel 16792: str2array($string) : convert string to hash using unescaping and
                   16793: splitting on '&', supports elements that are arrayrefs and hashrefs
                   16794: 
                   16795: =back
                   16796: 
                   16797: =head2 Logging Routines
                   16798: 
                   16799: 
                   16800: These routines allow one to make log messages in the lonnet.log and
                   16801: lonnet.perm logfiles.
1.191     harris41 16802: 
1.1119    foxr     16803: =over 4
                   16804: 
1.191     harris41 16805: =item *
                   16806: 
1.243     albertel 16807: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 16808: 
                   16809: =item *
                   16810: 
1.243     albertel 16811: logthis() : append message to the normal lonnet.log file, it gets
                   16812: preiodically rolled over and deleted.
1.191     harris41 16813: 
                   16814: =item *
                   16815: 
1.243     albertel 16816: logperm() : append a permanent message to lonnet.perm.log, this log
                   16817: file never gets deleted by any automated portion of the system, only
                   16818: messages of critical importance should go in here.
                   16819: 
1.1119    foxr     16820: 
1.243     albertel 16821: =back
                   16822: 
                   16823: =head2 General File Helper Routines
                   16824: 
                   16825: =over 4
1.191     harris41 16826: 
                   16827: =item *
                   16828: 
1.481     raeburn  16829: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   16830: (a) files in /uploaded
                   16831:   (i) If a local copy of the file exists - 
                   16832:       compares modification date of local copy with last-modified date for 
                   16833:       definitive version stored on home server for course. If local copy is 
                   16834:       stale, requests a new version from the home server and stores it. 
                   16835:       If the original has been removed from the home server, then local copy 
                   16836:       is unlinked.
                   16837:   (ii) If local copy does not exist -
                   16838:       requests the file from the home server and stores it. 
                   16839:   
                   16840:   If $caller is 'uploadrep':  
                   16841:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   16842:     for request for files originally uploaded via DOCS. 
                   16843:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   16844:   
                   16845:   Otherwise:
                   16846:      This indicates a call from the content generation phase of the request.
                   16847:      -  returns the entire contents of the file or -1.
                   16848:      
                   16849: (b) files in /res
                   16850:    - returns the entire contents of a file or -1; 
                   16851:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 16852: 
1.712     albertel 16853: 
                   16854: =item *
                   16855: 
                   16856: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   16857:                   reference
                   16858: 
                   16859: returns either a stat() list of data about the file or an empty list
                   16860: if the file doesn't exist or couldn't find out about it (connection
                   16861: problems or user unknown)
                   16862: 
1.191     harris41 16863: =item *
                   16864: 
1.243     albertel 16865: filelocation($dir,$file) : returns file system location of a file
                   16866: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   16867: directory that relative $file lookups are to looked in ($dir of /a/dir
                   16868: and a file of ../bob will become /a/bob)
1.191     harris41 16869: 
                   16870: =item *
                   16871: 
                   16872: hreflocation($dir,$file) : returns file system location or a URL; same as
                   16873: filelocation except for hrefs
                   16874: 
                   16875: =item *
                   16876: 
1.1172.2.49  raeburn  16877: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   16878: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 16879: 
1.243     albertel 16880: =back
                   16881: 
1.608     albertel 16882: =head2 Usererfile file routines (/uploaded*)
                   16883: 
                   16884: =over 4
                   16885: 
                   16886: =item *
                   16887: 
                   16888: userfileupload(): main rotine for putting a file in a user or course's
                   16889:                   filespace, arguments are,
                   16890: 
1.620     albertel 16891:  formname - required - this is the name of the element in $env where the
1.608     albertel 16892:            filename, and the contents of the file to create/modifed exist
1.620     albertel 16893:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   16894:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  16895:  context - if coursedoc, store the file in the course of the active role
                   16896:              of the current user; 
                   16897:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   16898:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 16899:  subdir - required - subdirectory to put the file in under ../userfiles/
                   16900:          if undefined, it will be placed in "unknown"
                   16901: 
                   16902:  (This routine calls clean_filename() to remove any dangerous
                   16903:  characters from the filename, and then calls finuserfileupload() to
                   16904:  complete the transaction)
                   16905: 
                   16906:  returns either the url of the uploaded file (/uploaded/....) if successful
                   16907:  and /adm/notfound.html if unsuccessful
                   16908: 
                   16909: =item *
                   16910: 
                   16911: clean_filename(): routine for cleaing a filename up for storage in
                   16912:                  userfile space, argument is:
                   16913: 
                   16914:  filename - proposed filename
                   16915: 
                   16916: returns: the new clean filename
                   16917: 
                   16918: =item *
                   16919: 
1.1090    raeburn  16920: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 16921: userspace, probably shouldn't be called directly
                   16922: 
                   16923:   docuname: username or courseid of destination for the file
                   16924:   docudom: domain of user/course of destination for the file
                   16925:   formname: same as for userfileupload()
1.1090    raeburn  16926:   fname: filename (including subdirectories) for the file
                   16927:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  16928:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  16929:   allfiles: reference to hash used to store objects found by parser
                   16930:   codebase: reference to hash used for codebases of java objects found by parser
                   16931:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   16932:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   16933:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   16934:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   16935:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   16936:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  16937:   mimetype: reference to scalar to accommodate mime type determined
                   16938:             from File::MMagic if $parser = parse.
1.608     albertel 16939: 
                   16940:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  16941:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   16942:  was 'overwrite').
                   16943:  
1.608     albertel 16944: 
                   16945: =item *
                   16946: 
                   16947: renameuserfile(): renames an existing userfile to a new name
                   16948: 
                   16949:   Args:
                   16950:    docuname: username or courseid of destination for the file
                   16951:    docudom: domain of user/course of destination for the file
                   16952:    old: current file name (including any subdirs under userfiles)
                   16953:    new: desired file name (including any subdirs under userfiles)
                   16954: 
                   16955: =item *
                   16956: 
                   16957: mkdiruserfile(): creates a directory is a userfiles dir
                   16958: 
                   16959:   Args:
                   16960:    docuname: username or courseid of destination for the file
                   16961:    docudom: domain of user/course of destination for the file
                   16962:    dir: dir to create (including any subdirs under userfiles)
                   16963: 
                   16964: =item *
                   16965: 
                   16966: removeuserfile(): removes a file that exists in userfiles
                   16967: 
                   16968:   Args:
                   16969:    docuname: username or courseid of destination for the file
                   16970:    docudom: domain of user/course of destination for the file
                   16971:    fname: filname to delete (including any subdirs under userfiles)
                   16972: 
                   16973: =item *
                   16974: 
                   16975: removeuploadedurl(): convience function for removeuserfile()
                   16976: 
                   16977:   Args:
                   16978:    url:  a full /uploaded/... url to delete
                   16979: 
1.747     albertel 16980: =item * 
                   16981: 
                   16982: get_portfile_permissions():
                   16983:   Args:
                   16984:     domain: domain of user or course contain the portfolio files
                   16985:     user: name of user or num of course contain the portfolio files
                   16986:   Returns:
                   16987:     hashref of a dump of the proper file_permissions.db
                   16988:    
                   16989: 
                   16990: =item * 
                   16991: 
                   16992: get_access_controls():
                   16993: 
                   16994: Args:
                   16995:   current_permissions: the hash ref returned from get_portfile_permissions()
                   16996:   group: (optional) the group you want the files associated with
                   16997:   file: (optional) the file you want access info on
                   16998: 
                   16999: Returns:
1.749     raeburn  17000:     a hash (keys are file names) of hashes containing
                   17001:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   17002:         values are XML containing access control settings (see below) 
1.747     albertel 17003: 
                   17004: Internal notes:
                   17005: 
1.749     raeburn  17006:  access controls are stored in file_permissions.db as key=value pairs.
                   17007:     key -> path to file/file_name\0uniqueID:scope_end_start
                   17008:         where scope -> public,guest,course,group,domains or users.
                   17009:               end -> UNIX time for end of access (0 -> no end date)
                   17010:               start -> UNIX time for start of access
                   17011: 
                   17012:     value -> XML description of access control
                   17013:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   17014:             <start></start>
                   17015:             <end></end>
                   17016: 
                   17017:             <password></password>  for scope type = guest
                   17018: 
                   17019:             <domain></domain>     for scope type = course or group
                   17020:             <number></number>
                   17021:             <roles id="">
                   17022:              <role></role>
                   17023:              <access></access>
                   17024:              <section></section>
                   17025:              <group></group>
                   17026:             </roles>
                   17027: 
                   17028:             <dom></dom>         for scope type = domains
                   17029: 
                   17030:             <users>             for scope type = users
                   17031:              <user>
                   17032:               <uname></uname>
                   17033:               <udom></udom>
                   17034:              </user>
                   17035:             </users>
                   17036:            </scope> 
                   17037:               
                   17038:  Access data is also aggregated for each file in an additional key=value pair:
                   17039:  key -> path to file/file_name\0accesscontrol 
                   17040:  value -> reference to hash
                   17041:           hash contains key = value pairs
                   17042:           where key = uniqueID:scope_end_start
                   17043:                 value = UNIX time record was last updated
                   17044: 
                   17045:           Used to improve speed of look-ups of access controls for each file.  
                   17046:  
                   17047:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   17048: 
1.1172.2.13  raeburn  17049: =item *
                   17050: 
1.749     raeburn  17051: modify_access_controls():
                   17052: 
                   17053: Modifies access controls for a portfolio file
                   17054: Args
                   17055: 1. file name
                   17056: 2. reference to hash of required changes,
                   17057: 3. domain
                   17058: 4. username
                   17059:   where domain,username are the domain of the portfolio owner 
                   17060:   (either a user or a course) 
                   17061: 
                   17062: Returns:
                   17063: 1. result of additions or updates ('ok' or 'error', with error message). 
                   17064: 2. result of deletions ('ok' or 'error', with error message).
                   17065: 3. reference to hash of any new or updated access controls.
                   17066: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   17067:    key = integer (inbound ID)
1.1172.2.13  raeburn  17068:    value = uniqueID
                   17069: 
                   17070: =item *
                   17071: 
                   17072: get_timebased_id():
                   17073: 
                   17074: Attempts to get a unique timestamp-based suffix for use with items added to a
                   17075: course via the Course Editor (e.g., folders, composite pages,
                   17076: group bulletin boards).
                   17077: 
                   17078: Args: (first three required; six others optional)
                   17079: 
                   17080: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   17081:    docssequence, or name of group
                   17082: 
                   17083: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   17084:    e.g., num, boardids
                   17085: 
                   17086: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   17087:    file will be named nohist_namespace.db
                   17088: 
                   17089: 4. cdom: domain of course; default is current course domain from %env
                   17090: 
                   17091: 5. cnum: course number; default is current course number from %env
                   17092: 
                   17093: 6. idtype: set to concat if an additional digit is to be appended to the
                   17094:    unix timestamp to form the suffix, if the plain timestamp is already
                   17095:    in use.  Default is to not do this, but simply increment the unix
                   17096:    timestamp by 1 until a unique key is obtained.
                   17097: 
                   17098: 7. who: holder of locking key; defaults to user:domain for user.
                   17099: 
                   17100: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   17101:    retrying); default is 3.
                   17102: 
                   17103: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   17104: 
                   17105: Returns:
                   17106: 
                   17107: 1. suffix obtained (numeric)
                   17108: 
                   17109: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   17110: 
                   17111: 3. error: contains (localized) error message if an error occurred.
                   17112: 
1.747     albertel 17113: 
1.608     albertel 17114: =back
                   17115: 
1.243     albertel 17116: =head2 HTTP Helper Routines
                   17117: 
                   17118: =over 4
                   17119: 
1.191     harris41 17120: =item *
                   17121: 
                   17122: escape() : unpack non-word characters into CGI-compatible hex codes
                   17123: 
                   17124: =item *
                   17125: 
                   17126: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   17127: 
1.243     albertel 17128: =back
                   17129: 
                   17130: =head1 PRIVATE SUBROUTINES
                   17131: 
                   17132: =head2 Underlying communication routines (Shouldn't call)
                   17133: 
                   17134: =over 4
                   17135: 
                   17136: =item *
                   17137: 
                   17138: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   17139: 
                   17140: =item *
                   17141: 
                   17142: reply() : uses subreply to send a message to remote machine, logs all failures
                   17143: 
                   17144: =item *
                   17145: 
                   17146: critical() : passes a critical message to another server; if cannot
                   17147: get through then place message in connection buffer directory and
                   17148: returns con_delayed, if incapable of saving message, returns
                   17149: con_failed
                   17150: 
                   17151: =item *
                   17152: 
                   17153: reconlonc() : tries to reconnect lonc client processes.
                   17154: 
                   17155: =back
                   17156: 
                   17157: =head2 Resource Access Logging
                   17158: 
                   17159: =over 4
                   17160: 
                   17161: =item *
                   17162: 
                   17163: flushcourselogs() : flush (save) buffer logs and access logs
                   17164: 
                   17165: =item *
                   17166: 
                   17167: courselog($what) : save message for course in hash
                   17168: 
                   17169: =item *
                   17170: 
                   17171: courseacclog($what) : save message for course using &courselog().  Perform
                   17172: special processing for specific resource types (problems, exams, quizzes, etc).
                   17173: 
1.191     harris41 17174: =item *
                   17175: 
                   17176: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   17177: as a PerlChildExitHandler
1.243     albertel 17178: 
                   17179: =back
                   17180: 
                   17181: =head2 Other
                   17182: 
                   17183: =over 4
                   17184: 
                   17185: =item *
                   17186: 
                   17187: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 17188: 
                   17189: =back
                   17190: 
                   17191: =cut
1.877     foxr     17192: 

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