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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.146.  .14(raeb    4:-23): # $Id: lonnet.pm,v 1.1172.2.146.2.13 2023/07/09 00:49:22 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;
                   5181:         }
                   5182:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   5183:                    $domain,$cnum,$cdom);
                   5184:         if (($trole ne 'st') || ($sec ne '')) {
                   5185:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  5186:         }
                   5187:     }
                   5188:     return;
                   5189: }
                   5190: 
1.1172.2.9  raeburn  5191: sub domainrolelog {
                   5192:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5193:     if ($area =~ m{^/($match_domain)/$}) {
                   5194:         my $cdom = $1;
                   5195:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   5196:         my $namespace = 'rolelog';
                   5197:         my %storehash = (
                   5198:                            role    => $trole,
                   5199:                            start   => $tstart,
                   5200:                            end     => $tend,
                   5201:                            context => $context,
                   5202:                         );
                   5203:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   5204:                    $domain,$domconfiguser,$cdom);
                   5205:     }
                   5206:     return;
                   5207: 
                   5208: }
                   5209: 
                   5210: sub coauthorrolelog {
                   5211:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5212:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   5213:         my $audom = $1;
                   5214:         my $auname = $2;
                   5215:         my $namespace = 'rolelog';
                   5216:         my %storehash = (
                   5217:                            role    => $trole,
                   5218:                            start   => $tstart,
                   5219:                            end     => $tend,
                   5220:                            context => $context,
                   5221:                         );
                   5222:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   5223:                    $domain,$auname,$audom);
                   5224:     }
                   5225:     return;
                   5226: }
                   5227: 
1.351     www      5228: sub get_course_adv_roles {
1.948     raeburn  5229:     my ($cid,$codes) = @_;
1.620     albertel 5230:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      5231:     my %coursehash=&coursedescription($cid);
1.988     raeburn  5232:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      5233:     my %nothide=();
1.800     albertel 5234:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  5235:         if ($user !~ /:/) {
                   5236: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   5237:         } else {
                   5238:             $nothide{$user}=1;
                   5239:         }
1.470     www      5240:     }
1.1172.2.23  raeburn  5241:     my @possdoms = ($coursehash{'domain'});
                   5242:     if ($coursehash{'checkforpriv'}) {
                   5243:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   5244:     }
1.351     www      5245:     my %returnhash=();
                   5246:     my %dumphash=
                   5247:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   5248:     my $now=time;
1.997     raeburn  5249:     my %privileged;
1.1000    raeburn  5250:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 5251: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      5252:         if (($tstart) && ($tstart<0)) { next; }
                   5253:         if (($tend) && ($tend<$now)) { next; }
                   5254:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 5255:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 5256: 	if ($username eq '' || $domain eq '') { next; }
1.1172.2.23  raeburn  5257:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  5258:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 5259: 	if ($role eq 'cr') { next; }
1.948     raeburn  5260:         if ($codes) {
                   5261:             if ($section) { $role .= ':'.$section; }
                   5262:             if ($returnhash{$role}) {
                   5263:                 $returnhash{$role}.=','.$username.':'.$domain;
                   5264:             } else {
                   5265:                 $returnhash{$role}=$username.':'.$domain;
                   5266:             }
1.351     www      5267:         } else {
1.988     raeburn  5268:             my $key=&plaintext($role,$crstype);
1.973     bisitz   5269:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  5270:             if ($returnhash{$key}) {
                   5271: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   5272:             } else {
                   5273:                 $returnhash{$key}=$username.':'.$domain;
                   5274:             }
1.351     www      5275:         }
1.948     raeburn  5276:     }
1.400     www      5277:     return %returnhash;
                   5278: }
                   5279: 
                   5280: sub get_my_roles {
1.937     raeburn  5281:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 5282:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   5283:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  5284:     my (%dumphash,%nothide);
1.1086    raeburn  5285:     if ($context eq 'userroles') {
1.1166    raeburn  5286:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  5287:     } else {
1.1172.2.23  raeburn  5288:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  5289:         if ($hidepriv) {
                   5290:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   5291:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   5292:                 if ($user !~ /:/) {
                   5293:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   5294:                 } else {
                   5295:                     $nothide{$user} = 1;
                   5296:                 }
                   5297:             }
                   5298:         }
1.858     raeburn  5299:     }
1.400     www      5300:     my %returnhash=();
                   5301:     my $now=time;
1.999     raeburn  5302:     my %privileged;
1.800     albertel 5303:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  5304:         my ($role,$tend,$tstart);
                   5305:         if ($context eq 'userroles') {
1.1149    raeburn  5306:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  5307: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   5308:         } else {
                   5309:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   5310:         }
1.400     www      5311:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  5312:         my $status = 'active';
1.939     raeburn  5313:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  5314:             $status = 'previous';
                   5315:         } 
                   5316:         if (($tstart) && ($now<$tstart)) {
                   5317:             $status = 'future';
                   5318:         }
                   5319:         if (ref($types) eq 'ARRAY') {
                   5320:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   5321:                 next;
                   5322:             } 
                   5323:         } else {
                   5324:             if ($status ne 'active') {
                   5325:                 next;
                   5326:             }
                   5327:         }
1.867     raeburn  5328:         my ($rolecode,$username,$domain,$section,$area);
                   5329:         if ($context eq 'userroles') {
1.1172.2.9  raeburn  5330:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5331:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5332:         } else {
                   5333:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5334:         }
1.832     raeburn  5335:         if (ref($roledoms) eq 'ARRAY') {
                   5336:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5337:                 next;
                   5338:             }
                   5339:         }
                   5340:         if (ref($roles) eq 'ARRAY') {
                   5341:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5342:                 if ($role =~ /^cr\//) {
                   5343:                     if (!grep(/^cr$/,@{$roles})) {
                   5344:                         next;
                   5345:                     }
1.1104    raeburn  5346:                 } elsif ($role =~ /^gr\//) {
                   5347:                     if (!grep(/^gr$/,@{$roles})) {
                   5348:                         next;
                   5349:                     }
1.922     raeburn  5350:                 } else {
                   5351:                     next;
                   5352:                 }
1.832     raeburn  5353:             }
1.867     raeburn  5354:         }
1.937     raeburn  5355:         if ($hidepriv) {
1.1172.2.23  raeburn  5356:             my @privroles = ('dc','su');
1.999     raeburn  5357:             if ($context eq 'userroles') {
1.1172.2.23  raeburn  5358:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5359:             } else {
1.1172.2.23  raeburn  5360:                 my $possdoms = [$domain];
                   5361:                 if (ref($roledoms) eq 'ARRAY') {
                   5362:                    push(@{$possdoms},@{$roledoms});
1.999     raeburn  5363:                 }
1.1172.2.23  raeburn  5364:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5365:                     if (!$nothide{$username.':'.$domain}) {
                   5366:                         next;
                   5367:                     }
                   5368:                 }
1.937     raeburn  5369:             }
                   5370:         }
1.933     raeburn  5371:         if ($withsec) {
                   5372:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5373:                 $tstart.':'.$tend;
                   5374:         } else {
                   5375:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5376:         }
1.832     raeburn  5377:     }
1.373     www      5378:     return %returnhash;
1.399     www      5379: }
                   5380: 
1.1172.2.89  raeburn  5381: sub get_all_adhocroles {
                   5382:     my ($dom) = @_;
                   5383:     my @roles_by_num = ();
                   5384:     my %domdefaults = &get_domain_defaults($dom);
                   5385:     my (%description,%access_in_dom,%access_info);
                   5386:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5387:         my $count = 0;
                   5388:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5389:         my %ordered;
                   5390:         foreach my $role (sort(keys(%domcurrent))) {
                   5391:             my ($order,$desc,$access_in_dom);
                   5392:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5393:                 $order = $domcurrent{$role}{'order'};
                   5394:                 $desc = $domcurrent{$role}{'desc'};
                   5395:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5396:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5397:             }
                   5398:             if ($order eq '') {
                   5399:                 $order = $count;
                   5400:             }
                   5401:             $ordered{$order} = $role;
                   5402:             if ($desc ne '') {
                   5403:                 $description{$role} = $desc;
                   5404:             } else {
                   5405:                 $description{$role}= $role;
                   5406:             }
                   5407:             $count++;
                   5408:         }
                   5409:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5410:             push(@roles_by_num,$ordered{$item});
                   5411:         }
                   5412:     }
                   5413:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5414: }
                   5415: 
                   5416: sub get_my_adhocroles {
                   5417:     my ($cid,$checkreg) = @_;
                   5418:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5419:     if ($env{'request.course.id'} eq $cid) {
                   5420:         $cdom = $env{'course.'.$cid.'.domain'};
                   5421:         $cnum = $env{'course.'.$cid.'.num'};
                   5422:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5423:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5424:         $cdom = $1;
                   5425:         $cnum = $2;
                   5426:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5427:                                      $cdom,$cnum);
                   5428:     }
                   5429:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5430:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5431:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5432:         if ($rosterhash{$user} ne '') {
                   5433:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5434:             return ([],{}) if ($type eq 'auto');
                   5435:         }
                   5436:     }
                   5437:     if (($cdom ne '') && ($cnum ne ''))  {
1.1172.2.90  raeburn  5438:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1172.2.89  raeburn  5439:             my $then=$env{'user.login.time'};
                   5440:             my $update=$env{'user.update.time'};
1.1172.2.90  raeburn  5441:             if (!$update) {
                   5442:                 $update = $then;
                   5443:             }
                   5444:             my @liveroles;
                   5445:             foreach my $role ('dh','da') {
                   5446:                 if ($env{"user.role.$role./$cdom/"}) {
                   5447:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
                   5448:                     my $limit = $update;
                   5449:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5450:                         $limit = $then;
                   5451:                     }
                   5452:                     my $activerole = 1;
                   5453:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5454:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5455:                     if ($activerole) {
                   5456:                         push(@liveroles,$role);
                   5457:                     }
                   5458:                 }
                   5459:             }
                   5460:             if (@liveroles) {
1.1172.2.89  raeburn  5461:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
                   5462:                     my ($accessref,$accessinfo,%access_in_dom);
                   5463:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5464:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5465:                         if (@{$roles_by_num}) {
                   5466:                             my %settings;
                   5467:                             if ($env{'request.course.id'} eq $cid) {
                   5468:                                 foreach my $envkey (keys(%env)) {
                   5469:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5470:                                         $settings{$1} = $env{$envkey};
                   5471:                                     }
                   5472:                                 }
                   5473:                             } else {
                   5474:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5475:                             }
                   5476:                             my %setincrs;
                   5477:                             if ($settings{'internal.adhocaccess'}) {
                   5478:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5479:                             }
                   5480:                             my @statuses;
                   5481:                             if ($env{'environment.inststatus'}) {
                   5482:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5483:                             }
                   5484:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5485:                             if (ref($accessref) eq 'HASH') {
                   5486:                                 %access_in_dom = %{$accessref};
                   5487:                             }
                   5488:                             foreach my $role (@{$roles_by_num}) {
                   5489:                                 my ($curraccess,@okstatus,@personnel);
                   5490:                                 if ($setincrs{$role}) {
                   5491:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5492:                                     if ($curraccess eq 'status') {
                   5493:                                         @okstatus = split(/\&/,$rest);
                   5494:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5495:                                         @personnel = split(/\&/,$rest);
                   5496:                                     }
                   5497:                                 } else {
                   5498:                                     $curraccess = $access_in_dom{$role};
                   5499:                                     if (ref($accessinfo) eq 'HASH') {
                   5500:                                         if ($curraccess eq 'status') {
                   5501:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5502:                                                 @okstatus = @{$accessinfo->{$role}};
                   5503:                                             }
                   5504:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5505:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5506:                                                 @personnel = @{$accessinfo->{$role}};
                   5507:                                             }
                   5508:                                         }
                   5509:                                     }
                   5510:                                 }
                   5511:                                 if ($curraccess eq 'none') {
                   5512:                                     next;
                   5513:                                 } elsif ($curraccess eq 'all') {
                   5514:                                     push(@possroles,$role);
1.1172.2.90  raeburn  5515:                                 } elsif ($curraccess eq 'dh') {
                   5516:                                     if (grep(/^dh$/,@liveroles)) {
                   5517:                                         push(@possroles,$role);
                   5518:                                     } else {
                   5519:                                         next;
                   5520:                                     }
                   5521:                                 } elsif ($curraccess eq 'da') {
                   5522:                                     if (grep(/^da$/,@liveroles)) {
                   5523:                                         push(@possroles,$role);
                   5524:                                     } else {
                   5525:                                         next;
                   5526:                                     }
1.1172.2.89  raeburn  5527:                                 } elsif ($curraccess eq 'status') {
                   5528:                                     if (@okstatus) {
                   5529:                                         if (!@statuses) {
                   5530:                                             if (grep(/^default$/,@okstatus)) {
                   5531:                                                 push(@possroles,$role);
                   5532:                                             }
                   5533:                                         } else {
                   5534:                                             foreach my $status (@okstatus) {
                   5535:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5536:                                                     push(@possroles,$role);
                   5537:                                                     last;
                   5538:                                                 }
                   5539:                                             }
                   5540:                                         }
                   5541:                                     }
                   5542:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5543:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5544:                                         if ($curraccess eq 'exc') {
                   5545:                                             push(@possroles,$role);
                   5546:                                         }
                   5547:                                     } elsif ($curraccess eq 'inc') {
                   5548:                                         push(@possroles,$role);
                   5549:                                     }
                   5550:                                 }
                   5551:                             }
                   5552:                         }
                   5553:                     }
                   5554:                 }
                   5555:             }
                   5556:         }
                   5557:     }
                   5558:     unless (ref($description) eq 'HASH') {
                   5559:         if (ref($roles_by_num) eq 'ARRAY') {
                   5560:             my %desc;
                   5561:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5562:             $description = \%desc;
                   5563:         } else {
                   5564:             $description = {};
                   5565:         }
                   5566:     }
                   5567:     return (\@possroles,$description);
                   5568: }
                   5569: 
1.399     www      5570: # ----------------------------------------------------- Frontpage Announcements
                   5571: #
                   5572: #
                   5573: 
                   5574: sub postannounce {
                   5575:     my ($server,$text)=@_;
1.844     albertel 5576:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5577:     unless ($text=~/\w/) { $text=''; }
                   5578:     return &reply('setannounce:'.&escape($text),$server);
                   5579: }
                   5580: 
                   5581: sub getannounce {
1.448     albertel 5582: 
1.1172.2.96  raeburn  5583:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5584: 	my $announcement='';
1.800     albertel 5585: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5586: 	close($fh);
1.399     www      5587: 	if ($announcement=~/\w/) { 
                   5588: 	    return 
                   5589:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5590:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5591: 	} else {
                   5592: 	    return '';
                   5593: 	}
                   5594:     } else {
                   5595: 	return '';
                   5596:     }
1.351     www      5597: }
1.353     www      5598: 
                   5599: # ---------------------------------------------------------- Course ID routines
                   5600: # Deal with domain's nohist_courseid.db files
                   5601: #
                   5602: 
                   5603: sub courseidput {
1.921     raeburn  5604:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5605:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5606:     my $outcome;
                   5607:     if ($caller eq 'timeonly') {
                   5608:         my $cids = '';
                   5609:         foreach my $item (keys(%$storehash)) {
                   5610:             $cids.=&escape($item).'&';
                   5611:         }
                   5612:         $cids=~s/\&$//;
                   5613:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5614:                           $coursehome);       
                   5615:     } else {
                   5616:         my $items = '';
                   5617:         foreach my $item (keys(%$storehash)) {
                   5618:             $items.= &escape($item).'='.
                   5619:                      &freeze_escape($$storehash{$item}).'&';
                   5620:         }
                   5621:         $items=~s/\&$//;
                   5622:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5623:                           $coursehome);
1.918     raeburn  5624:     }
                   5625:     if ($outcome eq 'unknown_cmd') {
                   5626:         my $what;
                   5627:         foreach my $cid (keys(%$storehash)) {
                   5628:             $what .= &escape($cid).'=';
1.921     raeburn  5629:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5630:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5631:             }
                   5632:             $what =~ s/\:$/&/;
                   5633:         }
                   5634:         $what =~ s/\&$//;  
                   5635:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5636:     } else {
                   5637:         return $outcome;
                   5638:     }
1.353     www      5639: }
                   5640: 
                   5641: sub courseiddump {
1.921     raeburn  5642:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5643:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5644:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1172.2.38  raeburn  5645:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1172.2.68  raeburn  5646:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5647:     my $as_hash = 1;
                   5648:     my %returnhash;
                   5649:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5650:     my %libserv = &all_library();
                   5651:     foreach my $tryserver (keys(%libserv)) {
                   5652:         if ( (  $hostidflag == 1 
                   5653: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5654: 	     || (!defined($hostidflag)) ) {
                   5655: 
1.918     raeburn  5656: 	    if (($domfilter eq '') ||
                   5657: 		(&host_domain($tryserver) eq $domfilter)) {
1.1172.2.22  raeburn  5658:                 my $rep;
                   5659:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
                   5660:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
                   5661:                         join(":", (&host_domain($tryserver), $sincefilter,
                   5662:                                 &escape($descfilter), &escape($instcodefilter),
                   5663:                                 &escape($ownerfilter), &escape($coursefilter),
                   5664:                                 &escape($typefilter), &escape($regexp_ok),
                   5665:                                 $as_hash, &escape($selfenrollonly),
                   5666:                                 &escape($catfilter), $showhidden, $caller,
                   5667:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
                   5668:                                 &escape($createdbefore), &escape($createdafter),
1.1172.2.68  raeburn  5669:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5670:                                 $reqcrsdom,&escape($reqinstcode))));
1.1172.2.22  raeburn  5671:                 } else {
                   5672:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5673:                              $sincefilter.':'.&escape($descfilter).':'.
                   5674:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5675:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5676:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5677:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5678:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5679:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5680:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1172.2.68  raeburn  5681:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5682:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1172.2.22  raeburn  5683:                 }
                   5684: 
1.918     raeburn  5685:                 my @pairs=split(/\&/,$rep);
                   5686:                 foreach my $item (@pairs) {
                   5687:                     my ($key,$value)=split(/\=/,$item,2);
                   5688:                     $key = &unescape($key);
                   5689:                     next if ($key =~ /^error: 2 /);
                   5690:                     my $result = &thaw_unescape($value);
                   5691:                     if (ref($result) eq 'HASH') {
                   5692:                         $returnhash{$key}=$result;
                   5693:                     } else {
1.921     raeburn  5694:                         my @responses = split(/:/,$value);
                   5695:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5696:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5697:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5698:                         }
1.1008    raeburn  5699:                     }
1.353     www      5700:                 }
                   5701:             }
                   5702:         }
                   5703:     }
                   5704:     return %returnhash;
                   5705: }
                   5706: 
1.1055    raeburn  5707: sub courselastaccess {
                   5708:     my ($cdom,$cnum,$hostidref) = @_;
                   5709:     my %returnhash;
                   5710:     if ($cdom && $cnum) {
                   5711:         my $chome = &homeserver($cnum,$cdom);
                   5712:         if ($chome ne 'no_host') {
                   5713:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5714:             &extract_lastaccess(\%returnhash,$rep);
                   5715:         }
                   5716:     } else {
                   5717:         if (!$cdom) { $cdom=''; }
                   5718:         my %libserv = &all_library();
                   5719:         foreach my $tryserver (keys(%libserv)) {
                   5720:             if (ref($hostidref) eq 'ARRAY') {
                   5721:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5722:             } 
                   5723:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5724:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5725:                 &extract_lastaccess(\%returnhash,$rep);
                   5726:             }
                   5727:         }
                   5728:     }
                   5729:     return %returnhash;
                   5730: }
                   5731: 
                   5732: sub extract_lastaccess {
                   5733:     my ($returnhash,$rep) = @_;
                   5734:     if (ref($returnhash) eq 'HASH') {
                   5735:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5736:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5737:                  $rep eq '') {
                   5738:             my @pairs=split(/\&/,$rep);
                   5739:             foreach my $item (@pairs) {
                   5740:                 my ($key,$value)=split(/\=/,$item,2);
                   5741:                 $key = &unescape($key);
                   5742:                 next if ($key =~ /^error: 2 /);
                   5743:                 $returnhash->{$key} = &thaw_unescape($value);
                   5744:             }
                   5745:         }
                   5746:     }
                   5747:     return;
                   5748: }
                   5749: 
1.658     raeburn  5750: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5751: 
                   5752: sub dcmailput {
1.685     raeburn  5753:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5754:     my $status = &Apache::lonnet::critical(
1.740     www      5755:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5756:        &escape($message),$server);
1.662     raeburn  5757:     return $status;
                   5758: }
                   5759: 
1.658     raeburn  5760: sub dcmaildump {
                   5761:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5762:     my %returnhash=();
1.846     albertel 5763: 
                   5764:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5765:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5766:                                                          &escape($enddate).':';
                   5767: 	my @esc_senders=map { &escape($_)} @$senders;
                   5768: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5769: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5770:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5771:             if (($key) && ($value)) {
                   5772:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5773:             }
                   5774:         }
                   5775:     }
                   5776:     return %returnhash;
                   5777: }
1.662     raeburn  5778: # ---------------------------------------------------------- Domain roles
                   5779: 
                   5780: sub get_domain_roles {
                   5781:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5782:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5783:         $startdate = '.';
                   5784:     }
1.1018    raeburn  5785:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5786:         $enddate = '.';
                   5787:     }
1.922     raeburn  5788:     my $rolelist;
                   5789:     if (ref($roles) eq 'ARRAY') {
1.1172.2.23  raeburn  5790:         $rolelist = join('&',@{$roles});
1.922     raeburn  5791:     }
1.662     raeburn  5792:     my %personnel = ();
1.841     albertel 5793: 
                   5794:     my %servers = &get_servers($dom,'library');
                   5795:     foreach my $tryserver (keys(%servers)) {
                   5796: 	%{$personnel{$tryserver}}=();
                   5797: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5798: 					    &escape($startdate).':'.
                   5799: 					    &escape($enddate).':'.
                   5800: 					    &escape($rolelist), $tryserver))) {
                   5801: 	    my ($key,$value) = split(/\=/,$line,2);
                   5802: 	    if (($key) && ($value)) {
                   5803: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5804: 	    }
                   5805: 	}
1.662     raeburn  5806:     }
                   5807:     return %personnel;
                   5808: }
1.658     raeburn  5809: 
1.1172.2.89  raeburn  5810: sub get_active_domroles {
                   5811:     my ($dom,$roles) = @_;
                   5812:     return () unless (ref($roles) eq 'ARRAY');
                   5813:     my $now = time;
                   5814:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5815:     my %domroles;
                   5816:     foreach my $server (keys(%dompersonnel)) {
                   5817:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5818:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5819:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5820:         }
                   5821:     }
                   5822:     return %domroles;
                   5823: }
                   5824: 
1.1057    www      5825: # ----------------------------------------------------------- Interval timing 
1.149     www      5826: 
1.1153    www      5827: {
                   5828: # Caches needed for speedup of navmaps
                   5829: # We don't want to cache this for very long at all (5 seconds at most)
                   5830: # 
                   5831: # The user for whom we cache
                   5832: my $cachedkey='';
                   5833: # The cached times for this user
                   5834: my %cachedtimes=();
                   5835: # When this was last done
1.1172.2.66  raeburn  5836: my $cachedtime='';
1.1153    www      5837: 
                   5838: sub load_all_first_access {
1.1172.2.146.  .1(raebu 5839:22):     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5840:     if (($cachedkey eq $uname.':'.$udom) &&
1.1172.2.146.  .1(raebu 5841:22):         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5842:22):         (!$ignorecache)) {
1.1154    raeburn  5843:         return;
                   5844:     }
                   5845:     $cachedtime=time;
                   5846:     $cachedkey=$uname.':'.$udom;
                   5847:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5848: }
                   5849: 
1.504     albertel 5850: sub get_first_access {
1.1172.2.146.  .1(raebu 5851:22):     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5852:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5853:     if ($argsymb) { $symb=$argsymb; }
                   5854:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5855:     if ($argmap) { $map = $argmap; }
1.926     albertel 5856:     if ($type eq 'course') {
                   5857: 	$res='course';
                   5858:     } elsif ($type eq 'map') {
1.588     albertel 5859: 	$res=&symbread($map);
                   5860:     } else {
                   5861: 	$res=$symb;
                   5862:     }
1.1172.2.146.  .1(raebu 5863:22):     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5864:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5865: }
                   5866: 
                   5867: sub set_first_access {
1.1162    raeburn  5868:     my ($type,$interval)=@_;
1.790     albertel 5869:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5870:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5871:     if ($type eq 'course') {
                   5872: 	$res='course';
                   5873:     } elsif ($type eq 'map') {
1.588     albertel 5874: 	$res=&symbread($map);
                   5875:     } else {
                   5876: 	$res=$symb;
                   5877:     }
1.1153    www      5878:     $cachedkey='';
1.1162    raeburn  5879:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1172.2.102  raeburn  5880:     if ($firstaccess) {
                   5881:         &logthis("First access time already set ($firstaccess) when attempting ".
                   5882:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5883:                  "in $courseid");
                   5884:         return 'already_set';
                   5885:     } else {
1.1162    raeburn  5886:         my $start = time;
                   5887: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5888:                           $udom,$uname);
                   5889:         if ($putres eq 'ok') {
                   5890:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5891:                  $udom,$uname); 
                   5892:             &appenv(
                   5893:                      {
                   5894:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5895:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5896:                      }
                   5897:                   );
1.1172.2.97  raeburn  5898:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5899:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5900:             }
1.1172.2.102  raeburn  5901:         } elsif ($putres ne 'refused') {
                   5902:             &logthis("Result: $putres when attempting to set first access time ".
                   5903:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5904:         }
                   5905:         return $putres;
1.505     albertel 5906:     }
                   5907:     return 'already_set';
1.504     albertel 5908: }
1.1153    www      5909: }
1.1172.2.32  raeburn  5910: 
                   5911: sub checkout {
                   5912:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
                   5913:     my $now=time;
                   5914:     my $lonhost=$perlvar{'lonHostID'};
1.1172.2.134  raeburn  5915:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5916:     my $infostr=&escape(
                   5917:                  'CHECKOUTTOKEN&'.
                   5918:                  $tuname.'&'.
                   5919:                  $tudom.'&'.
                   5920:                  $tcrsid.'&'.
                   5921:                  $symb.'&'.
1.1172.2.134  raeburn  5922:                  $now.'&'.$ip);
1.1172.2.32  raeburn  5923:     my $token=&reply('tmpput:'.$infostr,$lonhost);
                   5924:     if ($token=~/^error\:/) {
                   5925:         &logthis("<font color=\"blue\">WARNING: ".
                   5926:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5927:                  "</font>");
                   5928:         return '';
                   5929:     }
                   5930: 
                   5931:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
                   5932:     $token=~tr/a-z/A-Z/;
                   5933: 
                   5934:     my %infohash=('resource.0.outtoken' => $token,
                   5935:                   'resource.0.checkouttime' => $now,
1.1172.2.134  raeburn  5936:                   'resource.0.outremote' => $ip);
1.1172.2.32  raeburn  5937: 
                   5938:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5939:        return '';
                   5940:     } else {
                   5941:         &logthis("<font color=\"blue\">WARNING: ".
                   5942:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5943:                  "</font>");
                   5944:     }
                   5945: 
                   5946:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5947:                          &escape('Checkout '.$infostr.' - '.
                   5948:                                                  $token)) ne 'ok') {
                   5949:         return '';
                   5950:     } else {
                   5951:         &logthis("<font color=\"blue\">WARNING: ".
                   5952:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
                   5953:                  "</font>");
                   5954:     }
                   5955:     return $token;
                   5956: }
                   5957: 
                   5958: # ------------------------------------------------------------ Check in an item
                   5959: 
                   5960: sub checkin {
                   5961:     my $token=shift;
                   5962:     my $now=time;
                   5963:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
                   5964:     $lonhost=~tr/A-Z/a-z/;
                   5965:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
                   5966:     $dtoken=~s/\W/\_/g;
1.1172.2.134  raeburn  5967:     my $ip = &get_requestor_ip();
1.1172.2.32  raeburn  5968:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
                   5969:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
                   5970: 
                   5971:     unless (($tuname) && ($tudom)) {
                   5972:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
                   5973:         return '';
                   5974:     }
                   5975: 
                   5976:     unless (&allowed('mgr',$tcrsid)) {
                   5977:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
                   5978:                  $env{'user.name'}.' - '.$env{'user.domain'});
                   5979:         return '';
                   5980:     }
                   5981: 
                   5982:     my %infohash=('resource.0.intoken' => $token,
                   5983:                   'resource.0.checkintime' => $now,
1.1172.2.134  raeburn  5984:                   'resource.0.inremote' => $ip);
1.1172.2.32  raeburn  5985: 
                   5986:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
                   5987:        return '';
                   5988:     }
                   5989: 
                   5990:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
                   5991:                          &escape('Checkin - '.$token)) ne 'ok') {
                   5992:         return '';
                   5993:     }
                   5994: 
                   5995:     return ($symb,$tuname,$tudom,$tcrsid);
                   5996: }
                   5997: 
1.110     www      5998: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5999: 
                   6000: sub expirespread {
                   6001:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 6002:     my $cid=$env{'request.course.id'}; 
1.110     www      6003:     if ($cid) {
                   6004:        my $now=time;
                   6005:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 6006:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   6007:                             $env{'course.'.$cid.'.num'}.
1.110     www      6008: 	        	    ':nohist_expirationdates:'.
                   6009:                             &escape($key).'='.$now,
1.620     albertel 6010:                             $env{'course.'.$cid.'.home'})
1.110     www      6011:     }
                   6012:     return 'ok';
1.14      www      6013: }
                   6014: 
1.109     www      6015: # ----------------------------------------------------- Devalidate Spreadsheets
                   6016: 
                   6017: sub devalidate {
1.325     www      6018:     my ($symb,$uname,$udom)=@_;
1.620     albertel 6019:     my $cid=$env{'request.course.id'}; 
1.109     www      6020:     if ($cid) {
1.391     matthew  6021:         # delete the stored spreadsheets for
                   6022:         # - the student level sheet of this user in course's homespace
                   6023:         # - the assessment level sheet for this resource 
                   6024:         #   for this user in user's homespace
1.553     albertel 6025: 	# - current conditional state info
1.325     www      6026: 	my $key=$uname.':'.$udom.':';
1.109     www      6027:         my $status=
1.299     matthew  6028: 	    &del('nohist_calculatedsheets',
1.391     matthew  6029: 		 [$key.'studentcalc:'],
1.620     albertel 6030: 		 $env{'course.'.$cid.'.domain'},
                   6031: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 6032: 		.' '.
                   6033: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  6034: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      6035:         unless ($status eq 'ok ok') {
                   6036:            &logthis('Could not devalidate spreadsheet '.
1.325     www      6037:                     $uname.' at '.$udom.' for '.
1.109     www      6038: 		    $symb.': '.$status);
1.133     albertel 6039:         }
1.553     albertel 6040: 	&delenv('user.state.'.$cid);
1.109     www      6041:     }
                   6042: }
                   6043: 
1.265     albertel 6044: sub get_scalar {
                   6045:     my ($string,$end) = @_;
                   6046:     my $value;
                   6047:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   6048: 	$value = $1;
                   6049:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   6050: 	$value = $1;
                   6051:     }
                   6052:     return &unescape($value);
                   6053: }
                   6054: 
                   6055: sub array2str {
                   6056:   my (@array) = @_;
                   6057:   my $result=&arrayref2str(\@array);
                   6058:   $result=~s/^__ARRAY_REF__//;
                   6059:   $result=~s/__END_ARRAY_REF__$//;
                   6060:   return $result;
                   6061: }
                   6062: 
1.204     albertel 6063: sub arrayref2str {
                   6064:   my ($arrayref) = @_;
1.265     albertel 6065:   my $result='__ARRAY_REF__';
1.204     albertel 6066:   foreach my $elem (@$arrayref) {
1.265     albertel 6067:     if(ref($elem) eq 'ARRAY') {
                   6068:       $result.=&arrayref2str($elem).'&';
                   6069:     } elsif(ref($elem) eq 'HASH') {
                   6070:       $result.=&hashref2str($elem).'&';
                   6071:     } elsif(ref($elem)) {
                   6072:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 6073:     } else {
                   6074:       $result.=&escape($elem).'&';
                   6075:     }
                   6076:   }
                   6077:   $result=~s/\&$//;
1.265     albertel 6078:   $result .= '__END_ARRAY_REF__';
1.204     albertel 6079:   return $result;
                   6080: }
                   6081: 
1.168     albertel 6082: sub hash2str {
1.204     albertel 6083:   my (%hash) = @_;
                   6084:   my $result=&hashref2str(\%hash);
1.265     albertel 6085:   $result=~s/^__HASH_REF__//;
                   6086:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 6087:   return $result;
                   6088: }
                   6089: 
                   6090: sub hashref2str {
                   6091:   my ($hashref)=@_;
1.265     albertel 6092:   my $result='__HASH_REF__';
1.800     albertel 6093:   foreach my $key (sort(keys(%$hashref))) {
                   6094:     if (ref($key) eq 'ARRAY') {
                   6095:       $result.=&arrayref2str($key).'=';
                   6096:     } elsif (ref($key) eq 'HASH') {
                   6097:       $result.=&hashref2str($key).'=';
                   6098:     } elsif (ref($key)) {
1.265     albertel 6099:       $result.='=';
1.800     albertel 6100:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 6101:     } else {
1.1132    raeburn  6102: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 6103:     }
                   6104: 
1.800     albertel 6105:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   6106:       $result.=&arrayref2str($hashref->{$key}).'&';
                   6107:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   6108:       $result.=&hashref2str($hashref->{$key}).'&';
                   6109:     } elsif(ref($hashref->{$key})) {
1.265     albertel 6110:        $result.='&';
1.800     albertel 6111:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 6112:     } else {
1.800     albertel 6113:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 6114:     }
                   6115:   }
1.168     albertel 6116:   $result=~s/\&$//;
1.265     albertel 6117:   $result .= '__END_HASH_REF__';
1.168     albertel 6118:   return $result;
                   6119: }
                   6120: 
                   6121: sub str2hash {
1.265     albertel 6122:     my ($string)=@_;
                   6123:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   6124:     return %$hash;
                   6125: }
                   6126: 
                   6127: sub str2hashref {
1.168     albertel 6128:   my ($string) = @_;
1.265     albertel 6129: 
                   6130:   my %hash;
                   6131: 
                   6132:   if($string !~ /^__HASH_REF__/) {
                   6133:       if (! ($string eq '' || !defined($string))) {
                   6134: 	  $hash{'error'}='Not hash reference';
                   6135:       }
                   6136:       return (\%hash, $string);
                   6137:   }
                   6138: 
                   6139:   $string =~ s/^__HASH_REF__//;
                   6140: 
                   6141:   while($string !~ /^__END_HASH_REF__/) {
                   6142:       #key
                   6143:       my $key='';
                   6144:       if($string =~ /^__HASH_REF__/) {
                   6145:           ($key, $string)=&str2hashref($string);
                   6146:           if(defined($key->{'error'})) {
                   6147:               $hash{'error'}='Bad data';
                   6148:               return (\%hash, $string);
                   6149:           }
                   6150:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6151:           ($key, $string)=&str2arrayref($string);
                   6152:           if($key->[0] eq 'Array reference error') {
                   6153:               $hash{'error'}='Bad data';
                   6154:               return (\%hash, $string);
                   6155:           }
                   6156:       } else {
                   6157:           $string =~ s/^(.*?)=//;
1.267     albertel 6158: 	  $key=&unescape($1);
1.265     albertel 6159:       }
                   6160:       $string =~ s/^=//;
                   6161: 
                   6162:       #value
                   6163:       my $value='';
                   6164:       if($string =~ /^__HASH_REF__/) {
                   6165:           ($value, $string)=&str2hashref($string);
                   6166:           if(defined($value->{'error'})) {
                   6167:               $hash{'error'}='Bad data';
                   6168:               return (\%hash, $string);
                   6169:           }
                   6170:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6171:           ($value, $string)=&str2arrayref($string);
                   6172:           if($value->[0] eq 'Array reference error') {
                   6173:               $hash{'error'}='Bad data';
                   6174:               return (\%hash, $string);
                   6175:           }
                   6176:       } else {
                   6177: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   6178:       }
                   6179:       $string =~ s/^&//;
                   6180: 
                   6181:       $hash{$key}=$value;
1.204     albertel 6182:   }
1.265     albertel 6183: 
                   6184:   $string =~ s/^__END_HASH_REF__//;
                   6185: 
                   6186:   return (\%hash, $string);
1.204     albertel 6187: }
                   6188: 
                   6189: sub str2array {
1.265     albertel 6190:     my ($string)=@_;
                   6191:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   6192:     return @$array;
                   6193: }
                   6194: 
                   6195: sub str2arrayref {
1.204     albertel 6196:   my ($string) = @_;
1.265     albertel 6197:   my @array;
                   6198: 
                   6199:   if($string !~ /^__ARRAY_REF__/) {
                   6200:       if (! ($string eq '' || !defined($string))) {
                   6201: 	  $array[0]='Array reference error';
                   6202:       }
                   6203:       return (\@array, $string);
                   6204:   }
                   6205: 
                   6206:   $string =~ s/^__ARRAY_REF__//;
                   6207: 
                   6208:   while($string !~ /^__END_ARRAY_REF__/) {
                   6209:       my $value='';
                   6210:       if($string =~ /^__HASH_REF__/) {
                   6211:           ($value, $string)=&str2hashref($string);
                   6212:           if(defined($value->{'error'})) {
                   6213:               $array[0] ='Array reference error';
                   6214:               return (\@array, $string);
                   6215:           }
                   6216:       } elsif($string =~ /^__ARRAY_REF__/) {
                   6217:           ($value, $string)=&str2arrayref($string);
                   6218:           if($value->[0] eq 'Array reference error') {
                   6219:               $array[0] ='Array reference error';
                   6220:               return (\@array, $string);
                   6221:           }
                   6222:       } else {
                   6223: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   6224:       }
                   6225:       $string =~ s/^&//;
                   6226: 
                   6227:       push(@array, $value);
1.191     harris41 6228:   }
1.265     albertel 6229: 
                   6230:   $string =~ s/^__END_ARRAY_REF__//;
                   6231: 
                   6232:   return (\@array, $string);
1.168     albertel 6233: }
                   6234: 
1.167     albertel 6235: # -------------------------------------------------------------------Temp Store
                   6236: 
1.168     albertel 6237: sub tmpreset {
                   6238:   my ($symb,$namespace,$domain,$stuname) = @_;
                   6239:   if (!$symb) {
                   6240:     $symb=&symbread();
1.620     albertel 6241:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6242:   }
                   6243:   $symb=escape($symb);
                   6244: 
1.620     albertel 6245:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 6246:   $namespace=~s/\//\_/g;
                   6247:   $namespace=~s/\W//g;
                   6248: 
1.620     albertel 6249:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6250:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6251:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6252:       $stuname=&get_requestor_ip();
1.591     albertel 6253:   }
1.1117    foxr     6254:   my $path=LONCAPA::tempdir();
1.168     albertel 6255:   my %hash;
                   6256:   if (tie(%hash,'GDBM_File',
                   6257: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6258: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  6259:     foreach my $key (keys(%hash)) {
1.180     albertel 6260:       if ($key=~ /:$symb/) {
1.168     albertel 6261: 	delete($hash{$key});
                   6262:       }
                   6263:     }
                   6264:   }
                   6265: }
                   6266: 
1.167     albertel 6267: sub tmpstore {
1.168     albertel 6268:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   6269: 
                   6270:   if (!$symb) {
                   6271:     $symb=&symbread();
1.620     albertel 6272:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6273:   }
                   6274:   $symb=escape($symb);
                   6275: 
                   6276:   if (!$namespace) {
                   6277:     # I don't think we would ever want to store this for a course.
                   6278:     # it seems this will only be used if we don't have a course.
1.620     albertel 6279:     #$namespace=$env{'request.course.id'};
1.168     albertel 6280:     #if (!$namespace) {
1.620     albertel 6281:       $namespace=$env{'request.state'};
1.168     albertel 6282:     #}
                   6283:   }
                   6284:   $namespace=~s/\//\_/g;
                   6285:   $namespace=~s/\W//g;
1.620     albertel 6286:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6287:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6288:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6289:       $stuname=&get_requestor_ip();
1.591     albertel 6290:   }
1.168     albertel 6291:   my $now=time;
                   6292:   my %hash;
1.1117    foxr     6293:   my $path=LONCAPA::tempdir();
1.168     albertel 6294:   if (tie(%hash,'GDBM_File',
                   6295: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6296: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 6297:     $hash{"version:$symb"}++;
                   6298:     my $version=$hash{"version:$symb"};
                   6299:     my $allkeys=''; 
                   6300:     foreach my $key (keys(%$storehash)) {
                   6301:       $allkeys.=$key.':';
1.591     albertel 6302:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 6303:     }
                   6304:     $hash{"$version:$symb:timestamp"}=$now;
                   6305:     $allkeys.='timestamp';
                   6306:     $hash{"$version:keys:$symb"}=$allkeys;
                   6307:     if (untie(%hash)) {
                   6308:       return 'ok';
                   6309:     } else {
                   6310:       return "error:$!";
                   6311:     }
                   6312:   } else {
                   6313:     return "error:$!";
                   6314:   }
                   6315: }
1.167     albertel 6316: 
1.168     albertel 6317: # -----------------------------------------------------------------Temp Restore
1.167     albertel 6318: 
1.168     albertel 6319: sub tmprestore {
                   6320:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 6321: 
1.168     albertel 6322:   if (!$symb) {
                   6323:     $symb=&symbread();
1.620     albertel 6324:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 6325:   }
                   6326:   $symb=escape($symb);
                   6327: 
1.620     albertel 6328:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 6329: 
1.620     albertel 6330:   if (!$domain) { $domain=$env{'user.domain'}; }
                   6331:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 6332:   if ($domain eq 'public' && $stuname eq 'public') {
1.1172.2.138  raeburn  6333:       $stuname=&get_requestor_ip();
1.591     albertel 6334:   }
1.168     albertel 6335:   my %returnhash;
                   6336:   $namespace=~s/\//\_/g;
                   6337:   $namespace=~s/\W//g;
                   6338:   my %hash;
1.1117    foxr     6339:   my $path=LONCAPA::tempdir();
1.168     albertel 6340:   if (tie(%hash,'GDBM_File',
                   6341: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 6342: 	  &GDBM_READER(),0640)) {
1.168     albertel 6343:     my $version=$hash{"version:$symb"};
                   6344:     $returnhash{'version'}=$version;
                   6345:     my $scope;
                   6346:     for ($scope=1;$scope<=$version;$scope++) {
                   6347:       my $vkeys=$hash{"$scope:keys:$symb"};
                   6348:       my @keys=split(/:/,$vkeys);
                   6349:       my $key;
                   6350:       $returnhash{"$scope:keys"}=$vkeys;
                   6351:       foreach $key (@keys) {
1.591     albertel 6352: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   6353: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 6354:       }
                   6355:     }
1.168     albertel 6356:     if (!(untie(%hash))) {
                   6357:       return "error:$!";
                   6358:     }
                   6359:   } else {
                   6360:     return "error:$!";
                   6361:   }
                   6362:   return %returnhash;
1.167     albertel 6363: }
                   6364: 
1.9       www      6365: # ----------------------------------------------------------------------- Store
                   6366: 
                   6367: sub store {
1.1172.2.64  raeburn  6368:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6369:     my $home='';
                   6370: 
1.168     albertel 6371:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6372: 
1.213     www      6373:     $symb=&symbclean($symb);
1.122     albertel 6374:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6375: 
1.620     albertel 6376:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6377:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6378: 
                   6379:     &devalidate($symb,$stuname,$domain);
1.109     www      6380: 
                   6381:     $symb=escape($symb);
1.187     www      6382:     if (!$namespace) { 
1.620     albertel 6383:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6384:           return ''; 
                   6385:        } 
                   6386:     }
1.620     albertel 6387:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6388: 
1.1172.2.138  raeburn  6389:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6390:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   6391: 
1.12      www      6392:     my $namevalue='';
1.800     albertel 6393:     foreach my $key (keys(%$storehash)) {
                   6394:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6395:     }
1.12      www      6396:     $namevalue=~s/\&$//;
1.187     www      6397:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1172.2.64  raeburn  6398:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      6399: }
                   6400: 
1.47      www      6401: # -------------------------------------------------------------- Critical Store
                   6402: 
                   6403: sub cstore {
1.1172.2.64  raeburn  6404:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      6405:     my $home='';
                   6406: 
1.168     albertel 6407:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6408: 
1.213     www      6409:     $symb=&symbclean($symb);
1.122     albertel 6410:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      6411: 
1.620     albertel 6412:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6413:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      6414: 
                   6415:     &devalidate($symb,$stuname,$domain);
1.109     www      6416: 
                   6417:     $symb=escape($symb);
1.187     www      6418:     if (!$namespace) { 
1.620     albertel 6419:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      6420:           return ''; 
                   6421:        } 
                   6422:     }
1.620     albertel 6423:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      6424: 
1.1172.2.138  raeburn  6425:     $$storehash{'ip'}=&get_requestor_ip();
1.447     www      6426:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 6427: 
1.47      www      6428:     my $namevalue='';
1.800     albertel 6429:     foreach my $key (keys(%$storehash)) {
                   6430:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 6431:     }
1.47      www      6432:     $namevalue=~s/\&$//;
1.187     www      6433:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      6434:     return critical
1.1172.2.64  raeburn  6435:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      6436: }
                   6437: 
1.9       www      6438: # --------------------------------------------------------------------- Restore
                   6439: 
                   6440: sub restore {
1.124     www      6441:     my ($symb,$namespace,$domain,$stuname) = @_;
                   6442:     my $home='';
                   6443: 
1.168     albertel 6444:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      6445: 
1.122     albertel 6446:     if (!$symb) {
1.1172.2.26  raeburn  6447:         return if ($namespace eq 'courserequests');
                   6448:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6449:     } else {
1.1172.2.26  raeburn  6450:         unless ($namespace eq 'courserequests') {
                   6451:             $symb=&escape(&symbclean($symb));
                   6452:         }
1.122     albertel 6453:     }
1.188     www      6454:     if (!$namespace) { 
1.620     albertel 6455:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      6456:           return ''; 
                   6457:        } 
                   6458:     }
1.620     albertel 6459:     if (!$domain) { $domain=$env{'user.domain'}; }
                   6460:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   6461:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 6462:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   6463: 
1.12      www      6464:     my %returnhash=();
1.800     albertel 6465:     foreach my $line (split(/\&/,$answer)) {
                   6466: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 6467:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 6468:     }
1.75      www      6469:     my $version;
                   6470:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 6471:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   6472:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 6473:        }
1.75      www      6474:     }
1.13      www      6475:     return %returnhash;
1.34      www      6476: }
                   6477: 
                   6478: # ---------------------------------------------------------- Course Description
1.1118    foxr     6479: #
                   6480: #  
1.34      www      6481: 
                   6482: sub coursedescription {
1.731     albertel 6483:     my ($courseid,$args)=@_;
1.34      www      6484:     $courseid=~s/^\///;
1.49      www      6485:     $courseid=~s/\_/\//g;
1.34      www      6486:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 6487:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 6488:     my $normalid=$cdomain.'_'.$cnum;
                   6489:     # need to always cache even if we get errors otherwise we keep 
                   6490:     # trying and trying and trying to get the course description.
                   6491:     my %envhash=();
                   6492:     my %returnhash=();
1.731     albertel 6493:     
                   6494:     my $expiretime=600;
                   6495:     if ($env{'request.course.id'} eq $normalid) {
                   6496: 	$expiretime=120;
                   6497:     }
                   6498: 
                   6499:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   6500:     if (!$args->{'freshen_cache'}
                   6501: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   6502: 	foreach my $key (keys(%env)) {
                   6503: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   6504: 	    my ($setting) = $1;
                   6505: 	    $returnhash{$setting} = $env{$key};
                   6506: 	}
                   6507: 	return %returnhash;
                   6508:     }
                   6509: 
1.1118    foxr     6510:     # get the data again
                   6511: 
1.731     albertel 6512:     if (!$args->{'one_time'}) {
                   6513: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   6514:     }
1.811     albertel 6515: 
1.34      www      6516:     if ($chome ne 'no_host') {
1.302     albertel 6517:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 6518:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     6519: 	   my $username = $env{'user.name'}; # Defult username
                   6520: 	   if(defined $args->{'user'}) {
                   6521: 	       $username = $args->{'user'};
                   6522: 	   }
1.129     albertel 6523:            $returnhash{'home'}= $chome;
                   6524: 	   $returnhash{'domain'} = $cdomain;
                   6525: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  6526:            if (!defined($returnhash{'type'})) {
                   6527:                $returnhash{'type'} = 'Course';
                   6528:            }
1.130     albertel 6529:            while (my ($name,$value) = each %returnhash) {
1.53      www      6530:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 6531:            }
1.270     www      6532:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     6533:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     6534: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      6535:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   6536:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   6537:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      6538:        }
                   6539:     }
1.731     albertel 6540:     if (!$args->{'one_time'}) {
1.949     raeburn  6541: 	&appenv(\%envhash);
1.731     albertel 6542:     }
1.302     albertel 6543:     return %returnhash;
1.461     www      6544: }
                   6545: 
1.1080    raeburn  6546: sub update_released_required {
                   6547:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   6548:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   6549:         $cid = $env{'request.course.id'};
                   6550:         $cdom = $env{'course.'.$cid.'.domain'};
                   6551:         $cnum = $env{'course.'.$cid.'.num'};
                   6552:         $chome = $env{'course.'.$cid.'.home'};
                   6553:     }
                   6554:     if ($needsrelease) {
                   6555:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   6556:         my $needsupdate;
                   6557:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   6558:             $needsupdate = 1;
                   6559:         } else {
                   6560:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   6561:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   6562:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   6563:                 $needsupdate = 1;
                   6564:             }
                   6565:         }
                   6566:         if ($needsupdate) {
                   6567:             my %needshash = (
                   6568:                              'internal.releaserequired' => $needsrelease,
                   6569:                             );
                   6570:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   6571:             if ($putresult eq 'ok') {
                   6572:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   6573:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   6574:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   6575:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   6576:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   6577:                 }
                   6578:             }
                   6579:         }
                   6580:     }
                   6581:     return;
                   6582: }
                   6583: 
1.461     www      6584: # -------------------------------------------------See if a user is privileged
                   6585: 
                   6586: sub privileged {
1.1172.2.23  raeburn  6587:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6588:     my $now = time;
1.1172.2.23  raeburn  6589:     my $roles;
                   6590:     if (ref($possroles) eq 'ARRAY') {
                   6591:         $roles = $possroles;
                   6592:     } else {
                   6593:         $roles = ['dc','su'];
                   6594:     }
                   6595:     if (ref($possdomains) eq 'ARRAY') {
                   6596:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   6597:         foreach my $dom (@{$possdomains}) {
                   6598:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   6599:                 (ref($privileged{$dom}) eq 'HASH')) {
                   6600:                 foreach my $role (@{$roles}) {
                   6601:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6602:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   6603:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   6604:                             return 1 unless (($end && $end < $now) ||
                   6605:                                              ($start && $start > $now));
                   6606:                         }
                   6607:                     }
                   6608:                 }
                   6609:             }
                   6610:         }
                   6611:     } else {
                   6612:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   6613:         my $now = time;
1.1170    droeschl 6614: 
1.1172.2.58  raeburn  6615:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6616:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1172.2.23  raeburn  6617:             if (grep(/^\Q$trole\E$/,@{$roles})) {
                   6618:                 return 1 unless ($tend && $tend < $now)
                   6619:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6620:             }
1.1172.2.23  raeburn  6621:         }
                   6622:     }
1.461     www      6623:     return 0;
1.9       www      6624: }
1.1       albertel 6625: 
1.1172.2.23  raeburn  6626: sub privileged_by_domain {
                   6627:     my ($domains,$roles) = @_;
                   6628:     my %privileged = ();
                   6629:     my $cachetime = 60*60*24;
                   6630:     my $now = time;
                   6631:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   6632:         return %privileged;
                   6633:     }
                   6634:     foreach my $dom (@{$domains}) {
                   6635:         next if (ref($privileged{$dom}) eq 'HASH');
                   6636:         my $needroles;
                   6637:         foreach my $role (@{$roles}) {
                   6638:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   6639:             if (defined($cached)) {
                   6640:                 if (ref($result) eq 'HASH') {
                   6641:                     $privileged{$dom}{$role} = $result;
                   6642:                 }
                   6643:             } else {
                   6644:                 $needroles = 1;
                   6645:             }
                   6646:         }
                   6647:         if ($needroles) {
                   6648:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   6649:             $privileged{$dom} = {};
                   6650:             foreach my $server (keys(%dompersonnel)) {
                   6651:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   6652:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   6653:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   6654:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   6655:                         next if ($end && $end < $now);
                   6656:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
                   6657:                             $dompersonnel{$server}{$item};
                   6658:                     }
                   6659:                 }
                   6660:             }
                   6661:             if (ref($privileged{$dom}) eq 'HASH') {
                   6662:                 foreach my $role (@{$roles}) {
                   6663:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   6664:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   6665:                     } else {
                   6666:                         my %hash = ();
                   6667:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   6668:                     }
                   6669:                 }
                   6670:             }
                   6671:         }
                   6672:     }
                   6673:     return %privileged;
                   6674: }
                   6675: 
1.103     harris41 6676: # -------------------------------------------------------- Get user privileges
1.11      www      6677: 
                   6678: sub rolesinit {
1.1169    droeschl 6679:     my ($domain, $username) = @_;
                   6680:     my %userroles = ('user.login.time' => time);
                   6681:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   6682: 
                   6683:     # firstaccess and timerinterval are related to timed maps/resources. 
                   6684:     # also, blocking can be triggered by an activating timer
                   6685:     # it's saved in the user's %env.
                   6686:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   6687:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   6688:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   6689:         %timerintchk, %timerintenv);
                   6690: 
1.1162    raeburn  6691:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 6692:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  6693:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   6694:     }
1.1169    droeschl 6695: 
1.1162    raeburn  6696:     foreach my $key (keys(%timerinterval)) {
                   6697:         my ($cid,$rest) = split(/\0/,$key);
                   6698:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   6699:     }
1.1169    droeschl 6700: 
1.11      www      6701:     my %allroles=();
1.1162    raeburn  6702:     my %allgroups=();
1.11      www      6703: 
1.1172.2.58  raeburn  6704:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 6705:         my $role = $rolesdump{$area};
                   6706:         $area =~ s/\_\w\w$//;
                   6707: 
                   6708:         my ($trole, $tend, $tstart, $group_privs);
                   6709: 
                   6710:         if ($role =~ /^cr/) {
                   6711:         # Custom role, defined by a user 
                   6712:         # e.g., user.role.cr/msu/smith/mynewrole
                   6713:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   6714:                 $trole = $1;
                   6715:                 ($tend, $tstart) = split('_', $2);
                   6716:             } else {
                   6717:                 $trole = $role;
                   6718:             }
                   6719:         } elsif ($role =~ m|^gr/|) {
                   6720:         # Role of member in a group, defined within a course/community
                   6721:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   6722:             ($trole, $tend, $tstart) = split(/_/, $role);
                   6723:             next if $tstart eq '-1';
                   6724:             ($trole, $group_privs) = split(/\//, $trole);
                   6725:             $group_privs = &unescape($group_privs);
                   6726:         } else {
                   6727:         # Just a normal role, defined in roles.tab
                   6728:             ($trole, $tend, $tstart) = split(/_/,$role);
                   6729:         }
                   6730: 
                   6731:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   6732:                  $username);
                   6733:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   6734: 
                   6735:         # role expired or not available yet?
                   6736:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   6737:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   6738: 
                   6739:         next if $area eq '' or $trole eq '';
                   6740: 
                   6741:         my $spec = "$trole.$area";
                   6742:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   6743: 
                   6744:         if ($trole =~ /^cr\//) {
                   6745:         # Custom role, defined by a user
                   6746:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   6747:         } elsif ($trole eq 'gr') {
                   6748:         # Role of a member in a group, defined within a course/community
                   6749:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6750:             next;
                   6751:         } else {
                   6752:         # Normal role, defined in roles.tab
                   6753:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6754:         }
                   6755: 
                   6756:         my $cid = $tdomain.'_'.$trest;
                   6757:         unless ($firstaccchk{$cid}) {
                   6758:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6759:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6760:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6761:                         $coursetimerstarts{$cid}{$item}; 
                   6762:                 }
                   6763:             }
                   6764:             $firstaccchk{$cid} = 1;
                   6765:         }
                   6766:         unless ($timerintchk{$cid}) {
                   6767:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6768:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6769:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6770:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6771:                 }
1.12      www      6772:             }
1.1169    droeschl 6773:             $timerintchk{$cid} = 1;
1.191     harris41 6774:         }
1.11      www      6775:     }
1.1169    droeschl 6776: 
1.1172.2.91  raeburn  6777:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6778:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6779:     $env{'user.adv'} = $userroles{'user.adv'};
1.1172.2.91  raeburn  6780:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6781: 
1.1162    raeburn  6782:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6783: }
                   6784: 
1.567     raeburn  6785: sub set_arearole {
1.1172.2.19  raeburn  6786:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6787:     unless ($nolog) {
1.567     raeburn  6788: # log the associated role with the area
1.1172.2.19  raeburn  6789:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6790:     }
1.743     albertel 6791:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6792: }
                   6793: 
                   6794: sub custom_roleprivs {
                   6795:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6796:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1172.2.40  raeburn  6797:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6798:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6799:         my ($rdummy,$roledef)=
                   6800:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6801:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6802:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6803:             if (defined($syspriv)) {
1.1043    raeburn  6804:                 if ($trest =~ /^$match_community$/) {
                   6805:                     $syspriv =~ s/bre\&S//; 
                   6806:                 }
1.567     raeburn  6807:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6808:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6809:             }
                   6810:             if ($tdomain ne '') {
                   6811:                 if (defined($dompriv)) {
                   6812:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6813:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6814:                 }
                   6815:                 if (($trest ne '') && (defined($coursepriv))) {
1.1172.2.89  raeburn  6816:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6817:                         my $rolename = $1;
                   6818:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6819:                     }
1.567     raeburn  6820:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6821:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6822:                 }
                   6823:             }
                   6824:         }
                   6825:     }
                   6826: }
                   6827: 
1.1172.2.89  raeburn  6828: sub course_adhocrole_privs {
                   6829:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6830:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6831:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6832:         my (%currprivs,%storeprivs);
                   6833:         foreach my $item (split(/:/,$coursepriv)) {
                   6834:             my ($priv,$restrict) = split(/\&/,$item);
                   6835:             $currprivs{$priv} = $restrict;
                   6836:         }
                   6837:         my (%possadd,%possremove,%full);
                   6838:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6839:             my ($priv,$restrict)=split(/\&/,$item);
                   6840:             $full{$priv} = $restrict;
                   6841:         }
                   6842:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
1.1172.2.146.  .6(raebu 6843:22):             next if ($item eq '');
                   6844:22):             my ($rule,$rest) = split(/=/,$item);
                   6845:22):             next unless (($rule eq 'off') || ($rule eq 'on'));
                   6846:22):             foreach my $priv (split(/:/,$rest)) {
                   6847:22):                 if ($priv ne '') {
                   6848:22):                     if ($rule eq 'off') {
                   6849:22):                         $possremove{$priv} = 1;
                   6850:22):                     } else {
                   6851:22):                         $possadd{$priv} = 1;
                   6852:22):                     }
                   6853:22):                 }
                   6854:22):             }
                   6855:22):         }
                   6856:22):         foreach my $priv (sort(keys(%full))) {
                   6857:22):             if (exists($currprivs{$priv})) {
                   6858:22):                 unless (exists($possremove{$priv})) {
                   6859:22):                     $storeprivs{$priv} = $currprivs{$priv};
                   6860:22):                 }
                   6861:22):             } elsif (exists($possadd{$priv})) {
                   6862:22):                 $storeprivs{$priv} = $full{$priv};
                   6863:22):             }
                   6864:22):         }
                   6865:22):         $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6866:22):     }
                   6867:22):     return $coursepriv;
1.1172.2.89  raeburn  6868: }
                   6869: 
1.678     raeburn  6870: sub group_roleprivs {
                   6871:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6872:     my $access = 1;
                   6873:     my $now = time;
                   6874:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6875:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6876:     if ($access) {
1.811     albertel 6877:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6878:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6879:     }
                   6880: }
1.567     raeburn  6881: 
                   6882: sub standard_roleprivs {
                   6883:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6884:     if (defined($pr{$trole.':s'})) {
                   6885:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6886:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6887:     }
                   6888:     if ($tdomain ne '') {
                   6889:         if (defined($pr{$trole.':d'})) {
                   6890:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6891:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6892:         }
                   6893:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6894:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6895:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6896:         }
                   6897:     }
                   6898: }
                   6899: 
                   6900: sub set_userprivs {
1.1064    raeburn  6901:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6902:     my $author=0;
                   6903:     my $adv=0;
1.1172.2.91  raeburn  6904:     my $rar=0;
1.678     raeburn  6905:     my %grouproles = ();
                   6906:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6907:         my @groupkeys; 
1.1000    raeburn  6908:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6909:             push(@groupkeys,$role);
                   6910:         }
                   6911:         if (ref($groups_roles) eq 'HASH') {
                   6912:             foreach my $key (keys(%{$groups_roles})) {
                   6913:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6914:                     push(@groupkeys,$key);
                   6915:                 }
                   6916:             }
                   6917:         }
                   6918:         if (@groupkeys > 0) {
                   6919:             foreach my $role (@groupkeys) {
                   6920:                 my ($trole,$area,$sec,$extendedarea);
                   6921:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6922:                     $trole = $1;
                   6923:                     $area = $2;
                   6924:                     $sec = $3;
                   6925:                     $extendedarea = $area.$sec;
                   6926:                     if (exists($$allgroups{$area})) {
                   6927:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6928:                             my $spec = $trole.'.'.$extendedarea;
                   6929:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6930:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6931:                         }
1.678     raeburn  6932:                     }
                   6933:                 }
                   6934:             }
                   6935:         }
                   6936:     }
1.800     albertel 6937:     foreach my $group (keys(%grouproles)) {
                   6938:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6939:     }
1.800     albertel 6940:     foreach my $role (keys(%{$allroles})) {
                   6941:         my %thesepriv;
1.941     raeburn  6942:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6943:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6944:             if ($item ne '') {
                   6945:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6946:                 if ($restrictions eq '') {
                   6947:                     $thesepriv{$privilege}='F';
                   6948:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6949:                     $thesepriv{$privilege}.=$restrictions;
                   6950:                 }
                   6951:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1172.2.91  raeburn  6952:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6953:             }
                   6954:         }
                   6955:         my $thesestr='';
1.1104    raeburn  6956:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6957: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6958: 	}
                   6959:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6960:     }
1.1172.2.91  raeburn  6961:     return ($author,$adv,$rar);
1.567     raeburn  6962: }
                   6963: 
1.994     raeburn  6964: sub role_status {
1.1104    raeburn  6965:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6966:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1172.2.40  raeburn  6967:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6968:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6969:         unless (!defined($$role) || $$role eq '') {
1.1172.2.40  raeburn  6970:             $$where = '/'.$two;
1.994     raeburn  6971:             $$trolecode=$$role.'.'.$$where;
                   6972:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6973:             $$tstatus='is';
1.1104    raeburn  6974:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6975:                 $$tstatus='future';
1.1034    raeburn  6976:                 if ($$tstart<$now) {
                   6977:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6978:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6979:                             my (%allroles,%allgroups,$group_privs,
                   6980:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6981:                             my %userroles = (
                   6982:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6983:                             );
1.1064    raeburn  6984:                             @rolecodes = ('cm'); 
1.1002    raeburn  6985:                             my $spec=$$role.'.'.$$where;
                   6986:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6987:                             if ($$role =~ /^cr\//) {
                   6988:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6989:                                 push(@rolecodes,'cr');
1.1002    raeburn  6990:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6991:                                 push(@rolecodes,$$role);
1.1002    raeburn  6992:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6993:                                                     $env{'user.name'});
1.1064    raeburn  6994:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6995:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6996:                                 $group_privs = &unescape($group_privs);
                   6997:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6998:                                 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  6999:                                 &get_groups_roles($tdomain,$trest,
                   7000:                                                   \%course_roles,\@rolecodes,
                   7001:                                                   \%groups_roles);
1.1002    raeburn  7002:                             } else {
1.1064    raeburn  7003:                                 push(@rolecodes,$$role);
1.1002    raeburn  7004:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   7005:                             }
1.1172.2.91  raeburn  7006:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   7007:                                                                    \%groups_roles);
1.1064    raeburn  7008:                             &appenv(\%userroles,\@rolecodes);
1.1172.2.92  raeburn  7009:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  7010:                         }
                   7011:                     }
1.1034    raeburn  7012:                     $$tstatus = 'is';
1.1002    raeburn  7013:                 }
1.994     raeburn  7014:             }
                   7015:             if ($$tend) {
1.1104    raeburn  7016:                 if ($$tend<$update) {
1.994     raeburn  7017:                     $$tstatus='expired';
                   7018:                 } elsif ($$tend<$now) {
                   7019:                     $$tstatus='will_not';
                   7020:                 }
                   7021:             }
                   7022:         }
                   7023:     }
                   7024: }
                   7025: 
1.1104    raeburn  7026: sub get_groups_roles {
                   7027:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   7028:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   7029:                   (ref($rolecodes) eq 'ARRAY') && 
                   7030:                   (ref($groups_roles) eq 'HASH')); 
                   7031:     if (keys(%{$cdom_courseroles}) > 0) {
                   7032:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   7033:         if ($cdom ne '' && $cnum ne '') {
                   7034:             foreach my $key (keys(%{$cdom_courseroles})) {
                   7035:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   7036:                     my $crsrole = $1;
                   7037:                     my $crssec = $2;
                   7038:                     if ($crsrole =~ /^cr/) {
                   7039:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   7040:                             push(@{$rolecodes},'cr');
                   7041:                         }
                   7042:                     } else {
                   7043:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   7044:                             push(@{$rolecodes},$crsrole);
                   7045:                         }
                   7046:                     }
                   7047:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   7048:                     if ($crssec ne '') {
                   7049:                         $rolekey .= "/$crssec";
                   7050:                     }
                   7051:                     $rolekey .= './';
                   7052:                     $groups_roles->{$rolekey} = $rolecodes;
                   7053:                 }
                   7054:             }
                   7055:         }
                   7056:     }
                   7057:     return;
                   7058: }
                   7059: 
                   7060: sub delete_env_groupprivs {
                   7061:     my ($where,$courseroles,$possroles) = @_;
                   7062:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   7063:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   7064:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   7065:         %{$courseroles->{$udom}} =
                   7066:             &get_my_roles('','','userroles',['active'],
                   7067:                           $possroles,[$udom],1);
                   7068:     }
                   7069:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   7070:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   7071:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   7072:             my $area = '/'.$cdom.'/'.$cnum;
                   7073:             my $privkey = "user.priv.$crsrole.$area";
                   7074:             if ($crssec ne '') {
                   7075:                 $privkey .= '/'.$crssec;
                   7076:             }
                   7077:             $privkey .= ".$area/$group";
                   7078:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   7079:         }
                   7080:     }
                   7081:     return;
                   7082: }
                   7083: 
1.994     raeburn  7084: sub check_adhoc_privs {
1.1172.2.86  raeburn  7085:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  7086:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1172.2.86  raeburn  7087:     if ($sec) {
                   7088:         $cckey .= '/'.$sec;
                   7089:     }
1.1172.2.9  raeburn  7090:     my $setprivs;
1.994     raeburn  7091:     if ($env{$cckey}) {
                   7092:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  7093:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  7094:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1172.2.86  raeburn  7095:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  7096:             $setprivs = 1;
1.994     raeburn  7097:         }
                   7098:     } else {
1.1172.2.87  raeburn  7099:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1172.2.9  raeburn  7100:         $setprivs = 1;
1.994     raeburn  7101:     }
1.1172.2.9  raeburn  7102:     return $setprivs;
1.994     raeburn  7103: }
                   7104: 
                   7105: sub set_adhoc_privileges {
1.1172.2.84  raeburn  7106: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1172.2.86  raeburn  7107:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  7108:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1172.2.86  raeburn  7109:     if ($sec ne '') {
                   7110:         $area .= '/'.$sec;
                   7111:     }
1.994     raeburn  7112:     my $spec = $role.'.'.$area;
                   7113:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1172.2.19  raeburn  7114:                                   $env{'user.name'},1);
1.1172.2.84  raeburn  7115:     my %rolehash = ();
1.1172.2.89  raeburn  7116:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   7117:         my $rolename = $1;
1.1172.2.84  raeburn  7118:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1172.2.89  raeburn  7119:         my %domdef = &get_domain_defaults($dcdom);
                   7120:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   7121:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   7122:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   7123:             }
                   7124:         }
1.1172.2.84  raeburn  7125:     } else {
                   7126:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   7127:     }
1.1172.2.91  raeburn  7128:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  7129:     &appenv(\%userroles,[$role,'cm']);
1.1172.2.92  raeburn  7130:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1172.2.146.  .1(raebu 7131:22):     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
                   7132:22):             ($caller eq 'tiny')) {
1.1088    raeburn  7133:         &appenv( {'request.role'        => $spec,
                   7134:                   'request.role.domain' => $dcdom,
1.1172.2.89  raeburn  7135:                   'request.course.sec'  => $sec, 
1.1088    raeburn  7136:                  }
                   7137:                );
                   7138:         my $tadv=0;
                   7139:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   7140:         &appenv({'request.role.adv'    => $tadv});
                   7141:     }
1.994     raeburn  7142: }
                   7143: 
1.12      www      7144: # --------------------------------------------------------------- get interface
                   7145: 
                   7146: sub get {
1.131     albertel 7147:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7148:    my $items='';
1.800     albertel 7149:    foreach my $item (@$storearr) {
                   7150:        $items.=&escape($item).'&';
1.191     harris41 7151:    }
1.12      www      7152:    $items=~s/\&$//;
1.620     albertel 7153:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7154:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 7155:    my $uhome=&homeserver($uname,$udomain);
                   7156: 
1.133     albertel 7157:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7158:    my @pairs=split(/\&/,$rep);
1.273     albertel 7159:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   7160:      return @pairs;
                   7161:    }
1.15      www      7162:    my %returnhash=();
1.42      www      7163:    my $i=0;
1.800     albertel 7164:    foreach my $item (@$storearr) {
                   7165:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7166:       $i++;
1.191     harris41 7167:    }
1.15      www      7168:    return %returnhash;
1.27      www      7169: }
                   7170: 
                   7171: # --------------------------------------------------------------- del interface
                   7172: 
                   7173: sub del {
1.133     albertel 7174:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      7175:    my $items='';
1.800     albertel 7176:    foreach my $item (@$storearr) {
                   7177:        $items.=&escape($item).'&';
1.191     harris41 7178:    }
1.984     neumanie 7179: 
1.27      www      7180:    $items=~s/\&$//;
1.620     albertel 7181:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7182:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7183:    my $uhome=&homeserver($uname,$udomain);
                   7184:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      7185: }
                   7186: 
                   7187: # -------------------------------------------------------------- dump interface
                   7188: 
1.1172.2.22  raeburn  7189: sub unserialize {
                   7190:     my ($rep, $escapedkeys) = @_;
                   7191: 
                   7192:     return {} if $rep =~ /^error/;
                   7193: 
                   7194:     my %returnhash=();
                   7195:     foreach my $item (split(/\&/,$rep)) {
                   7196:         my ($key, $value) = split(/=/, $item, 2);
                   7197:         $key = unescape($key) unless $escapedkeys;
                   7198:         next if $key =~ /^error: 2 /;
                   7199:         $returnhash{$key} = &thaw_unescape($value);
                   7200:     }
                   7201:     return \%returnhash;
                   7202: }
                   7203: 
                   7204: # see Lond::dump_with_regexp
                   7205: # if $escapedkeys hash keys won't get unescaped.
1.15      www      7206: sub dump {
1.1172.2.146.  .1(raebu 7207:22):     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
1.755     albertel 7208:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7209:     if (!$uname) { $uname=$env{'user.name'}; }
                   7210:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 7211: 
1.1172.2.55  raeburn  7212:     if ($regexp) {
                   7213:         $regexp=&escape($regexp);
                   7214:     } else {
                   7215:         $regexp='.';
                   7216:     }
1.1172.2.22  raeburn  7217:     if (grep { $_ eq $uhome } &current_machine_ids()) {
                   7218:         # user is hosted on this machine
1.1172.2.55  raeburn  7219:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
1.1172.2.27  raeburn  7220:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1172.2.22  raeburn  7221:         return %{&unserialize($reply, $escapedkeys)};
                   7222:     }
1.1172.2.146.  .1(raebu 7223:22):     my $rep;
                   7224:22):     if ($encrypt) {
                   7225:22):         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   7226:22):     } else {
                   7227:22):         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   7228:22):     }
1.755     albertel 7229:     my @pairs=split(/\&/,$rep);
                   7230:     my %returnhash=();
1.1098    foxr     7231:     if (!($rep =~ /^error/ )) {
                   7232: 	foreach my $item (@pairs) {
                   7233: 	    my ($key,$value)=split(/=/,$item,2);
1.1172.2.22  raeburn  7234:             $key = &unescape($key) unless ($escapedkeys);
1.1098    foxr     7235: 	    next if ($key =~ /^error: 2 /);
                   7236: 	    $returnhash{$key}=&thaw_unescape($value);
                   7237: 	}
1.755     albertel 7238:     }
                   7239:     return %returnhash;
1.407     www      7240: }
                   7241: 
1.1098    foxr     7242: 
1.717     albertel 7243: # --------------------------------------------------------- dumpstore interface
                   7244: 
                   7245: sub dumpstore {
                   7246:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1172.2.22  raeburn  7247:    # same as dump but keys must be escaped. They may contain colon separated
                   7248:    # lists of values that may themself contain colons (e.g. symbs).
                   7249:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 7250: }
                   7251: 
1.407     www      7252: # -------------------------------------------------------------- keys interface
                   7253: 
                   7254: sub getkeys {
                   7255:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 7256:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7257:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      7258:    my $uhome=&homeserver($uname,$udomain);
                   7259:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   7260:    my @keyarray=();
1.800     albertel 7261:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  7262:       next if ($key =~ /^error: 2 /);
1.800     albertel 7263:       push(@keyarray,&unescape($key));
1.407     www      7264:    }
                   7265:    return @keyarray;
1.318     matthew  7266: }
                   7267: 
1.319     matthew  7268: # --------------------------------------------------------------- currentdump
                   7269: sub currentdump {
1.328     matthew  7270:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 7271:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   7272:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   7273:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  7274:    my $uhome = &homeserver($sname,$sdom);
1.1172.2.50  raeburn  7275:    my $rep;
                   7276: 
                   7277:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   7278:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
                   7279:                    $courseid)));
                   7280:    } else {
                   7281:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   7282:    }
                   7283: 
1.318     matthew  7284:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  7285:    #
1.318     matthew  7286:    my %returnhash=();
1.319     matthew  7287:    #
                   7288:    if ($rep eq "unknown_cmd") { 
                   7289:        # an old lond will not know currentdump
                   7290:        # Do a dump and make it look like a currentdump
1.822     albertel 7291:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  7292:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   7293:        my %hash = @tmp;
                   7294:        @tmp=();
1.424     matthew  7295:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  7296:    } else {
                   7297:        my @pairs=split(/\&/,$rep);
1.800     albertel 7298:        foreach my $pair (@pairs) {
                   7299:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  7300:            my ($symb,$param) = split(/:/,$key);
                   7301:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 7302:                                                         &thaw_unescape($value);
1.319     matthew  7303:        }
1.191     harris41 7304:    }
1.12      www      7305:    return %returnhash;
1.424     matthew  7306: }
                   7307: 
                   7308: sub convert_dump_to_currentdump{
                   7309:     my %hash = %{shift()};
                   7310:     my %returnhash;
                   7311:     # Code ripped from lond, essentially.  The only difference
                   7312:     # here is the unescaping done by lonnet::dump().  Conceivably
                   7313:     # we might run in to problems with parameter names =~ /^v\./
                   7314:     while (my ($key,$value) = each(%hash)) {
                   7315:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 7316: 	$symb  = &unescape($symb);
                   7317: 	$param = &unescape($param);
1.424     matthew  7318:         next if ($v eq 'version' || $symb eq 'keys');
                   7319:         next if (exists($returnhash{$symb}) &&
                   7320:                  exists($returnhash{$symb}->{$param}) &&
                   7321:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   7322:         $returnhash{$symb}->{$param}=$value;
                   7323:         $returnhash{$symb}->{'v.'.$param}=$v;
                   7324:     }
                   7325:     #
                   7326:     # Remove all of the keys in the hashes which keep track of
                   7327:     # the version of the parameter.
                   7328:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   7329:         # use a foreach because we are going to delete from the hash.
                   7330:         foreach my $key (keys(%$param_hash)) {
                   7331:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   7332:         }
                   7333:     }
                   7334:     return \%returnhash;
1.12      www      7335: }
                   7336: 
1.627     albertel 7337: # ------------------------------------------------------ critical inc interface
                   7338: 
                   7339: sub cinc {
                   7340:     return &inc(@_,'critical');
                   7341: }
                   7342: 
1.449     matthew  7343: # --------------------------------------------------------------- inc interface
                   7344: 
                   7345: sub inc {
1.627     albertel 7346:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7347:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7348:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7349:     my $uhome=&homeserver($uname,$udomain);
                   7350:     my $items='';
                   7351:     if (! ref($store)) {
                   7352:         # got a single value, so use that instead
                   7353:         $items = &escape($store).'=&';
                   7354:     } elsif (ref($store) eq 'SCALAR') {
                   7355:         $items = &escape($$store).'=&';        
                   7356:     } elsif (ref($store) eq 'ARRAY') {
                   7357:         $items = join('=&',map {&escape($_);} @{$store});
                   7358:     } elsif (ref($store) eq 'HASH') {
                   7359:         while (my($key,$value) = each(%{$store})) {
                   7360:             $items.= &escape($key).'='.&escape($value).'&';
                   7361:         }
                   7362:     }
                   7363:     $items=~s/\&$//;
1.627     albertel 7364:     if ($critical) {
                   7365: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7366:     } else {
                   7367: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7368:     }
1.449     matthew  7369: }
                   7370: 
1.12      www      7371: # --------------------------------------------------------------- put interface
                   7372: 
                   7373: sub put {
1.1172.2.146.  .1(raebu 7374:22):    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
1.620     albertel 7375:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7376:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7377:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7378:    my $items='';
1.800     albertel 7379:    foreach my $item (keys(%$storehash)) {
                   7380:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7381:    }
1.12      www      7382:    $items=~s/\&$//;
1.1172.2.146.  .1(raebu 7383:22):    if ($encrypt) {
                   7384:22):        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
                   7385:22):    } else {
                   7386:22):        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
                   7387:22):    }
1.47      www      7388: }
                   7389: 
1.631     albertel 7390: # ------------------------------------------------------------ newput interface
                   7391: 
                   7392: sub newput {
                   7393:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7394:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7395:    if (!$uname) { $uname=$env{'user.name'}; }
                   7396:    my $uhome=&homeserver($uname,$udomain);
                   7397:    my $items='';
                   7398:    foreach my $key (keys(%$storehash)) {
                   7399:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7400:    }
                   7401:    $items=~s/\&$//;
                   7402:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7403: }
                   7404: 
                   7405: # ---------------------------------------------------------  putstore interface
                   7406: 
1.524     raeburn  7407: sub putstore {
1.1172.2.59  raeburn  7408:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7409:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7410:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7411:    my $uhome=&homeserver($uname,$udomain);
                   7412:    my $items='';
1.715     albertel 7413:    foreach my $key (keys(%$storehash)) {
                   7414:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7415:    }
1.715     albertel 7416:    $items=~s/\&$//;
1.716     albertel 7417:    my $esc_symb=&escape($symb);
                   7418:    my $esc_v=&escape($version);
1.715     albertel 7419:    my $reply =
1.716     albertel 7420:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7421: 	      $uhome);
1.1172.2.59  raeburn  7422:    if (($tolog) && ($reply eq 'ok')) {
                   7423:        my $namevalue='';
                   7424:        foreach my $key (keys(%{$storehash})) {
                   7425:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7426:        }
1.1172.2.134  raeburn  7427:        my $ip = &get_requestor_ip();
1.1172.2.135  raeburn  7428:        $namevalue .= 'ip='.&escape($ip).
1.1172.2.59  raeburn  7429:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7430:                      '&version='.$esc_v.
                   7431:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7432:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7433:    }
1.715     albertel 7434:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7435:        # gfall back to way things use to be done
1.715     albertel 7436:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7437: 			    $uname);
1.524     raeburn  7438:    }
1.715     albertel 7439:    return $reply;
                   7440: }
                   7441: 
                   7442: sub old_putstore {
1.716     albertel 7443:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7444:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7445:     if (!$uname) { $uname=$env{'user.name'}; }
                   7446:     my $uhome=&homeserver($uname,$udomain);
                   7447:     my %newstorehash;
1.800     albertel 7448:     foreach my $item (keys(%$storehash)) {
                   7449: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7450: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7451:     }
                   7452:     my $items='';
                   7453:     my %allitems = ();
1.800     albertel 7454:     foreach my $item (keys(%newstorehash)) {
                   7455: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7456: 	    my $key = $1.':keys:'.$2;
                   7457: 	    $allitems{$key} .= $3.':';
                   7458: 	}
1.800     albertel 7459: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7460:     }
1.800     albertel 7461:     foreach my $item (keys(%allitems)) {
                   7462: 	$allitems{$item} =~ s/\:$//;
                   7463: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7464:     }
                   7465:     $items=~s/\&$//;
                   7466:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7467: }
                   7468: 
1.47      www      7469: # ------------------------------------------------------ critical put interface
                   7470: 
                   7471: sub cput {
1.134     albertel 7472:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7473:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7474:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7475:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7476:    my $items='';
1.800     albertel 7477:    foreach my $item (keys(%$storehash)) {
                   7478:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7479:    }
1.47      www      7480:    $items=~s/\&$//;
1.134     albertel 7481:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7482: }
                   7483: 
                   7484: # -------------------------------------------------------------- eget interface
                   7485: 
                   7486: sub eget {
1.133     albertel 7487:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7488:    my $items='';
1.800     albertel 7489:    foreach my $item (@$storearr) {
                   7490:        $items.=&escape($item).'&';
1.191     harris41 7491:    }
1.12      www      7492:    $items=~s/\&$//;
1.620     albertel 7493:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7494:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7495:    my $uhome=&homeserver($uname,$udomain);
                   7496:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7497:    my @pairs=split(/\&/,$rep);
                   7498:    my %returnhash=();
1.42      www      7499:    my $i=0;
1.800     albertel 7500:    foreach my $item (@$storearr) {
                   7501:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7502:       $i++;
1.191     harris41 7503:    }
1.12      www      7504:    return %returnhash;
                   7505: }
                   7506: 
1.667     albertel 7507: # ------------------------------------------------------------ tmpput interface
                   7508: sub tmpput {
1.802     raeburn  7509:     my ($storehash,$server,$context)=@_;
1.667     albertel 7510:     my $items='';
1.800     albertel 7511:     foreach my $item (keys(%$storehash)) {
                   7512: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7513:     }
                   7514:     $items=~s/\&$//;
1.802     raeburn  7515:     if (defined($context)) {
                   7516:         $items .= ':'.&escape($context);
                   7517:     }
1.667     albertel 7518:     return &reply("tmpput:$items",$server);
                   7519: }
                   7520: 
                   7521: # ------------------------------------------------------------ tmpget interface
                   7522: sub tmpget {
1.688     albertel 7523:     my ($token,$server)=@_;
                   7524:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7525:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7526:     my %returnhash;
1.1172.2.85  raeburn  7527:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7528:         return %returnhash;
                   7529:     }
1.667     albertel 7530:     foreach my $item (split(/\&/,$rep)) {
                   7531: 	my ($key,$value)=split(/=/,$item);
                   7532: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7533:     }
                   7534:     return %returnhash;
                   7535: }
                   7536: 
1.1113    raeburn  7537: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7538: sub tmpdel {
                   7539:     my ($token,$server)=@_;
                   7540:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7541:     return &reply("tmpdel:$token",$server);
                   7542: }
                   7543: 
1.1172.2.13  raeburn  7544: # ------------------------------------------------------------ get_timebased_id
                   7545: 
                   7546: sub get_timebased_id {
                   7547:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7548:         $maxtries) = @_;
                   7549:     my ($newid,$error,$dellock);
                   7550:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
                   7551:         return ('','ok','invalid call to get suffix');
                   7552:     }
                   7553: 
                   7554: # set defaults for any optional args for which values were not supplied
                   7555:     if ($who eq '') {
                   7556:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7557:     }
                   7558:     if (!$locktries) {
                   7559:         $locktries = 3;
                   7560:     }
                   7561:     if (!$maxtries) {
                   7562:         $maxtries = 10;
                   7563:     }
                   7564: 
                   7565:     if (($cdom eq '') || ($cnum eq '')) {
                   7566:         if ($env{'request.course.id'}) {
                   7567:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7568:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7569:         }
                   7570:         if (($cdom eq '') || ($cnum eq '')) {
                   7571:             return ('','ok','call to get suffix not in course context');
                   7572:         }
                   7573:     }
                   7574: 
                   7575: # construct locking item
                   7576:     my $lockhash = {
                   7577:                       $prefix."\0".'locked_'.$keyid => $who,
                   7578:                    };
                   7579:     my $tries = 0;
                   7580: 
                   7581: # attempt to get lock on nohist_$namespace file
                   7582:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7583:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7584:         $tries ++;
                   7585:         sleep 1;
                   7586:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7587:     }
                   7588: 
                   7589: # attempt to get unique identifier, based on current timestamp
                   7590:     if ($gotlock eq 'ok') {
                   7591:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7592:         my $id = time;
                   7593:         $newid = $id;
1.1172.2.56  raeburn  7594:         if ($idtype eq 'addcode') {
                   7595:             $newid .= &sixnum_code();
                   7596:         }
1.1172.2.13  raeburn  7597:         my $idtries = 0;
                   7598:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7599:             if ($idtype eq 'concat') {
                   7600:                 $newid = $id.$idtries;
1.1172.2.56  raeburn  7601:             } elsif ($idtype eq 'addcode') {
                   7602:                 $newid = $newid.&sixnum_code();
1.1172.2.13  raeburn  7603:             } else {
                   7604:                 $newid ++;
                   7605:             }
                   7606:             $idtries ++;
                   7607:         }
                   7608:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7609:             my %new_item =  (
                   7610:                               $prefix."\0".$newid => $who,
                   7611:                             );
                   7612:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7613:                                                  $cdom,$cnum);
                   7614:             if ($putresult ne 'ok') {
                   7615:                 undef($newid);
                   7616:                 $error = 'error saving new item: '.$putresult;
                   7617:             }
                   7618:         } else {
1.1172.2.56  raeburn  7619:              undef($newid);
1.1172.2.13  raeburn  7620:              $error = ('error: no unique suffix available for the new item ');
                   7621:         }
                   7622: #  remove lock
                   7623:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7624:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7625:     } else {
                   7626:         $error = "error: could not obtain lockfile\n";
                   7627:         $dellock = 'ok';
1.1172.2.58  raeburn  7628:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7629:             $dellock = 'nolock';
                   7630:         }
1.1172.2.13  raeburn  7631:     }
                   7632:     return ($newid,$dellock,$error);
                   7633: }
                   7634: 
1.1172.2.56  raeburn  7635: sub sixnum_code {
                   7636:     my $code;
                   7637:     for (0..6) {
                   7638:         $code .= int( rand(9) );
                   7639:     }
                   7640:     return $code;
                   7641: }
                   7642: 
1.765     albertel 7643: # -------------------------------------------------- portfolio access checking
                   7644: 
                   7645: sub portfolio_access {
1.1172.2.77  raeburn  7646:     my ($requrl,$clientip) = @_;
1.765     albertel 7647:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1172.2.77  raeburn  7648:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7649:     if ($result) {
                   7650:         my %setters;
                   7651:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1172.2.142  raeburn  7652:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
                   7653:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
                   7654:             if (($startblock && $endblock) || ($by_ip))  {
1.814     raeburn  7655:                 return 'B';
                   7656:             }
                   7657:         } else {
1.1172.2.142  raeburn  7658:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdo) =
                   7659:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   7660:             if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  7661:                 return 'B';
                   7662:             }
                   7663:         }
                   7664:     }
1.765     albertel 7665:     if ($result eq 'ok') {
1.766     albertel 7666:        return 'F';
1.765     albertel 7667:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7668:        return 'A';
1.765     albertel 7669:     }
1.766     albertel 7670:     return '';
1.765     albertel 7671: }
                   7672: 
                   7673: sub get_portfolio_access {
1.1172.2.77  raeburn  7674:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7675: 
                   7676:     if (!ref($access_hash)) {
                   7677: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7678: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7679: 						   $file_name);
                   7680: 	$access_hash = $access_controls{$file_name};
                   7681:     }
                   7682: 
1.1172.2.77  raeburn  7683:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7684:     my $now = time;
                   7685:     if (ref($access_hash) eq 'HASH') {
                   7686:         foreach my $key (keys(%{$access_hash})) {
                   7687:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7688:             if ($start > $now) {
                   7689:                 next;
                   7690:             }
                   7691:             if ($end && $end<$now) {
                   7692:                 next;
                   7693:             }
                   7694:             if ($scope eq 'public') {
                   7695:                 $public = $key;
                   7696:                 last;
                   7697:             } elsif ($scope eq 'guest') {
                   7698:                 $guest = $key;
                   7699:             } elsif ($scope eq 'domains') {
                   7700:                 push(@domains,$key);
                   7701:             } elsif ($scope eq 'users') {
                   7702:                 push(@users,$key);
                   7703:             } elsif ($scope eq 'course') {
                   7704:                 push(@courses,$key);
                   7705:             } elsif ($scope eq 'group') {
                   7706:                 push(@groups,$key);
1.1172.2.77  raeburn  7707:             } elsif ($scope eq 'ip') {
                   7708:                 push(@ips,$key);
1.765     albertel 7709:             }
                   7710:         }
                   7711:         if ($public) {
                   7712:             return 'ok';
1.1172.2.77  raeburn  7713:         } elsif (@ips > 0) {
                   7714:             my $allowed;
                   7715:             foreach my $ipkey (@ips) {
                   7716:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7717:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7718:                         $allowed = 1;
                   7719:                         last;
                   7720:                     }
                   7721:                 }
                   7722:             }
                   7723:             if ($allowed) {
                   7724:                 return 'ok';
                   7725:             }
1.765     albertel 7726:         }
                   7727:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7728:             if ($guest) {
                   7729:                 return $guest;
                   7730:             }
                   7731:         } else {
                   7732:             if (@domains > 0) {
                   7733:                 foreach my $domkey (@domains) {
                   7734:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7735:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7736:                             return 'ok';
                   7737:                         }
                   7738:                     }
                   7739:                 }
                   7740:             }
                   7741:             if (@users > 0) {
                   7742:                 foreach my $userkey (@users) {
1.865     raeburn  7743:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7744:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7745:                             if (ref($item) eq 'HASH') {
                   7746:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7747:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7748:                                     return 'ok';
                   7749:                                 }
                   7750:                             }
                   7751:                         }
                   7752:                     } 
1.765     albertel 7753:                 }
                   7754:             }
                   7755:             my %roleshash;
                   7756:             my @courses_and_groups = @courses;
                   7757:             push(@courses_and_groups,@groups); 
                   7758:             if (@courses_and_groups > 0) {
                   7759:                 my (%allgroups,%allroles); 
                   7760:                 my ($start,$end,$role,$sec,$group);
                   7761:                 foreach my $envkey (%env) {
1.1060    raeburn  7762:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7763:                         my $cid = $2.'_'.$3; 
                   7764:                         if ($1 eq 'gr') {
                   7765:                             $group = $4;
                   7766:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7767:                         } else {
                   7768:                             if ($4 eq '') {
                   7769:                                 $sec = 'none';
                   7770:                             } else {
                   7771:                                 $sec = $4;
                   7772:                             }
                   7773:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7774:                         }
1.811     albertel 7775:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7776:                         my $cid = $2.'_'.$3;
                   7777:                         if ($4 eq '') {
                   7778:                             $sec = 'none';
                   7779:                         } else {
                   7780:                             $sec = $4;
                   7781:                         }
                   7782:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7783:                     }
                   7784:                 }
                   7785:                 if (keys(%allroles) == 0) {
                   7786:                     return;
                   7787:                 }
                   7788:                 foreach my $key (@courses_and_groups) {
                   7789:                     my %content = %{$$access_hash{$key}};
                   7790:                     my $cnum = $content{'number'};
                   7791:                     my $cdom = $content{'domain'};
                   7792:                     my $cid = $cdom.'_'.$cnum;
                   7793:                     if (!exists($allroles{$cid})) {
                   7794:                         next;
                   7795:                     }    
                   7796:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7797:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7798:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7799:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7800:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7801:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7802:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7803:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7804:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7805:                                         if (grep/^all$/,@sections) {
                   7806:                                             return 'ok';
                   7807:                                         } else {
                   7808:                                             if (grep/^$sec$/,@sections) {
                   7809:                                                 return 'ok';
                   7810:                                             }
                   7811:                                         }
                   7812:                                     }
                   7813:                                 }
                   7814:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7815:                                     if (grep/^none$/,@groups) {
                   7816:                                         return 'ok';
                   7817:                                     }
                   7818:                                 } else {
                   7819:                                     if (grep/^all$/,@groups) {
                   7820:                                         return 'ok';
                   7821:                                     } 
                   7822:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7823:                                         if (grep/^$group$/,@groups) {
                   7824:                                             return 'ok';
                   7825:                                         }
                   7826:                                     }
                   7827:                                 } 
                   7828:                             }
                   7829:                         }
                   7830:                     }
                   7831:                 }
                   7832:             }
                   7833:             if ($guest) {
                   7834:                 return $guest;
                   7835:             }
                   7836:         }
                   7837:     }
                   7838:     return;
                   7839: }
                   7840: 
                   7841: sub course_group_datechecker {
                   7842:     my ($dates,$now,$status) = @_;
                   7843:     my ($start,$end) = split(/\./,$dates);
                   7844:     if (!$start && !$end) {
                   7845:         return 'ok';
                   7846:     }
                   7847:     if (grep/^active$/,@{$status}) {
                   7848:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7849:             return 'ok';
                   7850:         }
                   7851:     }
                   7852:     if (grep/^previous$/,@{$status}) {
                   7853:         if ($end > $now ) {
                   7854:             return 'ok';
                   7855:         }
                   7856:     }
                   7857:     if (grep/^future$/,@{$status}) {
                   7858:         if ($start > $now) {
                   7859:             return 'ok';
                   7860:         }
                   7861:     }
                   7862:     return; 
                   7863: }
                   7864: 
                   7865: sub parse_portfolio_url {
                   7866:     my ($url) = @_;
                   7867: 
                   7868:     my ($type,$udom,$unum,$group,$file_name);
                   7869:     
1.823     albertel 7870:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7871: 	$type = 1;
                   7872:         $udom = $1;
                   7873:         $unum = $2;
                   7874:         $file_name = $3;
1.823     albertel 7875:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7876: 	$type = 2;
                   7877:         $udom = $1;
                   7878:         $unum = $2;
                   7879:         $group = $3;
                   7880:         $file_name = $3.'/'.$4;
                   7881:     }
                   7882:     if (wantarray) {
                   7883: 	return ($type,$udom,$unum,$file_name,$group);
                   7884:     }
                   7885:     return $type;
                   7886: }
                   7887: 
                   7888: sub is_portfolio_url {
                   7889:     my ($url) = @_;
                   7890:     return scalar(&parse_portfolio_url($url));
                   7891: }
                   7892: 
1.798     raeburn  7893: sub is_portfolio_file {
                   7894:     my ($file) = @_;
1.820     raeburn  7895:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7896:         return 1;
                   7897:     }
                   7898:     return;
                   7899: }
                   7900: 
1.1172.2.146.  .13(raeb 7901:-23): sub is_coursetool_logo {
                   7902:-23):     my ($uri) = @_;
                   7903:-23):     if ($env{'request.course.id'}) {
                   7904:-23):         my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   7905:-23):         if ($uri =~ m{^/*uploaded\Q$courseurl\E/toollogo/\d+/[^/]+$}) {
                   7906:-23):             return 1;
                   7907:-23):         }
                   7908:-23):     }
                   7909:-23):     return;
                   7910:-23): }
                   7911:-23): 
1.976     raeburn  7912: sub usertools_access {
1.1084    raeburn  7913:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7914:     my ($access,%tools);
                   7915:     if ($context eq '') {
                   7916:         $context = 'tools';
                   7917:     }
                   7918:     if ($context eq 'requestcourses') {
                   7919:         %tools = (
                   7920:                       official   => 1,
                   7921:                       unofficial => 1,
1.1006    raeburn  7922:                       community  => 1,
1.1172.2.37  raeburn  7923:                       textbook   => 1,
1.1172.2.146.  .13(raeb 7924:-23):                       lti        => 1,
1.985     raeburn  7925:                  );
1.1172.2.9  raeburn  7926:     } elsif ($context eq 'requestauthor') {
                   7927:         %tools = (
                   7928:                       requestauthor => 1,
                   7929:                  );
1.985     raeburn  7930:     } else {
                   7931:         %tools = (
                   7932:                       aboutme   => 1,
                   7933:                       blog      => 1,
1.1172.2.6  raeburn  7934:                       webdav    => 1,
1.985     raeburn  7935:                       portfolio => 1,
1.1172.2.146.  .6(raebu 7936:22):                       timezone  => 1,
1.985     raeburn  7937:                  );
                   7938:     }
1.976     raeburn  7939:     return if (!defined($tools{$tool}));
                   7940: 
1.1172.2.35  raeburn  7941:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7942:         $udom = $env{'user.domain'};
                   7943:         $uname = $env{'user.name'};
                   7944:     }
                   7945: 
1.978     raeburn  7946:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7947:         if ($action ne 'reload') {
1.985     raeburn  7948:             if ($context eq 'requestcourses') {
                   7949:                 return $env{'environment.canrequest.'.$tool};
1.1172.2.9  raeburn  7950:             } elsif ($context eq 'requestauthor') {
                   7951:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7952:             } else {
                   7953:                 return $env{'environment.availabletools.'.$tool};
                   7954:             }
                   7955:         }
1.976     raeburn  7956:     }
                   7957: 
1.1172.2.9  raeburn  7958:     my ($toolstatus,$inststatus,$envkey);
                   7959:     if ($context eq 'requestauthor') {
                   7960:         $envkey = $context;
                   7961:     } else {
                   7962:         $envkey = $context.'.'.$tool;
                   7963:     }
1.976     raeburn  7964: 
1.985     raeburn  7965:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7966:          ($action ne 'reload')) {
1.1172.2.9  raeburn  7967:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7968:         $inststatus = $env{'environment.inststatus'};
                   7969:     } else {
1.1084    raeburn  7970:         if (ref($userenvref) eq 'HASH') {
1.1172.2.9  raeburn  7971:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7972:             $inststatus = $userenvref->{'inststatus'};
                   7973:         } else {
1.1172.2.9  raeburn  7974:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7975:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7976:             $inststatus = $userenv{'inststatus'};
                   7977:         }
1.976     raeburn  7978:     }
                   7979: 
                   7980:     if ($toolstatus ne '') {
                   7981:         if ($toolstatus) {
                   7982:             $access = 1;
                   7983:         } else {
                   7984:             $access = 0;
                   7985:         }
                   7986:         return $access;
                   7987:     }
                   7988: 
1.1084    raeburn  7989:     my ($is_adv,%domdef);
                   7990:     if (ref($is_advref) eq 'HASH') {
                   7991:         $is_adv = $is_advref->{'is_adv'};
                   7992:     } else {
                   7993:         $is_adv = &is_advanced_user($udom,$uname);
                   7994:     }
                   7995:     if (ref($domdefref) eq 'HASH') {
                   7996:         %domdef = %{$domdefref};
                   7997:     } else {
                   7998:         %domdef = &get_domain_defaults($udom);
                   7999:     }
1.976     raeburn  8000:     if (ref($domdef{$tool}) eq 'HASH') {
                   8001:         if ($is_adv) {
                   8002:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   8003:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   8004:                     $access = 1;
                   8005:                 } else {
                   8006:                     $access = 0;
                   8007:                 }
                   8008:                 return $access;
                   8009:             }
                   8010:         }
                   8011:         if ($inststatus ne '') {
                   8012:             my ($hasaccess,$hasnoaccess);
                   8013:             foreach my $affiliation (split(/:/,$inststatus)) {
                   8014:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   8015:                     if ($domdef{$tool}{$affiliation}) {
                   8016:                         $hasaccess = 1;
                   8017:                     } else {
                   8018:                         $hasnoaccess = 1;
                   8019:                     }
                   8020:                 }
                   8021:             }
                   8022:             if ($hasaccess || $hasnoaccess) {
                   8023:                 if ($hasaccess) {
                   8024:                     $access = 1;
                   8025:                 } elsif ($hasnoaccess) {
                   8026:                     $access = 0; 
                   8027:                 }
                   8028:                 return $access;
                   8029:             }
                   8030:         } else {
                   8031:             if ($domdef{$tool}{'default'} ne '') {
                   8032:                 if ($domdef{$tool}{'default'}) {
                   8033:                     $access = 1;
                   8034:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   8035:                     $access = 0;
                   8036:                 }
                   8037:                 return $access;
                   8038:             }
                   8039:         }
                   8040:     } else {
1.1172.2.6  raeburn  8041:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  8042:             $access = 1;
                   8043:         } else {
                   8044:             $access = 0;
                   8045:         }
1.976     raeburn  8046:         return $access;
                   8047:     }
                   8048: }
                   8049: 
1.1050    raeburn  8050: sub is_course_owner {
                   8051:     my ($cdom,$cnum,$udom,$uname) = @_;
                   8052:     if (($udom eq '') || ($uname eq '')) {
                   8053:         $udom = $env{'user.domain'};
                   8054:         $uname = $env{'user.name'};
                   8055:     }
                   8056:     unless (($udom eq '') || ($uname eq '')) {
                   8057:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   8058:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   8059:                 return 1;
                   8060:             } else {
                   8061:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   8062:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   8063:                     return 1;
                   8064:                 }
                   8065:             }
                   8066:         }
                   8067:     }
                   8068:     return;
                   8069: }
                   8070: 
1.976     raeburn  8071: sub is_advanced_user {
                   8072:     my ($udom,$uname) = @_;
1.1085    raeburn  8073:     if ($udom ne '' && $uname ne '') {
                   8074:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  8075:             if (wantarray) {
                   8076:                 return ($env{'user.adv'},$env{'user.author'});
                   8077:             } else {
                   8078:                 return $env{'user.adv'};
                   8079:             }
1.1085    raeburn  8080:         }
                   8081:     }
1.976     raeburn  8082:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   8083:     my %allroles;
1.1128    raeburn  8084:     my ($is_adv,$is_author);
1.976     raeburn  8085:     foreach my $role (keys(%roleshash)) {
                   8086:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   8087:         my $area = '/'.$tdomain.'/'.$trest;
                   8088:         if ($sec ne '') {
                   8089:             $area .= '/'.$sec;
                   8090:         }
                   8091:         if (($area ne '') && ($trole ne '')) {
                   8092:             my $spec=$trole.'.'.$area;
                   8093:             if ($trole =~ /^cr\//) {
                   8094:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   8095:             } elsif ($trole ne 'gr') {
                   8096:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   8097:             }
1.1128    raeburn  8098:             if ($trole eq 'au') {
                   8099:                 $is_author = 1;
                   8100:             }
1.976     raeburn  8101:         }
                   8102:     }
                   8103:     foreach my $role (keys(%allroles)) {
                   8104:         last if ($is_adv);
                   8105:         foreach my $item (split(/:/,$allroles{$role})) {
                   8106:             if ($item ne '') {
                   8107:                 my ($privilege,$restrictions)=split(/&/,$item);
                   8108:                 if ($privilege eq 'adv') {
                   8109:                     $is_adv = 1;
                   8110:                     last;
                   8111:                 }
                   8112:             }
                   8113:         }
                   8114:     }
1.1128    raeburn  8115:     if (wantarray) {
                   8116:         return ($is_adv,$is_author);
                   8117:     }
1.976     raeburn  8118:     return $is_adv;
                   8119: }
1.798     raeburn  8120: 
1.1035    raeburn  8121: sub check_can_request {
1.1172.2.146.  .13(raeb 8122:-23):     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  8123:     my $canreq = 0;
1.1172.2.146.  .13(raeb 8124:-23):     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8125:-23):         $uname = $env{'user.name'};
                   8126:-23):         $udom = $env{'user.domain'};
                   8127:-23):     }
1.1035    raeburn  8128:     my ($types,$typename) = &Apache::loncommon::course_types();
                   8129:     my @options = ('approval','validate','autolimit');
                   8130:     my $optregex = join('|',@options);
                   8131:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   8132:         foreach my $type (@{$types}) {
1.1172.2.146.  .13(raeb 8133:-23):             if (&usertools_access($uname,$udom,$type,undef,
                   8134:-23):                                   'requestcourses')) {
1.1035    raeburn  8135:                 $canreq ++;
1.1036    raeburn  8136:                 if (ref($request_domains) eq 'HASH') {
1.1172.2.146.  .13(raeb 8137:-23):                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  8138:                 }
1.1172.2.146.  .13(raeb 8139:-23):                 if ($dom eq $udom) {
1.1035    raeburn  8140:                     $can_request->{$type} = 1;
                   8141:                 }
                   8142:             }
1.1172.2.146.  .13(raeb 8143:-23):             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   8144:-23):                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  8145:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   8146:                 if (@curr > 0) {
1.1036    raeburn  8147:                     foreach my $item (@curr) {
                   8148:                         if (ref($request_domains) eq 'HASH') {
                   8149:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   8150:                             if ($otherdom ne '') {
                   8151:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   8152:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   8153:                                         push(@{$request_domains->{$type}},$otherdom);
                   8154:                                     }
                   8155:                                 } else {
                   8156:                                     push(@{$request_domains->{$type}},$otherdom);
                   8157:                                 }
                   8158:                             }
                   8159:                         }
                   8160:                     }
1.1172.2.146.  .13(raeb 8161:-23):                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  8162:                         $canreq ++;
1.1035    raeburn  8163:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   8164:                             $can_request->{$type} = 1;
                   8165:                         }
                   8166:                     }
                   8167:                 }
                   8168:             }
                   8169:         }
                   8170:     }
                   8171:     return $canreq;
                   8172: }
                   8173: 
1.341     www      8174: # ---------------------------------------------- Custom access rule evaluation
                   8175: 
                   8176: sub customaccess {
                   8177:     my ($priv,$uri)=@_;
1.807     albertel 8178:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      8179:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 8180:     $udom = &LONCAPA::clean_domain($udom);
                   8181:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      8182:     my $access=0;
1.800     albertel 8183:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 8184: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   8185: 	if ($type eq 'user') {
                   8186: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 8187: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 8188: 		if ($tdom) {
                   8189: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   8190: 		}
1.896     albertel 8191: 		if ($tuname) {
                   8192: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 8193: 		}
                   8194: 		$access=($effect eq 'allow');
                   8195: 		last;
                   8196: 	    }
                   8197: 	} else {
                   8198: 	    if ($role) {
                   8199: 		if ($role ne $urole) { next; }
                   8200: 	    }
                   8201: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   8202: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   8203: 		if ($tdom) {
                   8204: 		    if ($tdom ne $udom) { next; }
                   8205: 		}
                   8206: 		if ($tcrs) {
                   8207: 		    if ($tcrs ne $ucrs) { next; }
                   8208: 		}
                   8209: 		if ($tsec) {
                   8210: 		    if ($tsec ne $usec) { next; }
                   8211: 		}
                   8212: 		$access=($effect eq 'allow');
                   8213: 		last;
                   8214: 	    }
                   8215: 	    if ($realm eq '' && $role eq '') {
                   8216: 		$access=($effect eq 'allow');
                   8217: 	    }
1.402     bowersj2 8218: 	}
1.341     www      8219:     }
                   8220:     return $access;
                   8221: }
                   8222: 
1.103     harris41 8223: # ------------------------------------------------- Check for a user privilege
1.12      www      8224: 
                   8225: sub allowed {
1.1172.2.146.  .1(raebu 8226:22):     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
1.705     albertel 8227:     my $ver_orguri=$uri;
1.439     www      8228:     $uri=&deversion($uri);
1.152     www      8229:     my $orguri=$uri;
1.52      www      8230:     $uri=&declutter($uri);
1.809     raeburn  8231: 
1.810     raeburn  8232:     if ($priv eq 'evb') {
1.1172.2.146.  .3(raebu 8233:22): # Evade communication block restrictions for specified role in a course or domain
1.810     raeburn  8234:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   8235:             return $1;
                   8236:         } else {
                   8237:             return;
                   8238:         }
                   8239:     }
                   8240: 
1.620     albertel 8241:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      8242: # Free bre access to adm and meta resources
1.1172.2.146.  .1(raebu 8243:22):     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
1.769     albertel 8244: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   8245: 	&& ($priv eq 'bre')) {
1.14      www      8246: 	return 'F';
1.159     www      8247:     }
                   8248: 
1.545     banghart 8249: # Free bre access to user's own portfolio contents
1.714     raeburn  8250:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  8251:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  8252: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  8253:         my %setters;
1.1172.2.142  raeburn  8254:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   8255:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   8256:         if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  8257:             return 'B';
                   8258:         } else {
                   8259:             return 'F';
                   8260:         }
1.545     banghart 8261:     }
                   8262: 
1.762     raeburn  8263: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  8264:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   8265:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   8266:         if (exists($env{'request.course.id'})) {
                   8267:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8268:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8269:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   8270:                 my $courseprivid=$env{'request.course.id'};
                   8271:                 $courseprivid=~s/\_/\//;
                   8272:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   8273:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   8274:                     return $1; 
1.762     raeburn  8275:                 } else {
                   8276:                     if ($env{'request.course.sec'}) {
                   8277:                         $courseprivid.='/'.$env{'request.course.sec'};
                   8278:                     }
                   8279:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   8280:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   8281:                         return $2;
                   8282:                     }
1.714     raeburn  8283:                 }
                   8284:             }
                   8285:         }
                   8286:     }
                   8287: 
1.159     www      8288: # Free bre to public access
                   8289: 
                   8290:     if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8291:22):         my $copyright;
                   8292:22):         unless ($uri =~ /ext\.tool/) {
                   8293:22):             $copyright=&metadata($uri,'copyright');
                   8294:22):         }
1.620     albertel 8295: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      8296:            return 'F'; 
                   8297:         }
1.238     www      8298:         if ($copyright eq 'priv') {
                   8299:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8300: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      8301: 		return '';
                   8302:             }
                   8303:         }
                   8304:         if ($copyright eq 'domain') {
                   8305:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8306: 	    unless (($env{'user.domain'} eq $1) ||
                   8307:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      8308: 		return '';
                   8309:             }
1.262     matthew  8310:         }
1.620     albertel 8311:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  8312:             # Library role, so allow browsing of resources in this domain.
                   8313:             return 'F';
1.238     www      8314:         }
1.341     www      8315:         if ($copyright eq 'custom') {
                   8316: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   8317:         }
1.14      www      8318:     }
1.264     matthew  8319:     # Domain coordinator is trying to create a course
1.620     albertel 8320:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  8321:         # uri is the requested domain in this case.
                   8322:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  8323:         # a role of dc for the domain in question.
1.620     albertel 8324:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  8325:     }
1.29      www      8326: 
1.52      www      8327:     my $thisallowed='';
                   8328:     my $statecond=0;
                   8329:     my $courseprivid='';
                   8330: 
1.1039    raeburn  8331:     my $ownaccess;
1.1043    raeburn  8332:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  8333:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   8334:         if ($uri eq '') {
                   8335:             $ownaccess = 1;
                   8336:         } else {
                   8337:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   8338:                 my $udom = $env{'user.domain'};
                   8339:                 my $uname = $env{'user.name'};
                   8340:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   8341:                     $ownaccess = 1;
1.1040    raeburn  8342:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  8343:                     unless ($uri =~ m{\.\./}) {
                   8344:                         $ownaccess = 1;
                   8345:                     }
                   8346:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   8347:                     my $now = time;
                   8348:                     if ($uri =~ m{^([^/]+)/?$}) {
                   8349:                         my $adom = $1;
                   8350:                         foreach my $key (keys(%env)) {
1.1042    raeburn  8351:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1172.2.142  raeburn  8352:                                 my ($start,$end) = split(/\./,$env{$key});
                   8353:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1039    raeburn  8354:                                     $ownaccess = 1;
                   8355:                                     last;
                   8356:                                 }
                   8357:                             }
                   8358:                         }
                   8359:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8360:                         my $adom = $1;
                   8361:                         my $aname = $2;
1.1042    raeburn  8362:                         foreach my $role ('ca','aa') { 
                   8363:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8364:                                 my ($start,$end) =
1.1172.2.142  raeburn  8365:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
                   8366:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1042    raeburn  8367:                                     $ownaccess = 1;
                   8368:                                     last;
                   8369:                                 }
1.1039    raeburn  8370:                             }
                   8371:                         }
                   8372:                     }
                   8373:                 }
                   8374:             }
                   8375:         }
                   8376:     }
                   8377: 
1.52      www      8378: # Course
                   8379: 
1.620     albertel 8380:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8381:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8382:             $thisallowed.=$1;
                   8383:         }
1.52      www      8384:     }
1.29      www      8385: 
1.52      www      8386: # Domain
                   8387: 
1.620     albertel 8388:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8389:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8390:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8391:             $thisallowed.=$1;
                   8392:         }
1.12      www      8393:     }
1.52      www      8394: 
1.1141    raeburn  8395: # User who is not author or co-author might still be able to edit
                   8396: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8397:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8398:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8399:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8400:             $thisallowed.=$1;
                   8401:         }
                   8402:     }
                   8403: 
1.52      www      8404: # Course: uri itself is a course
1.66      www      8405:     my $courseuri=$uri;
                   8406:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8407:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8408: 
1.620     albertel 8409:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8410:        =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.115  raeburn  8411:         if ($priv eq 'mip') {
                   8412:             my $rem = $1;
                   8413:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8414:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8415:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8416:                 if ($cdom ne '') {
                   8417:                     my %passwdconf = &get_passwdconf($cdom);
                   8418:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8419:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8420:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8421:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8422:                                 unless (@inststatuses) {
                   8423:                                     @inststatuses = ('default');
                   8424:                                 }
                   8425:                                 foreach my $status (@inststatuses) {
                   8426:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8427:                                         $thisallowed.=$rem;
                   8428:                                     }
                   8429:                                 }
                   8430:                             }
                   8431:                         }
                   8432:                     }
                   8433:                 }
                   8434:             }
                   8435:         } else {
                   8436:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8437:                 $thisallowed.=$1;
                   8438:             }
1.1039    raeburn  8439:         }
1.12      www      8440:     }
1.29      www      8441: 
1.665     albertel 8442: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8443: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8444:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8445: 	$thisallowed='';
1.671     raeburn  8446:         my ($match)=&is_on_map($uri);
                   8447:         if ($match) {
                   8448:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8449:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1172.2.65  raeburn  8450:                 my $value = $1;
1.1172.2.146.  .1(raebu 8451:22):                 my $deeplinkblock;
                   8452:22):                 unless ($nodeeplinkcheck) {
                   8453:22):                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8454:22):                 }
                   8455:22):                 if ($deeplinkblock) {
                   8456:22):                     $thisallowed='D';
                   8457:22):                 } elsif ($noblockcheck) {
1.1172.2.65  raeburn  8458:                     $thisallowed.=$value;
1.1162    raeburn  8459:                 } else {
1.1172.2.126  raeburn  8460:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8461:                     if (@blockers > 0) {
                   8462:                         $thisallowed = 'B';
                   8463:                     } else {
                   8464:                         $thisallowed.=$value;
                   8465:                     }
1.1162    raeburn  8466:                 }
1.671     raeburn  8467:             }
                   8468:         } else {
1.705     albertel 8469:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8470:             if ($refuri) {
                   8471:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8472:                     $thisallowed='F';
1.671     raeburn  8473:                 } else {
                   8474:                     $refuri=&declutter($refuri);
                   8475:                     my ($match) = &is_on_map($refuri);
                   8476:                     if ($match) {
1.1172.2.146.  .1(raebu 8477:22):                         my $deeplinkblock;
                   8478:22):                         unless ($nodeeplinkcheck) {
                   8479:22):                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8480:22):                         }
                   8481:22):                         if ($deeplinkblock) {
                   8482:22):                             $thisallowed='D';
                   8483:22):                         } elsif ($noblockcheck) {
1.1162    raeburn  8484:                             $thisallowed='F';
1.1172.2.65  raeburn  8485:                         } else {
1.1172.2.127  raeburn  8486:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8487:                             if (@blockers > 0) {
                   8488:                                 $thisallowed = 'B';
                   8489:                             } else {
                   8490:                                 $thisallowed='F';
                   8491:                             }
1.1162    raeburn  8492:                         }
1.671     raeburn  8493:                     }
1.669     raeburn  8494:                 }
1.671     raeburn  8495:             }
                   8496:         }
1.314     www      8497:     }
1.492     albertel 8498: 
1.766     albertel 8499:     if ($priv eq 'bre'
                   8500: 	&& $thisallowed ne 'F' 
                   8501: 	&& $thisallowed ne '2'
                   8502: 	&& &is_portfolio_url($uri)) {
1.1172.2.77  raeburn  8503: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8504:     }
                   8505:     
1.52      www      8506: # Full access at system, domain or course-wide level? Exit.
1.29      www      8507:     if ($thisallowed=~/F/) {
                   8508: 	return 'F';
                   8509:     }
                   8510: 
1.52      www      8511: # If this is generating or modifying users, exit with special codes
1.29      www      8512: 
1.643     www      8513:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8514: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8515: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8516: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8517: 	    unless ($auname) { return $thisallowed; }
                   8518: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8519: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8520: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8521: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8522: 	}
1.52      www      8523: 	return $thisallowed;
                   8524:     }
                   8525: #
1.103     harris41 8526: # Gathered so far: system, domain and course wide privileges
1.52      www      8527: #
                   8528: # Course: See if uri or referer is an individual resource that is part of 
                   8529: # the course
                   8530: 
1.620     albertel 8531:     if ($env{'request.course.id'}) {
1.232     www      8532: 
1.1172.2.146.  .13(raeb 8533:-23):         if ($priv eq 'bre') {
                   8534:-23):             if (&is_coursetool_logo($uri)) {
                   8535:-23):                 return 'F';
                   8536:-23):             }
                   8537:-23):         }
                   8538:-23): 
1.1172.2.115  raeburn  8539: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8540: 
                   8541:         if ($priv eq 'mip') {
                   8542:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8543:                 return $thisallowed;
                   8544:             } else {
                   8545:                 return '';
                   8546:             }
                   8547:         }
                   8548: 
1.620     albertel 8549:        $courseprivid=$env{'request.course.id'};
                   8550:        if ($env{'request.course.sec'}) {
                   8551:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8552:        }
                   8553:        $courseprivid=~s/\_/\//;
                   8554:        my $checkreferer=1;
1.232     www      8555:        my ($match,$cond)=&is_on_map($uri);
                   8556:        if ($match) {
                   8557:            $statecond=$cond;
1.620     albertel 8558:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8559:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8560:                my $value = $1;
                   8561:                if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8562:22):                    my $deeplinkblock;
                   8563:22):                    unless ($nodeeplinkcheck) {
                   8564:22):                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8565:22):                    }
                   8566:22):                    if ($deeplinkblock) {
                   8567:22):                        $thisallowed = 'D';
                   8568:22):                    } elsif ($noblockcheck) {
1.1162    raeburn  8569:                        $thisallowed.=$value;
1.1172.2.65  raeburn  8570:                    } else {
1.1172.2.126  raeburn  8571:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1172.2.65  raeburn  8572:                        if (@blockers > 0) {
                   8573:                            $thisallowed = 'B';
                   8574:                        } else {
                   8575:                            $thisallowed.=$value;
                   8576:                        }
1.1162    raeburn  8577:                    }
                   8578:                } else {
                   8579:                    $thisallowed.=$value;
                   8580:                }
1.52      www      8581:                $checkreferer=0;
                   8582:            }
1.29      www      8583:        }
1.1172.2.126  raeburn  8584: 
1.148     www      8585:        if ($checkreferer) {
1.620     albertel 8586: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8587:             unless ($refuri) {
1.800     albertel 8588:                 foreach my $key (keys(%env)) {
                   8589: 		    if ($key=~/^httpref\..*\*/) {
                   8590: 			my $pattern=$key;
1.156     www      8591:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8592:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8593:                         $pattern=~s/\//\\\//g;
1.152     www      8594:                         if ($orguri=~/$pattern/) {
1.800     albertel 8595: 			    $refuri=$env{$key};
1.148     www      8596:                         }
                   8597:                     }
1.191     harris41 8598:                 }
1.148     www      8599:             }
1.232     www      8600: 
1.148     www      8601:          if ($refuri) { 
1.152     www      8602: 	  $refuri=&declutter($refuri);
1.232     www      8603:           my ($match,$cond)=&is_on_map($refuri);
                   8604:             if ($match) {
                   8605:               my $refstatecond=$cond;
1.620     albertel 8606:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8607:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8608:                   my $value = $1;
                   8609:                   if ($priv eq 'bre') {
1.1172.2.146.  .1(raebu 8610:22):                       my $deeplinkblock;
                   8611:22):                       unless ($nodeeplinkcheck) {
                   8612:22):                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8613:22):                       }
                   8614:22):                       if ($deeplinkblock) {
                   8615:22):                           $thisallowed = 'D';
                   8616:22):                       } elsif ($noblockcheck) {
1.1162    raeburn  8617:                           $thisallowed.=$value;
1.1172.2.65  raeburn  8618:                       } else {
1.1172.2.127  raeburn  8619:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1172.2.65  raeburn  8620:                           if (@blockers > 0) {
                   8621:                               $thisallowed = 'B';
                   8622:                           } else {
                   8623:                               $thisallowed.=$value;
                   8624:                           }
1.1162    raeburn  8625:                       }
                   8626:                   } else {
                   8627:                       $thisallowed.=$value;
                   8628:                   }
1.53      www      8629:                   $uri=$refuri;
                   8630:                   $statecond=$refstatecond;
1.52      www      8631:               }
                   8632:           }
1.148     www      8633:         }
1.29      www      8634:        }
1.52      www      8635:    }
1.29      www      8636: 
1.52      www      8637: #
1.103     harris41 8638: # Gathered now: all privileges that could apply, and condition number
1.52      www      8639: # 
                   8640: #
                   8641: # Full or no access?
                   8642: #
1.29      www      8643: 
1.52      www      8644:     if ($thisallowed=~/F/) {
                   8645: 	return 'F';
                   8646:     }
1.29      www      8647: 
1.52      www      8648:     unless ($thisallowed) {
                   8649:         return '';
                   8650:     }
1.29      www      8651: 
1.52      www      8652: # Restrictions exist, deal with them
                   8653: #
                   8654: #   C:according to course preferences
                   8655: #   R:according to resource settings
                   8656: #   L:unless locked
                   8657: #   X:according to user session state
                   8658: #
                   8659: 
                   8660: # Possibly locked functionality, check all courses
1.1172.2.142  raeburn  8661: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54      www      8662: # Locks might take effect only after 10 minutes cache expiration for other
1.1172.2.142  raeburn  8663: # courses, and 2 minutes for current course, in which user has st or ta role
                   8664: # which is neither expired nor a future role (unless current course).
1.52      www      8665: 
1.1172.2.142  raeburn  8666:     my ($needlockcheck,$now,$crsonly);
1.52      www      8667:     if ($thisallowed=~/L/) {
1.1172.2.142  raeburn  8668:         $now = time;
                   8669:         if ($priv eq 'bre') {
                   8670:             if ($uri ne '') {
                   8671:                 if ($orguri =~ m{^/+res/}) {
                   8672:                     if ($uri =~ m{^lib/templates/}) {
                   8673:                         if ($env{'request.course.id'}) {
                   8674:                             $crsonly = 1;
                   8675:                             $needlockcheck = 1;
                   8676:                         }
                   8677:                     } else {
                   8678:                         $needlockcheck = 1;
                   8679:                     }
                   8680:                 } elsif ($env{'request.course.id'}) {
                   8681:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
                   8682:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
                   8683:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
                   8684:                         $crsonly = 1;
                   8685:                     }
                   8686:                     $needlockcheck = 1;
                   8687:                 }
                   8688:             }
                   8689:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
                   8690:             $needlockcheck = 1;
                   8691:         }
                   8692:     }
                   8693:     if ($needlockcheck) {
                   8694:         foreach my $envkey (keys(%env)) {
1.54      www      8695:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8696:                my $courseid=$2;
                   8697:                my $roleid=$1.'.'.$2;
1.92      www      8698:                $courseid=~s/^\///;
1.1172.2.142  raeburn  8699:                unless ($env{'request.role'} eq $roleid) {
                   8700:                    my ($start,$end) = split(/\./,$env{$envkey});
                   8701:                    next unless (($now >= $start) && (!$end || $end > $now));
                   8702:                }
1.54      www      8703:                my $expiretime=600;
1.620     albertel 8704:                if ($env{'request.role'} eq $roleid) {
1.54      www      8705: 		  $expiretime=120;
                   8706:                }
                   8707: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8708:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8709:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8710: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8711:                }
1.620     albertel 8712:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8713:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8714: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8715:                        &log($env{'user.domain'},$env{'user.name'},
                   8716:                             $env{'user.home'},
1.57      www      8717:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8718:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8719:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8720: 		       return '';
                   8721:                    }
                   8722:                }
1.620     albertel 8723:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8724:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1172.2.142  raeburn  8725: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620     albertel 8726:                        &log($env{'user.domain'},$env{'user.name'},
                   8727:                             $env{'user.home'},
1.57      www      8728:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8729:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8730:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8731: 		       return '';
                   8732:                    }
                   8733:                }
                   8734: 	   }
1.29      www      8735:        }
1.52      www      8736:     }
1.1172.2.126  raeburn  8737: 
1.52      www      8738: #
                   8739: # Rest of the restrictions depend on selected course
                   8740: #
                   8741: 
1.620     albertel 8742:     unless ($env{'request.course.id'}) {
1.766     albertel 8743: 	if ($thisallowed eq 'A') {
                   8744: 	    return 'A';
1.814     raeburn  8745:         } elsif ($thisallowed eq 'B') {
                   8746:             return 'B';
1.766     albertel 8747: 	} else {
                   8748: 	    return '1';
                   8749: 	}
1.52      www      8750:     }
1.29      www      8751: 
1.52      www      8752: #
                   8753: # Now user is definitely in a course
                   8754: #
1.53      www      8755: 
                   8756: 
                   8757: # Course preferences
                   8758: 
                   8759:    if ($thisallowed=~/C/) {
1.620     albertel 8760:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8761:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8762:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8763: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  8764: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8765: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8766: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8767: 			$env{'request.course.id'});
                   8768: 	   }
1.237     www      8769:            return '';
                   8770:        }
                   8771: 
1.620     albertel 8772:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8773: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  8774: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8775: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8776: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8777: 			$env{'request.course.id'});
                   8778: 	   }
1.54      www      8779:            return '';
                   8780:        }
1.53      www      8781:    }
                   8782: 
                   8783: # Resource preferences
                   8784: 
                   8785:    if ($thisallowed=~/R/) {
1.620     albertel 8786:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8787:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8788: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8789: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8790: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8791: 	   }
                   8792: 	   return '';
1.54      www      8793:        }
1.53      www      8794:    }
1.30      www      8795: 
1.1172.2.146.  .1(raebu 8796:22): # Restricted for deeplinked session?
                   8797:22): 
                   8798:22):     if ($env{'request.deeplink.login'}) {
                   8799:22):         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
                   8800:22):             if (!$symb) { $symb=&symbread($uri,1); }
                   8801:22):             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
                   8802:22):                 return '';
                   8803:22):             }
                   8804:22):         }
                   8805:22):     }
                   8806:22): 
1.246     www      8807: # Restricted by state or randomout?
1.30      www      8808: 
1.52      www      8809:    if ($thisallowed=~/X/) {
1.620     albertel 8810:       if ($env{'acc.randomout'}) {
1.579     albertel 8811: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8812:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8813:             return ''; 
                   8814:          }
1.247     www      8815:       }
                   8816:       if (&condval($statecond)) {
1.52      www      8817: 	 return '2';
                   8818:       } else {
                   8819:          return '';
                   8820:       }
                   8821:    }
1.30      www      8822: 
1.766     albertel 8823:     if ($thisallowed eq 'A') {
                   8824: 	return 'A';
1.814     raeburn  8825:     } elsif ($thisallowed eq 'B') {
                   8826:         return 'B';
1.1172.2.146.  .1(raebu 8827:22):     } elsif ($thisallowed eq 'D') {
                   8828:22):         return 'D';
1.766     albertel 8829:     }
1.52      www      8830:    return 'F';
1.232     www      8831: }
1.1162    raeburn  8832: 
1.1172.2.13  raeburn  8833: # ------------------------------------------- Check construction space access
                   8834: 
                   8835: sub constructaccess {
                   8836:     my ($url,$setpriv)=@_;
                   8837: 
                   8838: # We do not allow editing of previous versions of files
                   8839:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8840: 
                   8841: # Get username and domain from URL
                   8842:     my ($ownername,$ownerdomain,$ownerhome);
                   8843: 
                   8844:     ($ownerdomain,$ownername) =
1.1172.2.83  raeburn  8845:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
1.1172.2.13  raeburn  8846: 
                   8847: # The URL does not really point to any authorspace, forget it
                   8848:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8849: 
                   8850: # Now we need to see if the user has access to the authorspace of
                   8851: # $ownername at $ownerdomain
                   8852: 
                   8853:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8854: # Real author for this?
                   8855:        $ownerhome = $env{'user.home'};
                   8856:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8857:           return ($ownername,$ownerdomain,$ownerhome);
                   8858:        }
                   8859:     } else {
                   8860: # Co-author for this?
                   8861:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8862:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8863:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8864:             return ($ownername,$ownerdomain,$ownerhome);
                   8865:         }
                   8866:     }
                   8867: 
                   8868: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8869: # we might as well leave
                   8870:    unless ($setpriv) { return ''; }
                   8871: 
                   8872: # Backdoor access?
                   8873:     my $allowed=&allowed('eco',$ownerdomain);
                   8874: # Nope
                   8875:     unless ($allowed) { return ''; }
                   8876: # Looks like we may have access, but could be locked by the owner of the construction space
                   8877:     if ($allowed eq 'U') {
                   8878:         my %blocked=&get('environment',['domcoord.author'],
                   8879:                          $ownerdomain,$ownername);
                   8880: # Is blocked by owner
                   8881:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8882:     }
                   8883:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8884: # Grant temporary access
                   8885:         my $then=$env{'user.login.time'};
1.1172.2.16  raeburn  8886:         my $update=$env{'user.update.time'};
1.1172.2.13  raeburn  8887:         if (!$update) { $update = $then; }
                   8888:         my $refresh=$env{'user.refresh.time'};
                   8889:         if (!$refresh) { $refresh = $update; }
                   8890:         my $now = time;
                   8891:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8892:                            $now,'ca','constructaccess');
                   8893:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8894:         return($ownername,$ownerdomain,$ownerhome);
                   8895:     }
                   8896: # No business here
                   8897:     return '';
                   8898: }
                   8899: 
1.1172.2.66  raeburn  8900: # ----------------------------------------------------------- Content Blocking
                   8901: 
                   8902: {
                   8903: # Caches for faster Course Contents display where content blocking
                   8904: # is in operation (i.e., interval param set) for timed quiz.
                   8905: #
                   8906: # User for whom data are being temporarily cached.
                   8907: my $cacheduser='';
1.1172.2.126  raeburn  8908: # Course for which data are being temporarily cached.
                   8909: my $cachedcid='';
1.1172.2.66  raeburn  8910: # Cached blockers for this user (a hash of blocking items).
                   8911: my %cachedblockers=();
                   8912: # When the data were last cached.
                   8913: my $cachedlast='';
                   8914: 
                   8915: sub load_all_blockers {
1.1172.2.128  raeburn  8916:     my ($uname,$udom)=@_;
1.1172.2.66  raeburn  8917:     if (($uname ne '') && ($udom ne '')) {
                   8918:         if (($cacheduser eq $uname.':'.$udom) &&
1.1172.2.126  raeburn  8919:             ($cachedcid eq $env{'request.course.id'}) &&
1.1172.2.128  raeburn  8920:             (abs($cachedlast-time)<5)) {
1.1172.2.66  raeburn  8921:             return;
                   8922:         }
                   8923:     }
                   8924:     $cachedlast=time;
                   8925:     $cacheduser=$uname.':'.$udom;
1.1172.2.126  raeburn  8926:     $cachedcid=$env{'request.course.id'};
1.1172.2.128  raeburn  8927:     %cachedblockers = &get_commblock_resources();
1.1172.2.126  raeburn  8928:     return;
1.1172.2.66  raeburn  8929: }
                   8930: 
1.1162    raeburn  8931: sub get_comm_blocks {
                   8932:     my ($cdom,$cnum) = @_;
                   8933:     if ($cdom eq '' || $cnum eq '') {
                   8934:         return unless ($env{'request.course.id'});
                   8935:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8936:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8937:     }
                   8938:     my %commblocks;
                   8939:     my $hashid=$cdom.'_'.$cnum;
                   8940:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8941:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8942:         %commblocks = %{$blocksref};
                   8943:     } else {
                   8944:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8945:         my $cachetime = 600;
                   8946:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8947:     }
                   8948:     return %commblocks;
                   8949: }
                   8950: 
1.1172.2.66  raeburn  8951: sub get_commblock_resources {
                   8952:     my ($blocks) = @_;
                   8953:     my %blockers = ();
                   8954:     return %blockers unless ($env{'request.course.id'});
1.1172.2.142  raeburn  8955:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8956:     if ($env{'request.course.sec'}) {
                   8957:         $courseurl .= '/'.$env{'request.course.sec'};
                   8958:     }
                   8959:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162    raeburn  8960:     my %commblocks;
                   8961:     if (ref($blocks) eq 'HASH') {
                   8962:         %commblocks = %{$blocks};
                   8963:     } else {
                   8964:         %commblocks = &get_comm_blocks();
                   8965:     }
1.1172.2.66  raeburn  8966:     return %blockers unless (keys(%commblocks) > 0);
1.1163    raeburn  8967:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1172.2.66  raeburn  8968:     return %blockers unless (ref($navmap));
                   8969:     my $now = time;
1.1162    raeburn  8970:     foreach my $block (keys(%commblocks)) {
                   8971:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8972:             my ($start,$end) = ($1,$2);
                   8973:             if ($start <= $now && $end >= $now) {
                   8974:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8975:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8976:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1172.2.66  raeburn  8977:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8978:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
1.1162    raeburn  8979:                             }
                   8980:                         }
                   8981:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1172.2.66  raeburn  8982:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8983:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8984:                             }
                   8985:                         }
                   8986:                     }
                   8987:                 }
                   8988:             }
                   8989:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8990:             my $item = $1;
                   8991:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8992:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1172.2.142  raeburn  8993:                     my (@interval,$mapname);
1.1172.2.66  raeburn  8994:                     my $type = 'map';
                   8995:                     if ($item eq 'course') {
                   8996:                         $type = 'course';
                   8997:                         @interval=&EXT("resource.0.interval");
                   8998:                     } else {
                   8999:                         if ($item =~ /___\d+___/) {
                   9000:                             $type = 'resource';
                   9001:                             @interval=&EXT("resource.0.interval",$item);
1.1162    raeburn  9002:                         } else {
1.1172.2.142  raeburn  9003:                             $mapname = &deversion($item);
                   9004:                             if (ref($navmap)) {
                   9005:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
                   9006:                                 @interval = ($timelimit,'map');
1.1162    raeburn  9007:                             }
                   9008:                         }
1.1172.2.66  raeburn  9009:                     }
1.1172.2.146.  .1(raebu 9010:22):                     if ($interval[0] =~ /^(\d+)/) {
                   9011:22):                         my $timelimit = $1;
1.1172.2.66  raeburn  9012:                         my $first_access;
                   9013:                         if ($type eq 'resource') {
                   9014:                             $first_access=&get_first_access($interval[1],$item);
                   9015:                         } elsif ($type eq 'map') {
                   9016:                             $first_access=&get_first_access($interval[1],undef,$item);
                   9017:                         } else {
                   9018:                             $first_access=&get_first_access($interval[1]);
                   9019:                         }
                   9020:                         if ($first_access) {
1.1172.2.146.  .1(raebu 9021:22):                             my $timesup = $first_access+$timelimit;
1.1172.2.66  raeburn  9022:                             if ($timesup > $now) {
                   9023:                                 my $activeblock;
1.1172.2.142  raeburn  9024:                                 if ($type eq 'resource') {
                   9025:                                     if (ref($navmap)) {
                   9026:                                         my $res = $navmap->getBySymb($item);
                   9027:                                         if ($res->answerable()) {
                   9028:                                             $activeblock = 1;
                   9029:                                         }
                   9030:                                     }
                   9031:                                 } elsif ($type eq 'map') {
                   9032:                                     my $mapsymb = &symbread($mapname,1);
                   9033:                                     if (($mapsymb) && (ref($navmap))) {
                   9034:                                         my $mapres = $navmap->getBySymb($mapsymb);
                   9035:                                         if (ref($mapres)) {
                   9036:                                             my $first = $mapres->map_start();
                   9037:                                             my $finish = $mapres->map_finish();
                   9038:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   9039:                                             if (ref($it)) {
                   9040:                                                 my $res;
                   9041:                                                 while ($res = $it->next(undef,1)) {
                   9042:                                                     next unless (ref($res));
                   9043:                                                     my $symb = $res->symb();
                   9044:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
                   9045:                                                     @interval=&EXT("resource.0.interval",$symb);
                   9046:                                                     if ($interval[1] eq 'map') {
                   9047:                                                         if ($res->answerable()) {
                   9048:                                                             $activeblock = 1;
                   9049:                                                             last;
                   9050:                                                         }
                   9051:                                                     }
                   9052:                                                 }
                   9053:                                             }
                   9054:                                         }
1.1172.2.66  raeburn  9055:                                     }
                   9056:                                 }
                   9057:                                 if ($activeblock) {
                   9058:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   9059:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   9060:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   9061:                                          }
                   9062:                                     }
                   9063:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   9064:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   9065:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  9066:                                         }
1.1162    raeburn  9067:                                     }
                   9068:                                 }
                   9069:                             }
                   9070:                         }
                   9071:                     }
                   9072:                 }
                   9073:             }
                   9074:         }
                   9075:     }
1.1172.2.66  raeburn  9076:     return %blockers;
1.1162    raeburn  9077: }
                   9078: 
1.1172.2.66  raeburn  9079: sub has_comm_blocking {
1.1172.2.128  raeburn  9080:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1172.2.66  raeburn  9081:     my @blockers;
                   9082:     return unless ($env{'request.course.id'});
                   9083:     return unless ($priv eq 'bre');
                   9084:     return if ($env{'request.state'} eq 'construct');
1.1172.2.142  raeburn  9085:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   9086:     if ($env{'request.course.sec'}) {
                   9087:         $courseurl .= '/'.$env{'request.course.sec'};
                   9088:     }
                   9089:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1172.2.128  raeburn  9090:     my %blockinfo;
                   9091:     if (ref($blocks) eq 'HASH') {
                   9092:         %blockinfo = &get_commblock_resources($blocks);
                   9093:     } else {
                   9094:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   9095:         %blockinfo = %cachedblockers;
                   9096:     }
                   9097:     return unless (keys(%blockinfo) > 0);
1.1172.2.66  raeburn  9098:     my (%possibles,@symbs);
                   9099:     if (!$symb) {
1.1172.2.128  raeburn  9100:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  9101:     }
1.1172.2.66  raeburn  9102:     if ($symb) {
                   9103:         @symbs = ($symb);
                   9104:     } elsif (keys(%possibles)) {
                   9105:         @symbs = keys(%possibles);
                   9106:     }
                   9107:     my $noblock;
                   9108:     foreach my $symb (@symbs) {
                   9109:         last if ($noblock);
                   9110:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1172.2.128  raeburn  9111:         foreach my $block (keys(%blockinfo)) {
1.1172.2.66  raeburn  9112:             if ($block =~ /^firstaccess____(.+)$/) {
                   9113:                 my $item = $1;
1.1172.2.126  raeburn  9114:                 unless ($blocked) {
                   9115:                     if (($item eq $map) || ($item eq $symb)) {
                   9116:                         $noblock = 1;
                   9117:                         last;
                   9118:                     }
1.1172.2.66  raeburn  9119:                 }
1.1162    raeburn  9120:             }
1.1172.2.128  raeburn  9121:             if (ref($blockinfo{$block}) eq 'HASH') {
                   9122:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   9123:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1172.2.66  raeburn  9124:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   9125:                             push(@blockers,$block);
                   9126:                         }
                   9127:                     }
                   9128:                 }
1.1172.2.128  raeburn  9129:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   9130:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1172.2.126  raeburn  9131:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   9132:                             push(@blockers,$block);
                   9133:                         }
1.1172.2.66  raeburn  9134:                     }
                   9135:                 }
1.1162    raeburn  9136:             }
                   9137:         }
                   9138:     }
1.1172.2.126  raeburn  9139:     unless ($noblock) {
                   9140:         return @blockers;
                   9141:     }
                   9142:     return;
1.1172.2.66  raeburn  9143: }
1.1162    raeburn  9144: }
                   9145: 
1.1172.2.146.  .1(raebu 9146:22): sub deeplink_check {
                   9147:22):     my ($priv,$symb,$uri) = @_;
                   9148:22):     return unless ($env{'request.course.id'});
                   9149:22):     return unless ($priv eq 'bre');
                   9150:22):     return if ($env{'request.state'} eq 'construct');
                   9151:22):     return if ($env{'request.role.adv'});
                   9152:22):     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9153:22):     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9154:22):     my (%possibles,@symbs);
                   9155:22):     if (!$symb) {
                   9156:22):         $symb = &symbread($uri,1,1,1,\%possibles);
                   9157:22):     }
                   9158:22):     if ($symb) {
                   9159:22):         @symbs = ($symb);
                   9160:22):     } elsif (keys(%possibles)) {
                   9161:22):         @symbs = keys(%possibles);
                   9162:22):     }
                   9163:22): 
                   9164:22):     my ($deeplink_symb,$allow);
                   9165:22):     if ($env{'request.deeplink.login'}) {
                   9166:22):         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
                   9167:22):     }
                   9168:22):     foreach my $symb (@symbs) {
                   9169:22):         last if ($allow);
                   9170:22):         my $deeplink = &EXT("resource.0.deeplink",$symb);
                   9171:22):         if ($deeplink eq '') {
                   9172:22):             $allow = 1;
                   9173:22):         } else {
                   9174:22):             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
                   9175:22):             if ($state ne 'only') {
                   9176:22):                 $allow = 1;
                   9177:22):             } else {
                   9178:22):                 my $check_deeplink_entry;
                   9179:22):                 if ($protect ne 'none') {
                   9180:22):                     my ($acctype,$item) = split(/:/,$protect);
                   9181:22):                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
                   9182:22):                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
                   9183:22):                             $check_deeplink_entry = 1
                   9184:22):                         }
                   9185:22):                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
                   9186:22):                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
                   9187:22):                             $check_deeplink_entry = 1;
                   9188:22):                         }
                   9189:22):                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
                   9190:22):                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
                   9191:22):                             $check_deeplink_entry = 1;
                   9192:22):                         }
                   9193:22):                     }
                   9194:22):                 }
                   9195:22):                 if (($protect eq 'none') || ($check_deeplink_entry)) {
                   9196:22):                     if ($scope eq 'res') {
                   9197:22):                         if ($symb eq $deeplink_symb) {
                   9198:22):                             $allow = 1;
                   9199:22):                         }
                   9200:22):                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
                   9201:22):                         my ($map_from_symb,$map_from_login);
                   9202:22):                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
                   9203:22):                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9204:22):                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
                   9205:22):                         } else {
                   9206:22):                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
                   9207:22):                         }
                   9208:22):                         if (($map_from_symb) && ($map_from_login)) {
                   9209:22):                             if ($map_from_symb eq $map_from_login) {
                   9210:22):                                 $allow = 1;
                   9211:22):                             } elsif ($scope eq 'rec') {
                   9212:22):                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
                   9213:22):                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
                   9214:22):                                     $allow = 1;
                   9215:22):                                 }
                   9216:22):                             }
                   9217:22):                         }
                   9218:22):                     }
                   9219:22):                 }
                   9220:22):             }
                   9221:22):         }
                   9222:22):     }
                   9223:22):     return if ($allow);
                   9224:22):     return 1;
                   9225:22): }
                   9226:22): 
1.1172.2.66  raeburn  9227: # -------------------------------- Deversion and split uri into path an filename
                   9228: 
1.1133    foxr     9229: #
1.1172.2.66  raeburn  9230: #   Removes the version from a URI and
1.1133    foxr     9231: #   splits it in to its filename and path to the filename.
                   9232: #   Seems like File::Basename could have done this more clearly.
                   9233: #   Parameters:
                   9234: #      $uri   - input URI
                   9235: #   Returns:
                   9236: #     Two element list consisting of 
                   9237: #     $pathname  - the URI up to and excluding the trailing /
                   9238: #     $filename  - The part of the URI following the last /
                   9239: #  NOTE:
                   9240: #    Another realization of this is simply:
                   9241: #    use File::Basename;
                   9242: #    ...
                   9243: #    $uri = shift;
                   9244: #    $filename = basename($uri);
                   9245: #    $path     = dirname($uri);
                   9246: #    return ($filename, $path);
                   9247: #
                   9248: #     The implementation below is probably faster however.
                   9249: #
1.710     albertel 9250: sub split_uri_for_cond {
                   9251:     my $uri=&deversion(&declutter(shift));
                   9252:     my @uriparts=split(/\//,$uri);
                   9253:     my $filename=pop(@uriparts);
                   9254:     my $pathname=join('/',@uriparts);
                   9255:     return ($pathname,$filename);
                   9256: }
1.232     www      9257: # --------------------------------------------------- Is a resource on the map?
                   9258: 
                   9259: sub is_on_map {
1.710     albertel 9260:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 9261:     #Trying to find the conditional for the file
1.620     albertel 9262:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 9263: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      9264:     if ($match) {
1.289     bowersj2 9265: 	return (1,$1);
                   9266:     } else {
1.434     www      9267: 	return (0,0);
1.289     bowersj2 9268:     }
1.12      www      9269: }
                   9270: 
1.427     www      9271: # --------------------------------------------------------- Get symb from alias
                   9272: 
                   9273: sub get_symb_from_alias {
                   9274:     my $symb=shift;
                   9275:     my ($map,$resid,$url)=&decode_symb($symb);
                   9276: # Already is a symb
                   9277:     if ($url) { return $symb; }
                   9278: # Must be an alias
                   9279:     my $aliassymb='';
                   9280:     my %bighash;
1.620     albertel 9281:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      9282:                             &GDBM_READER(),0640)) {
                   9283:         my $rid=$bighash{'mapalias_'.$symb};
                   9284: 	if ($rid) {
                   9285: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 9286: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   9287: 				    $resid,$bighash{'src_'.$rid});
1.427     www      9288: 	}
                   9289:         untie %bighash;
                   9290:     }
                   9291:     return $aliassymb;
                   9292: }
                   9293: 
1.12      www      9294: # ----------------------------------------------------------------- Define Role
                   9295: 
                   9296: sub definerole {
                   9297:   if (allowed('mcr','/')) {
1.1172.2.84  raeburn  9298:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 9299:     foreach my $role (split(':',$sysrole)) {
                   9300: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9301:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   9302:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   9303: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9304:                return "refused:s:$crole&$cqual"; 
                   9305:             }
                   9306:         }
1.191     harris41 9307:     }
1.800     albertel 9308:     foreach my $role (split(':',$domrole)) {
                   9309: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9310:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   9311:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   9312: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      9313:                return "refused:d:$crole&$cqual"; 
                   9314:             }
                   9315:         }
1.191     harris41 9316:     }
1.800     albertel 9317:     foreach my $role (split(':',$courole)) {
                   9318: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9319:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   9320:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   9321: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9322:                return "refused:c:$crole&$cqual"; 
                   9323:             }
                   9324:         }
1.191     harris41 9325:     }
1.1172.2.84  raeburn  9326:     my $uhome;
                   9327:     if (($uname ne '') && ($udom ne '')) {
                   9328:         $uhome = &homeserver($uname,$udom);
                   9329:         return $uhome if ($uhome eq 'no_host');
                   9330:     } else {
                   9331:         $uname = $env{'user.name'};
                   9332:         $udom = $env{'user.domain'};
                   9333:         $uhome = $env{'user.home'};
                   9334:     }
1.620     albertel 9335:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1172.2.84  raeburn  9336:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      9337:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1172.2.84  raeburn  9338:     return reply($command,$uhome);
1.12      www      9339:   } else {
                   9340:     return 'refused';
                   9341:   }
1.105     harris41 9342: }
                   9343: 
                   9344: # ---------------- Make a metadata query against the network of library servers
                   9345: 
                   9346: sub metadata_query {
1.1172.2.33  raeburn  9347:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 9348:     my %rhash;
1.845     albertel 9349:     my %libserv = &all_library();
1.244     matthew  9350:     my @server_list = (defined($server_array) ? @$server_array
                   9351:                                               : keys(%libserv) );
                   9352:     for my $server (@server_list) {
1.1172.2.33  raeburn  9353:         my $domains = '';
                   9354:         if (ref($domains_hash) eq 'HASH') {
                   9355:             $domains = $domains_hash->{$server};    
                   9356:         }
1.118     harris41 9357: 	unless ($custom or $customshow) {
1.1172.2.33  raeburn  9358: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 9359: 	    $rhash{$server}=$reply;
                   9360: 	}
                   9361: 	else {
                   9362: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1172.2.33  raeburn  9363: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 9364: 			     $server);
                   9365: 	    $rhash{$server}=$reply;
                   9366: 	}
1.112     harris41 9367:     }
1.118     harris41 9368:     return \%rhash;
1.240     www      9369: }
                   9370: 
                   9371: # ----------------------------------------- Send log queries and wait for reply
                   9372: 
                   9373: sub log_query {
                   9374:     my ($uname,$udom,$query,%filters)=@_;
                   9375:     my $uhome=&homeserver($uname,$udom);
                   9376:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 9377:     my $uhost=&hostname($uhome);
1.800     albertel 9378:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      9379:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   9380:                        $uhome);
1.479     albertel 9381:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      9382:     return get_query_reply($queryid);
                   9383: }
                   9384: 
1.818     raeburn  9385: # -------------------------- Update MySQL table for portfolio file
                   9386: 
                   9387: sub update_portfolio_table {
1.821     raeburn  9388:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  9389:     if ($group ne '') {
                   9390:         $file_name =~s /^\Q$group\E//;
                   9391:     }
1.818     raeburn  9392:     my $homeserver = &homeserver($uname,$udom);
                   9393:     my $queryid=
1.821     raeburn  9394:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   9395:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  9396:     my $reply = &get_query_reply($queryid);
                   9397:     return $reply;
                   9398: }
                   9399: 
1.899     raeburn  9400: # -------------------------- Update MySQL allusers table
                   9401: 
                   9402: sub update_allusers_table {
                   9403:     my ($uname,$udom,$names) = @_;
                   9404:     my $homeserver = &homeserver($uname,$udom);
                   9405:     my $queryid=
                   9406:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   9407:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   9408:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   9409:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   9410:                'generation='.&escape($names->{'generation'}).'%%'.
                   9411:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   9412:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  9413:     return;
1.899     raeburn  9414: }
                   9415: 
1.508     raeburn  9416: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  9417: 
                   9418: sub fetch_enrollment_query {
1.511     raeburn  9419:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1172.2.79  raeburn  9420:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  9421:     my $maxtries = 1;
1.508     raeburn  9422:     if ($context eq 'automated') {
                   9423:         $homeserver = $perlvar{'lonHostID'};
1.1172.2.79  raeburn  9424:         $sleep = 2;
                   9425:         $loopmax = 100;
1.547     raeburn  9426:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  9427:     } else {
                   9428:         $homeserver = &homeserver($cnum,$dom);
                   9429:     }
1.838     albertel 9430:     my $host=&hostname($homeserver);
1.506     raeburn  9431:     my $cmd = '';
1.1000    raeburn  9432:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 9433:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  9434:     }
                   9435:     $cmd =~ s/%%$//;
                   9436:     $cmd = &escape($cmd);
                   9437:     my $query = 'fetchenrollment';
1.620     albertel 9438:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  9439:     unless ($queryid=~/^\Q$host\E\_/) { 
                   9440:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   9441:         return 'error: '.$queryid;
                   9442:     }
1.1172.2.93  raeburn  9443:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9444:     my $tries = 1;
                   9445:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1172.2.79  raeburn  9446:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9447:         $tries ++;
                   9448:     }
1.526     raeburn  9449:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 9450:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  9451:     } else {
1.901     albertel 9452:         my @responses = split(/:/,$reply);
1.1172.2.82  raeburn  9453:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 9454:             foreach my $line (@responses) {
                   9455:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  9456:                 $$replyref{$key} = $value;
                   9457:             }
                   9458:         } else {
1.1117    foxr     9459:             my $pathname = LONCAPA::tempdir();
1.800     albertel 9460:             foreach my $line (@responses) {
                   9461:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  9462:                 $$replyref{$key} = $value;
                   9463:                 if ($value > 0) {
1.800     albertel 9464:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   9465:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  9466:                         my $destname = $pathname.'/'.$filename;
                   9467:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  9468:                         if ($xml_classlist =~ /^error/) {
                   9469:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   9470:                         } else {
1.1172.2.96  raeburn  9471:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  9472:                                 print FILE &unescape($xml_classlist);
                   9473:                                 close(FILE);
1.526     raeburn  9474:                             } else {
                   9475:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  9476:                             }
                   9477:                         }
                   9478:                     }
                   9479:                 }
                   9480:             }
                   9481:         }
                   9482:         return 'ok';
                   9483:     }
                   9484:     return 'error';
                   9485: }
                   9486: 
1.242     www      9487: sub get_query_reply {
1.1172.2.79  raeburn  9488:     my ($queryid,$sleep,$loopmax) = @_;
                   9489:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9490:         $sleep = 0.2;
                   9491:     }
                   9492:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9493:         $loopmax = 100;
                   9494:     }
1.1117    foxr     9495:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9496:     my $reply='';
1.1172.2.79  raeburn  9497:     for (1..$loopmax) {
                   9498: 	sleep($sleep);
1.240     www      9499:         if (-e $replyfile.'.end') {
1.1172.2.96  raeburn  9500: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9501: 		$reply = join('',<$fh>);
                   9502: 		close($fh);
1.240     www      9503: 	   } else { return 'error: reply_file_error'; }
1.242     www      9504:            return &unescape($reply);
                   9505: 	}
1.240     www      9506:     }
1.242     www      9507:     return 'timeout:'.$queryid;
1.240     www      9508: }
                   9509: 
                   9510: sub courselog_query {
1.241     www      9511: #
                   9512: # possible filters:
                   9513: # url: url or symb
                   9514: # username
                   9515: # domain
                   9516: # action: view, submit, grade
                   9517: # start: timestamp
                   9518: # end: timestamp
                   9519: #
1.240     www      9520:     my (%filters)=@_;
1.620     albertel 9521:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9522:     if ($filters{'url'}) {
                   9523: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9524:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9525:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9526:     }
1.620     albertel 9527:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9528:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9529:     return &log_query($cname,$cdom,'courselog',%filters);
                   9530: }
                   9531: 
                   9532: sub userlog_query {
1.858     raeburn  9533: #
                   9534: # possible filters:
                   9535: # action: log check role
                   9536: # start: timestamp
                   9537: # end: timestamp
                   9538: #
1.240     www      9539:     my ($uname,$udom,%filters)=@_;
                   9540:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9541: }
                   9542: 
1.506     raeburn  9543: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9544: 
                   9545: sub auto_run {
1.508     raeburn  9546:     my ($cnum,$cdom) = @_;
1.876     raeburn  9547:     my $response = 0;
                   9548:     my $settings;
                   9549:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9550:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9551:         $settings = $domconfig{'autoenroll'};
                   9552:         if ($settings->{'run'} eq '1') {
                   9553:             $response = 1;
                   9554:         }
                   9555:     } else {
1.934     raeburn  9556:         my $homeserver;
                   9557:         if (&is_course($cdom,$cnum)) {
                   9558:             $homeserver = &homeserver($cnum,$cdom);
                   9559:         } else {
                   9560:             $homeserver = &domain($cdom,'primary');
                   9561:         }
                   9562:         if ($homeserver ne 'no_host') {
                   9563:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9564:         }
1.876     raeburn  9565:     }
1.506     raeburn  9566:     return $response;
                   9567: }
1.776     albertel 9568: 
1.506     raeburn  9569: sub auto_get_sections {
1.508     raeburn  9570:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9571:     my $homeserver;
                   9572:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9573:         $homeserver = &homeserver($cnum,$cdom);
                   9574:     }
                   9575:     if (!defined($homeserver)) { 
                   9576:         if ($cdom =~ /^$match_domain$/) {
                   9577:             $homeserver = &domain($cdom,'primary');
                   9578:         }
                   9579:     }
                   9580:     my @secs;
                   9581:     if (defined($homeserver)) {
                   9582:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9583:         unless ($response eq 'refused') {
                   9584:             @secs = split(/:/,$response);
                   9585:         }
1.506     raeburn  9586:     }
                   9587:     return @secs;
                   9588: }
1.776     albertel 9589: 
1.506     raeburn  9590: sub auto_new_course {
1.1099    raeburn  9591:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9592:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9593:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9594:     return $response;
                   9595: }
1.776     albertel 9596: 
1.506     raeburn  9597: sub auto_validate_courseID {
1.508     raeburn  9598:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9599:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9600:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9601:     return $response;
                   9602: }
1.776     albertel 9603: 
1.1007    raeburn  9604: sub auto_validate_instcode {
1.1020    raeburn  9605:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9606:     my ($homeserver,$response);
                   9607:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9608:         $homeserver = &homeserver($cnum,$cdom);
                   9609:     }
                   9610:     if (!defined($homeserver)) {
                   9611:         if ($cdom =~ /^$match_domain$/) {
                   9612:             $homeserver = &domain($cdom,'primary');
                   9613:         }
                   9614:     }
1.1065    raeburn  9615:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9616:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1172.2.19  raeburn  9617:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9618:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9619: }
                   9620: 
1.1172.2.141  raeburn  9621: sub auto_validate_inst_crosslist {
                   9622:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
                   9623:     my ($homeserver,$response);
                   9624:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9625:         $homeserver = &homeserver($cnum,$cdom);
                   9626:     }
                   9627:     if (!defined($homeserver)) {
                   9628:         if ($cdom =~ /^$match_domain$/) {
                   9629:             $homeserver = &domain($cdom,'primary');
                   9630:         }
                   9631:     }
                   9632:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
                   9633:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
                   9634:                          &escape($instcode).':'.&escape($inst_xlist).':'.
                   9635:                          &escape($coowner),$homeserver);
                   9636:     }
                   9637:     return $response;
                   9638: }
                   9639: 
1.506     raeburn  9640: sub auto_create_password {
1.873     raeburn  9641:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9642:     my ($homeserver,$response);
1.506     raeburn  9643:     my $create_passwd = 0;
                   9644:     my $authchk = '';
1.873     raeburn  9645:     if ($udom =~ /^$match_domain$/) {
                   9646:         $homeserver = &domain($udom,'primary');
                   9647:     }
                   9648:     if ($homeserver eq '') {
                   9649:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9650:             $homeserver = &homeserver($cnum,$cdom);
                   9651:         }
                   9652:     }
                   9653:     if ($homeserver eq '') {
                   9654:         $authchk = 'nodomain';
1.506     raeburn  9655:     } else {
1.873     raeburn  9656:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9657:         if ($response eq 'refused') {
                   9658:             $authchk = 'refused';
                   9659:         } else {
1.901     albertel 9660:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9661:         }
1.506     raeburn  9662:     }
                   9663:     return ($authparam,$create_passwd,$authchk);
                   9664: }
                   9665: 
1.706     raeburn  9666: sub auto_photo_permission {
                   9667:     my ($cnum,$cdom,$students) = @_;
                   9668:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9669:     my ($outcome,$perm_reqd,$conditions) = 
                   9670: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9671:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9672: 	return (undef,undef);
                   9673:     }
1.706     raeburn  9674:     return ($outcome,$perm_reqd,$conditions);
                   9675: }
                   9676: 
                   9677: sub auto_checkphotos {
                   9678:     my ($uname,$udom,$pid) = @_;
                   9679:     my $homeserver = &homeserver($uname,$udom);
                   9680:     my ($result,$resulttype);
                   9681:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9682: 				   &escape($uname).':'.&escape($pid),
                   9683: 				   $homeserver));
1.709     albertel 9684:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9685: 	return (undef,undef);
                   9686:     }
1.706     raeburn  9687:     if ($outcome) {
                   9688:         ($result,$resulttype) = split(/:/,$outcome);
                   9689:     } 
                   9690:     return ($result,$resulttype);
                   9691: }
                   9692: 
                   9693: sub auto_photochoice {
                   9694:     my ($cnum,$cdom) = @_;
                   9695:     my $homeserver = &homeserver($cnum,$cdom);
                   9696:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9697: 						       &escape($cdom),
                   9698: 						       $homeserver)));
1.709     albertel 9699:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9700: 	return (undef,undef);
                   9701:     }
1.706     raeburn  9702:     return ($update,$comment);
                   9703: }
                   9704: 
                   9705: sub auto_photoupdate {
                   9706:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9707:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9708:     my $host=&hostname($homeserver);
1.706     raeburn  9709:     my $cmd = '';
                   9710:     my $maxtries = 1;
1.800     albertel 9711:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9712:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9713:     }
                   9714:     $cmd =~ s/%%$//;
                   9715:     $cmd = &escape($cmd);
                   9716:     my $query = 'institutionalphotos';
                   9717:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9718:     unless ($queryid=~/^\Q$host\E\_/) {
                   9719:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9720:         return 'error: '.$queryid;
                   9721:     }
                   9722:     my $reply = &get_query_reply($queryid);
                   9723:     my $tries = 1;
                   9724:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9725:         $reply = &get_query_reply($queryid);
                   9726:         $tries ++;
                   9727:     }
                   9728:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9729:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9730:     } else {
                   9731:         my @responses = split(/:/,$reply);
                   9732:         my $outcome = shift(@responses); 
                   9733:         foreach my $item (@responses) {
                   9734:             my ($key,$value) = split(/=/,$item);
                   9735:             $$photo{$key} = $value;
                   9736:         }
                   9737:         return $outcome;
                   9738:     }
                   9739:     return 'error';
                   9740: }
                   9741: 
1.521     raeburn  9742: sub auto_instcode_format {
1.793     albertel 9743:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9744: 	$cat_order) = @_;
1.521     raeburn  9745:     my $courses = '';
1.772     raeburn  9746:     my @homeservers;
1.521     raeburn  9747:     if ($caller eq 'global') {
1.841     albertel 9748: 	my %servers = &get_servers($codedom,'library');
                   9749: 	foreach my $tryserver (keys(%servers)) {
                   9750: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9751: 		push(@homeservers,$tryserver);
                   9752: 	    }
1.584     raeburn  9753:         }
1.1022    raeburn  9754:     } elsif ($caller eq 'requests') {
                   9755:         if ($codedom =~ /^$match_domain$/) {
                   9756:             my $chome = &domain($codedom,'primary');
                   9757:             unless ($chome eq 'no_host') {
                   9758:                 push(@homeservers,$chome);
                   9759:             }
                   9760:         }
1.521     raeburn  9761:     } else {
1.772     raeburn  9762:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9763:     }
1.793     albertel 9764:     foreach my $code (keys(%{$instcodes})) {
                   9765:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9766:     }
                   9767:     chop($courses);
1.772     raeburn  9768:     my $ok_response = 0;
                   9769:     my $response;
                   9770:     while (@homeservers > 0 && $ok_response == 0) {
                   9771:         my $server = shift(@homeservers); 
                   9772:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9773:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9774:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9775: 		split(/:/,$response);
1.772     raeburn  9776:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9777:             push(@{$codetitles},&str2array($codetitles_str));
                   9778:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9779:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9780:             $ok_response = 1;
                   9781:         }
                   9782:     }
                   9783:     if ($ok_response) {
1.521     raeburn  9784:         return 'ok';
1.772     raeburn  9785:     } else {
                   9786:         return $response;
1.521     raeburn  9787:     }
                   9788: }
                   9789: 
1.792     raeburn  9790: sub auto_instcode_defaults {
                   9791:     my ($domain,$returnhash,$code_order) = @_;
                   9792:     my @homeservers;
1.841     albertel 9793: 
                   9794:     my %servers = &get_servers($domain,'library');
                   9795:     foreach my $tryserver (keys(%servers)) {
                   9796: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9797: 	    push(@homeservers,$tryserver);
                   9798: 	}
1.792     raeburn  9799:     }
1.841     albertel 9800: 
1.792     raeburn  9801:     my $response;
1.841     albertel 9802:     foreach my $server (@homeservers) {
1.792     raeburn  9803:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9804:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9805: 	
                   9806: 	foreach my $pair (split(/\&/,$response)) {
                   9807: 	    my ($name,$value)=split(/\=/,$pair);
                   9808: 	    if ($name eq 'code_order') {
                   9809: 		@{$code_order} = split(/\&/,&unescape($value));
                   9810: 	    } else {
                   9811: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9812: 	    }
                   9813: 	}
                   9814: 	return 'ok';
1.792     raeburn  9815:     }
1.841     albertel 9816: 
                   9817:     return $response;
1.1003    raeburn  9818: }
                   9819: 
                   9820: sub auto_possible_instcodes {
1.1007    raeburn  9821:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9822:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9823:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9824:         return;
                   9825:     }
1.1003    raeburn  9826:     my (@homeservers,$uhome);
                   9827:     if (defined(&domain($domain,'primary'))) {
                   9828:         $uhome=&domain($domain,'primary');
                   9829:         push(@homeservers,&domain($domain,'primary'));
                   9830:     } else {
                   9831:         my %servers = &get_servers($domain,'library');
                   9832:         foreach my $tryserver (keys(%servers)) {
                   9833:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9834:                 push(@homeservers,$tryserver);
                   9835:             }
                   9836:         }
                   9837:     }
                   9838:     my $response;
                   9839:     foreach my $server (@homeservers) {
                   9840:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9841:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9842:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9843:             split(':',$response);
                   9844:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9845:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9846:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9847:             my ($name,$value)=split('=',$item);
                   9848:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9849:         }
                   9850:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9851:             my ($name,$value)=split('=',$item);
                   9852:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9853:         }
                   9854:         return 'ok';
                   9855:     }
                   9856:     return $response;
                   9857: }
1.792     raeburn  9858: 
1.1010    raeburn  9859: sub auto_courserequest_checks {
                   9860:     my ($dom) = @_;
1.1020    raeburn  9861:     my ($homeserver,%validations);
                   9862:     if ($dom =~ /^$match_domain$/) {
                   9863:         $homeserver = &domain($dom,'primary');
                   9864:     }
                   9865:     unless ($homeserver eq 'no_host') {
                   9866:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9867:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9868:             my @items = split(/&/,$response);
                   9869:             foreach my $item (@items) {
                   9870:                 my ($key,$value) = split('=',$item);
                   9871:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9872:             }
                   9873:         }
                   9874:     }
1.1010    raeburn  9875:     return %validations; 
                   9876: }
                   9877: 
1.1020    raeburn  9878: sub auto_courserequest_validation {
1.1172.2.43  raeburn  9879:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9880:     my ($homeserver,$response);
                   9881:     if ($dom =~ /^$match_domain$/) {
                   9882:         $homeserver = &domain($dom,'primary');
                   9883:     }
1.1172.2.43  raeburn  9884:     unless ($homeserver eq 'no_host') {
                   9885:         my $customdata;
                   9886:         if (ref($custominfo) eq 'HASH') {
                   9887:             $customdata = &freeze_escape($custominfo);
                   9888:         }
1.1020    raeburn  9889:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9890:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1172.2.43  raeburn  9891:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9892:                                     $customdata,$homeserver));
1.1020    raeburn  9893:     }
                   9894:     return $response;
                   9895: }
                   9896: 
1.777     albertel 9897: sub auto_validate_class_sec {
1.918     raeburn  9898:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9899:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9900:     my $ownerlist;
                   9901:     if (ref($owners) eq 'ARRAY') {
                   9902:         $ownerlist = join(',',@{$owners});
                   9903:     } else {
                   9904:         $ownerlist = $owners;
                   9905:     }
1.773     raeburn  9906:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9907:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9908:     return $response;
                   9909: }
                   9910: 
1.1172.2.141  raeburn  9911: sub auto_instsec_reformat {
                   9912:     my ($cdom,$action,$instsecref) = @_;
                   9913:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
                   9914:     my @homeservers;
                   9915:     if (defined(&domain($cdom,'primary'))) {
                   9916:         push(@homeservers,&domain($cdom,'primary'));
                   9917:     } else {
                   9918:         my %servers = &get_servers($cdom,'library');
                   9919:         foreach my $tryserver (keys(%servers)) {
                   9920:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9921:                 push(@homeservers,$tryserver);
                   9922:             }
                   9923:         }
                   9924:     }
                   9925:     my $response;
                   9926:     my %reformatted = %{$instsecref};
                   9927:     foreach my $server (@homeservers) {
                   9928:         if (ref($instsecref) eq 'HASH') {
                   9929:             my $info = &freeze_escape($instsecref);
                   9930:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
                   9931:                                 $action.':'.$info,$server);
                   9932:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
                   9933:             my @items = split(/&/,$response);
                   9934:             foreach my $item (@items) {
                   9935:                 my ($key,$value) = split(/=/,$item);
                   9936:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
                   9937:             }
                   9938:         }
                   9939:     }
                   9940:     return %reformatted;
                   9941: }
                   9942: 
1.1172.2.94  raeburn  9943: sub auto_validate_instclasses {
                   9944:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9945:     my ($homeserver,%validations);
                   9946:     $homeserver = &homeserver($cnum,$cdom);
                   9947:     unless ($homeserver eq 'no_host') {
                   9948:         my $ownerlist;
                   9949:         if (ref($owners) eq 'ARRAY') {
                   9950:             $ownerlist = join(',',@{$owners});
                   9951:         } else {
                   9952:             $ownerlist = $owners;
                   9953:         }
                   9954:         if (ref($classesref) eq 'HASH') {
                   9955:             my $classes = &freeze_escape($classesref);
                   9956:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9957:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9958:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9959:                 my @items = split(/&/,$response);
                   9960:                 foreach my $item (@items) {
                   9961:                     my ($key,$value) = split('=',$item);
                   9962:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9963:                 }
                   9964:             }
                   9965:         }
                   9966:     }
                   9967:     return %validations;
                   9968: }
                   9969: 
1.1172.2.38  raeburn  9970: sub auto_crsreq_update {
                   9971:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1172.2.45  raeburn  9972:         $code,$accessstart,$accessend,$inbound) = @_;
1.1172.2.38  raeburn  9973:     my ($homeserver,%crsreqresponse);
                   9974:     if ($cdom =~ /^$match_domain$/) {
                   9975:         $homeserver = &domain($cdom,'primary');
                   9976:     }
                   9977:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9978:         my $info;
                   9979:         if (ref($inbound) eq 'HASH') {
                   9980:             $info = &freeze_escape($inbound);
                   9981:         }
                   9982:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9983:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9984:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1172.2.45  raeburn  9985:                             &escape($title).':'.&escape($code).':'.
                   9986:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
1.1172.2.38  raeburn  9987:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9988:             my @items = split(/&/,$response);
                   9989:             foreach my $item (@items) {
                   9990:                 my ($key,$value) = split('=',$item);
                   9991:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9992:             }
                   9993:         }
                   9994:     }
                   9995:     return \%crsreqresponse;
                   9996: }
                   9997: 
1.1172.2.78  raeburn  9998: sub auto_export_grades {
                   9999:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   10000:     my ($homeserver,%exportresponse);
                   10001:     if ($cdom =~ /^$match_domain$/) {
                   10002:         $homeserver = &domain($cdom,'primary');
                   10003:     }
                   10004:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   10005:         my $info;
                   10006:         if (ref($inforef) eq 'HASH') {
                   10007:             $info = &freeze_escape($inforef);
                   10008:         }
                   10009:         if (ref($gradesref) eq 'HASH') {
                   10010:             my $grades = &freeze_escape($gradesref);
                   10011:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   10012:                                 $info.':'.$grades,$homeserver);
                   10013:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   10014:                 my @items = split(/&/,$response);
                   10015:                 foreach my $item (@items) {
                   10016:                     my ($key,$value) = split('=',$item);
                   10017:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   10018:                 }
                   10019:             }
                   10020:         }
                   10021:     }
                   10022:     return \%exportresponse;
                   10023: }
                   10024: 
1.1172.2.68  raeburn  10025: sub check_instcode_cloning {
                   10026:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   10027:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   10028:         return;
                   10029:     }
                   10030:     my $canclone;
                   10031:     if (@{$code_order} > 0) {
                   10032:         my $instcoderegexp ='^';
                   10033:         my @clonecodes = split(/\&/,$cloner);
                   10034:         foreach my $item (@{$code_order}) {
                   10035:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   10036:                 foreach my $pair (@clonecodes) {
                   10037:                     my ($key,$val) = split(/\=/,$pair,2);
                   10038:                     $val = &unescape($val);
                   10039:                     if ($key eq $item) {
                   10040:                         $instcoderegexp .= '('.$val.')';
                   10041:                         last;
                   10042:                     }
                   10043:                 }
                   10044:             } else {
                   10045:                 $instcoderegexp .= $codedefaults->{$item};
                   10046:             }
                   10047:         }
                   10048:         $instcoderegexp .= '$';
                   10049:         my (@from,@to);
                   10050:         eval {
                   10051:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   10052:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   10053:         };
                   10054:         if ((@from > 0) && (@to > 0)) {
                   10055:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   10056:             if (!@diffs) {
                   10057:                 $canclone = 1;
                   10058:             }
                   10059:         }
                   10060:     }
                   10061:     return $canclone;
                   10062: }
                   10063: 
                   10064: sub default_instcode_cloning {
                   10065:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   10066:     my (%codedefaults,@code_order,$canclone);
                   10067:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   10068:         %codedefaults = %{$codedefaultsref};
                   10069:         @code_order = @{$codeorderref};
                   10070:     } elsif ($clonedom) {
                   10071:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   10072:     }
                   10073:     if (($domdefclone) && (@code_order)) {
                   10074:         my @clonecodes = split(/\+/,$domdefclone);
                   10075:         my $instcoderegexp ='^';
                   10076:         foreach my $item (@code_order) {
                   10077:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   10078:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   10079:             } else {
                   10080:                 $instcoderegexp .= $codedefaults{$item};
                   10081:             }
                   10082:         }
                   10083:         $instcoderegexp .= '$';
                   10084:         my (@from,@to);
                   10085:         eval {
                   10086:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   10087:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   10088:         };
                   10089:         if ((@from > 0) && (@to > 0)) {
                   10090:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   10091:             if (!@diffs) {
                   10092:                 $canclone = 1;
                   10093:             }
                   10094:         }
                   10095:     }
                   10096:     return $canclone;
                   10097: }
                   10098: 
1.679     raeburn  10099: # ------------------------------------------------------- Course Group routines
                   10100: 
                   10101: sub get_coursegroups {
1.809     raeburn  10102:     my ($cdom,$cnum,$group,$namespace) = @_;
                   10103:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  10104: }
                   10105: 
1.679     raeburn  10106: sub modify_coursegroup {
                   10107:     my ($cdom,$cnum,$groupsettings) = @_;
                   10108:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   10109: }
                   10110: 
1.809     raeburn  10111: sub toggle_coursegroup_status {
                   10112:     my ($cdom,$cnum,$group,$action) = @_;
                   10113:     my ($from_namespace,$to_namespace);
                   10114:     if ($action eq 'delete') {
                   10115:         $from_namespace = 'coursegroups';
                   10116:         $to_namespace = 'deleted_groups';
                   10117:     } else {
                   10118:         $from_namespace = 'deleted_groups';
                   10119:         $to_namespace = 'coursegroups';
                   10120:     }
                   10121:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  10122:     if (my $tmp = &error(%curr_group)) {
                   10123:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   10124:         return ('read error',$tmp);
                   10125:     } else {
                   10126:         my %savedsettings = %curr_group; 
1.809     raeburn  10127:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  10128:         my $deloutcome;
                   10129:         if ($result eq 'ok') {
1.809     raeburn  10130:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  10131:         } else {
                   10132:             return ('write error',$result);
                   10133:         }
                   10134:         if ($deloutcome eq 'ok') {
                   10135:             return 'ok';
                   10136:         } else {
                   10137:             return ('delete error',$deloutcome);
                   10138:         }
                   10139:     }
                   10140: }
                   10141: 
1.679     raeburn  10142: sub modify_group_roles {
1.957     raeburn  10143:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  10144:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   10145:     my $role = 'gr/'.&escape($userprivs);
                   10146:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  10147:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  10148:     if ($result eq 'ok') {
                   10149:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   10150:     }
1.679     raeburn  10151:     return $result;
                   10152: }
                   10153: 
                   10154: sub modify_coursegroup_membership {
                   10155:     my ($cdom,$cnum,$membership) = @_;
                   10156:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   10157:     return $result;
                   10158: }
                   10159: 
1.682     raeburn  10160: sub get_active_groups {
                   10161:     my ($udom,$uname,$cdom,$cnum) = @_;
                   10162:     my $now = time;
                   10163:     my %groups = ();
                   10164:     foreach my $key (keys(%env)) {
1.811     albertel 10165:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  10166:             my ($start,$end) = split(/\./,$env{$key});
                   10167:             if (($end!=0) && ($end<$now)) { next; }
                   10168:             if (($start!=0) && ($start>$now)) { next; }
                   10169:             if ($1 eq $cdom && $2 eq $cnum) {
                   10170:                 $groups{$3} = $env{$key} ;
                   10171:             }
                   10172:         }
                   10173:     }
                   10174:     return %groups;
                   10175: }
                   10176: 
1.683     raeburn  10177: sub get_group_membership {
                   10178:     my ($cdom,$cnum,$group) = @_;
                   10179:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   10180: }
                   10181: 
                   10182: sub get_users_groups {
                   10183:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  10184:     my @usersgroups;
1.683     raeburn  10185:     my $cachetime=1800;
                   10186: 
                   10187:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  10188:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   10189:     if (defined($cached)) {
1.734     albertel 10190:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  10191:     } else {  
                   10192:         $grouplist = '';
1.816     raeburn  10193:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  10194:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  10195:         my $access_end = $env{'course.'.$courseid.
                   10196:                               '.default_enrollment_end_date'};
                   10197:         my $now = time;
                   10198:         foreach my $key (keys(%roleshash)) {
                   10199:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   10200:                 my $group = $1;
                   10201:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   10202:                     my $start = $2;
                   10203:                     my $end = $1;
                   10204:                     if ($start == -1) { next; } # deleted from group
                   10205:                     if (($start!=0) && ($start>$now)) { next; }
                   10206:                     if (($end!=0) && ($end<$now)) {
                   10207:                         if ($access_end && $access_end < $now) {
                   10208:                             if ($access_end - $end < 86400) {
                   10209:                                 push(@usersgroups,$group);
1.733     raeburn  10210:                             }
                   10211:                         }
1.817     raeburn  10212:                         next;
1.733     raeburn  10213:                     }
1.817     raeburn  10214:                     push(@usersgroups,$group);
1.683     raeburn  10215:                 }
                   10216:             }
                   10217:         }
1.817     raeburn  10218:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   10219:         $grouplist = join(':',@usersgroups);
                   10220:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  10221:     }
1.733     raeburn  10222:     return @usersgroups;
1.683     raeburn  10223: }
                   10224: 
                   10225: sub devalidate_getgroups_cache {
                   10226:     my ($udom,$uname,$cdom,$cnum)=@_;
                   10227:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 10228: 
1.683     raeburn  10229:     my $hashid="$udom:$uname:$courseid";
                   10230:     &devalidate_cache_new('getgroups',$hashid);
                   10231: }
                   10232: 
1.12      www      10233: # ------------------------------------------------------------------ Plain Text
                   10234: 
                   10235: sub plaintext {
1.988     raeburn  10236:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  10237:     if ($short =~ m{^cr/}) {
1.758     albertel 10238: 	return (split('/',$short))[-1];
                   10239:     }
1.742     raeburn  10240:     if (!defined($cid)) {
                   10241:         $cid = $env{'request.course.id'};
                   10242:     }
                   10243:     my %rolenames = (
1.1008    raeburn  10244:                       Course    => 'std',
                   10245:                       Community => 'alt1',
1.742     raeburn  10246:                     );
1.1037    raeburn  10247:     if ($cid ne '') {
                   10248:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   10249:             unless ($forcedefault) {
                   10250:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   10251:                 &Apache::lonlocal::mt_escape(\$roletext);
                   10252:                 return &Apache::lonlocal::mt($roletext);
                   10253:             }
                   10254:         }
                   10255:     }
                   10256:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   10257:         (defined($rolenames{$type})) && 
                   10258:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  10259:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  10260:     } elsif ($cid ne '') {
                   10261:         my $crstype = $env{'course.'.$cid.'.type'};
                   10262:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   10263:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   10264:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   10265:         }
1.742     raeburn  10266:     }
1.1037    raeburn  10267:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      10268: }
                   10269: 
                   10270: # ----------------------------------------------------------------- Assign Role
                   10271: 
                   10272: sub assignrole {
1.957     raeburn  10273:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   10274:         $context)=@_;
1.21      www      10275:     my $mrole;
                   10276:     if ($role =~ /^cr\//) {
1.393     www      10277:         my $cwosec=$url;
1.811     albertel 10278:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      10279: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  10280:            my $refused = 1;
                   10281:            if ($context eq 'requestcourses') {
                   10282:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   10283:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   10284:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   10285:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10286:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10287:                            if ($crsenv{'internal.courseowner'} eq
                   10288:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   10289:                                $refused = '';
                   10290:                            }
                   10291:                        }
                   10292:                    }
                   10293:                }
                   10294:            }
                   10295:            if ($refused) {
                   10296:                &logthis('Refused custom assignrole: '.
                   10297:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   10298:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   10299:                return 'refused';
                   10300:            }
1.104     www      10301:         }
1.21      www      10302:         $mrole='cr';
1.678     raeburn  10303:     } elsif ($role =~ /^gr\//) {
                   10304:         my $cwogrp=$url;
1.811     albertel 10305:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  10306:         unless (&allowed('mdg',$cwogrp)) {
                   10307:             &logthis('Refused group assignrole: '.
                   10308:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   10309:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   10310:             return 'refused';
                   10311:         }
                   10312:         $mrole='gr';
1.21      www      10313:     } else {
1.82      www      10314:         my $cwosec=$url;
1.811     albertel 10315:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  10316:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   10317:             my $refused;
                   10318:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   10319:                 if (!(&allowed('c'.$role,$url))) {
                   10320:                     $refused = 1;
                   10321:                 }
                   10322:             } else {
                   10323:                 $refused = 1;
                   10324:             }
1.947     raeburn  10325:             if ($refused) {
1.1045    raeburn  10326:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10327:                 if (!$selfenroll && $context eq 'course') {
                   10328:                     my %crsenv;
                   10329:                     if ($role eq 'cc' || $role eq 'co') {
                   10330:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10331:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   10332:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   10333:                                 if ($crsenv{'internal.courseowner'} eq 
                   10334:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10335:                                     $refused = '';
                   10336:                                 }
                   10337:                             }
                   10338:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   10339:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   10340:                                 if ($crsenv{'internal.courseowner'} eq 
                   10341:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10342:                                     $refused = '';
                   10343:                                 }
                   10344:                             }
                   10345:                         }
                   10346:                     }
1.1172.2.146.  .13(raeb 10347:-23):                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   10348:-23):                     if ($role eq 'st') {
                   10349:-23):                         $refused = '';
                   10350:-23):                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
                   10351:-23):                         $refused = '';
                   10352:-23):                     }
1.1017    raeburn  10353:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  10354:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  10355:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  10356:                         my $wrongcc;
                   10357:                         if ($cnum =~ /^$match_community$/) {
                   10358:                             $wrongcc = 1 if ($role eq 'cc');
                   10359:                         } else {
                   10360:                             $wrongcc = 1 if ($role eq 'co');
                   10361:                         }
                   10362:                         unless ($wrongcc) {
                   10363:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10364:                             if ($crsenv{'internal.courseowner'} eq 
                   10365:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   10366:                                 $refused = '';
                   10367:                             }
1.1017    raeburn  10368:                         }
                   10369:                     }
1.1172.2.9  raeburn  10370:                 } elsif ($context eq 'requestauthor') {
                   10371:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   10372:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   10373:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   10374:                             $refused = '';
                   10375:                         } else {
                   10376:                             my %domdefaults = &get_domain_defaults($udom);
                   10377:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   10378:                                 my $checkbystatus;
                   10379:                                 if ($env{'user.adv'}) {
                   10380:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   10381:                                     if ($disposition eq 'automatic') {
                   10382:                                         $refused = '';
                   10383:                                     } elsif ($disposition eq '') {
                   10384:                                         $checkbystatus = 1;
                   10385:                                     }
                   10386:                                 } else {
                   10387:                                     $checkbystatus = 1;
                   10388:                                 }
                   10389:                                 if ($checkbystatus) {
                   10390:                                     if ($env{'environment.inststatus'}) {
                   10391:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   10392:                                         foreach my $type (@inststatuses) {
                   10393:                                             if (($type ne '') &&
                   10394:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   10395:                                                 $refused = '';
                   10396:                                             }
                   10397:                                         }
                   10398:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   10399:                                         $refused = '';
                   10400:                                     }
                   10401:                                 }
                   10402:                             }
                   10403:                         }
                   10404:                     }
1.1017    raeburn  10405:                 }
                   10406:                 if ($refused) {
1.947     raeburn  10407:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   10408:                              ' '.$role.' '.$end.' '.$start.' by '.
                   10409: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   10410:                     return 'refused';
                   10411:                 }
1.932     raeburn  10412:             }
1.1131    raeburn  10413:         } elsif ($role eq 'au') {
                   10414:             if ($url ne '/'.$udom.'/') {
                   10415:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   10416:                          ' to assign author role for '.$uname.':'.$udom.
                   10417:                          ' in domain: '.$url.' refused (wrong domain).');
                   10418:                 return 'refused';
                   10419:             }
1.104     www      10420:         }
1.21      www      10421:         $mrole=$role;
                   10422:     }
1.620     albertel 10423:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      10424:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      10425:     if ($end) { $command.='_'.$end; }
1.21      www      10426:     if ($start) {
                   10427: 	if ($end) { 
1.81      www      10428:            $command.='_'.$start; 
1.21      www      10429:         } else {
1.81      www      10430:            $command.='_0_'.$start;
1.21      www      10431:         }
                   10432:     }
1.739     raeburn  10433:     my $origstart = $start;
                   10434:     my $origend = $end;
1.957     raeburn  10435:     my $delflag;
1.357     www      10436: # actually delete
                   10437:     if ($deleteflag) {
1.373     www      10438: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      10439: # modify command to delete the role
1.620     albertel 10440:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      10441:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 10442: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      10443: # set start and finish to negative values for userrolelog
                   10444:            $start=-1;
                   10445:            $end=-1;
1.957     raeburn  10446:            $delflag = 1;
1.357     www      10447:         }
                   10448:     }
                   10449: # send command
1.349     www      10450:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      10451: # log new user role if status is ok
1.349     www      10452:     if ($answer eq 'ok') {
1.663     raeburn  10453: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1172.2.9  raeburn  10454:         if (($role eq 'cc') || ($role eq 'in') ||
                   10455:             ($role eq 'ep') || ($role eq 'ad') ||
                   10456:             ($role eq 'ta') || ($role eq 'st') ||
                   10457:             ($role=~/^cr/) || ($role eq 'gr') ||
                   10458:             ($role eq 'co')) {
1.1172.2.13  raeburn  10459: # for course roles, perform group memberships changes triggered by role change.
                   10460:             unless ($role =~ /^gr/) {
                   10461:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   10462:                                                  $origstart,$selfenroll,$context);
                   10463:             }
1.1172.2.9  raeburn  10464:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10465:                            $selfenroll,$context);
                   10466:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1172.2.90  raeburn  10467:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   10468:                  ($role eq 'da')) {
1.1172.2.9  raeburn  10469:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10470:                            $context);
                   10471:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   10472:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10473:                              $context);
                   10474:         }
1.1053    raeburn  10475:         if ($role eq 'cc') {
                   10476:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   10477:         }
1.349     www      10478:     }
                   10479:     return $answer;
1.169     harris41 10480: }
                   10481: 
1.1053    raeburn  10482: sub autoupdate_coowners {
                   10483:     my ($url,$end,$start,$uname,$udom) = @_;
                   10484:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   10485:     if (($cdom ne '') && ($cnum ne '')) {
                   10486:         my $now = time;
                   10487:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   10488:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   10489:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   10490:             my $instcode = $coursehash{'internal.coursecode'};
1.1172.2.141  raeburn  10491:             my $xlists = $coursehash{'internal.crosslistings'};
1.1053    raeburn  10492:             if ($instcode ne '') {
1.1056    raeburn  10493:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   10494:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  10495:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  10496:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1172.2.141  raeburn  10497:                         unless ($result eq 'valid') {
                   10498:                             if ($xlists ne '') {
                   10499:                                 foreach my $xlist (split(',',$xlists)) {
                   10500:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
                   10501:                                     $result =
                   10502:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
                   10503:                                                                       $inst_crosslist,$uname.':'.$udom);
                   10504:                                     last if ($result eq 'valid');
                   10505:                                 }
                   10506:                             }
                   10507:                         }
1.1056    raeburn  10508:                         if ($result eq 'valid') {
                   10509:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  10510:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10511:                                     push(@newcoowners,$coowner);
                   10512:                                 }
                   10513:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   10514:                                     push(@newcoowners,$uname.':'.$udom);
                   10515:                                 }
                   10516:                                 @newcoowners = sort(@newcoowners);
                   10517:                             } else {
                   10518:                                 push(@newcoowners,$uname.':'.$udom);
                   10519:                             }
1.1172.2.141  raeburn  10520:                         } elsif ($coursehash{'internal.co-owners'}) {
                   10521:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10522:                                 unless ($coowner eq $uname.':'.$udom) {
                   10523:                                     push(@newcoowners,$coowner);
1.1053    raeburn  10524:                                 }
                   10525:                             }
1.1172.2.141  raeburn  10526:                             unless (@newcoowners > 0) {
                   10527:                                 $delcoowners = 1;
                   10528:                                 $coowners = '';
                   10529:                             }
1.1053    raeburn  10530:                         }
                   10531:                         if (@newcoowners || $delcoowners) {
                   10532:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   10533:                                             $delcoowners,@newcoowners);
                   10534:                         }
                   10535:                     }
                   10536:                 }
                   10537:             }
                   10538:         }
                   10539:     }
                   10540: }
                   10541: 
                   10542: sub store_coowners {
                   10543:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   10544:     my $cid = $cdom.'_'.$cnum;
                   10545:     my ($coowners,$delresult,$putresult);
                   10546:     if (@newcoowners) {
                   10547:         $coowners = join(',',@newcoowners);
                   10548:         my %coownershash = (
                   10549:                             'internal.co-owners' => $coowners,
                   10550:                            );
                   10551:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   10552:         if ($putresult eq 'ok') {
                   10553:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   10554:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   10555:             }
                   10556:         }
                   10557:     }
                   10558:     if ($delcoowners) {
                   10559:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   10560:         if ($delresult eq 'ok') {
                   10561:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   10562:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   10563:             }
                   10564:         }
                   10565:     }
                   10566:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   10567:         my %crsinfo =
                   10568:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   10569:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   10570:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   10571:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   10572:         }
                   10573:     }
                   10574: }
                   10575: 
1.169     harris41 10576: # -------------------------------------------------- Modify user authentication
1.197     www      10577: # Overrides without validation
                   10578: 
1.169     harris41 10579: sub modifyuserauth {
                   10580:     my ($udom,$uname,$umode,$upass)=@_;
                   10581:     my $uhome=&homeserver($uname,$udom);
1.1172.2.115  raeburn  10582:     my $allowed;
                   10583:     if (&allowed('mau',$udom)) {
                   10584:         $allowed = 1;
                   10585:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   10586:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   10587:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   10588:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10589:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10590:         if (($cdom ne '') && ($cnum ne '')) {
                   10591:             my $is_owner = &is_course_owner($cdom,$cnum);
                   10592:             if ($is_owner) {
                   10593:                 $allowed = 1;
                   10594:             }
                   10595:         }
                   10596:     }
                   10597:     unless ($allowed) { return 'refused'; }
1.197     www      10598:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 10599:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10600:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 10601:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10602: 		     &escape($upass),$uhome);
1.1172.2.134  raeburn  10603:     my $ip = &get_requestor_ip();
1.620     albertel 10604:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10605:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1172.2.134  raeburn  10606:          '(Remote '.$ip.'): '.$reply);
1.197     www      10607:     &log($udom,,$uname,$uhome,
1.620     albertel 10608:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10609:                                      $env{'user.name'}.', '.$umode.
1.1172.2.134  raeburn  10610:          '(Remote '.$ip.'): '.$reply);
1.169     harris41 10611:     unless ($reply eq 'ok') {
1.197     www      10612:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10613: 	return 'error: '.$reply;
                   10614:     }   
1.170     harris41 10615:     return 'ok';
1.80      www      10616: }
                   10617: 
1.81      www      10618: # --------------------------------------------------------------- Modify a user
1.80      www      10619: 
1.81      www      10620: sub modifyuser {
1.206     matthew  10621:     my ($udom,    $uname, $uid,
                   10622:         $umode,   $upass, $first,
                   10623:         $middle,  $last,  $gene,
1.1058    raeburn  10624:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10625:     $udom= &LONCAPA::clean_domain($udom);
                   10626:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10627:     my $showcandelete = 'none';
                   10628:     if (ref($candelete) eq 'ARRAY') {
                   10629:         if (@{$candelete} > 0) {
                   10630:             $showcandelete = join(', ',@{$candelete});
                   10631:         }
                   10632:     }
1.81      www      10633:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10634:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10635: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10636:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10637:                                      ' desiredhome not specified'). 
1.620     albertel 10638:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10639:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10640:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10641:     my $newuser;
                   10642:     if ($uhome eq 'no_host') {
                   10643:         $newuser = 1;
1.1172.2.146.  .13(raeb 10644:-23):         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   10645:-23):                 ($umode eq 'lti')) {
                   10646:-23):             return 'error: more information needed to create new user';
                   10647:-23):         }
1.1075    raeburn  10648:     }
1.80      www      10649: # ----------------------------------------------------------------- Create User
1.406     albertel 10650:     if (($uhome eq 'no_host') && 
1.1172.2.146.  .13(raeb 10651:-23): 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      10652:         my $unhome='';
1.844     albertel 10653:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10654:             $unhome = $desiredhome;
1.620     albertel 10655: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10656: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10657:         } else { # load balancing routine for determining $unhome
1.81      www      10658:             my $loadm=10000000;
1.841     albertel 10659: 	    my %servers = &get_servers($udom,'library');
                   10660: 	    foreach my $tryserver (keys(%servers)) {
                   10661: 		my $answer=reply('load',$tryserver);
                   10662: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10663: 		    $loadm=$answer;
                   10664: 		    $unhome=$tryserver;
                   10665: 		}
1.80      www      10666: 	    }
                   10667:         }
                   10668:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10669: 	    return 'error: unable to find a home server for '.$uname.
                   10670:                    ' in domain '.$udom;
1.80      www      10671:         }
                   10672:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10673:                          &escape($upass),$unhome);
                   10674: 	unless ($reply eq 'ok') {
                   10675:             return 'error: '.$reply;
                   10676:         }   
1.230     stredwic 10677:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10678:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10679: 	    return 'error: unable verify users home machine.';
1.80      www      10680:         }
1.209     matthew  10681:     }   # End of creation of new user
1.80      www      10682: # ---------------------------------------------------------------------- Add ID
                   10683:     if ($uid) {
                   10684:        $uid=~tr/A-Z/a-z/;
                   10685:        my %uidhash=&idrget($udom,$uname);
1.196     www      10686:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10687:          && (!$forceid)) {
1.80      www      10688: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10689: 	      return 'error: user id "'.$uid.'" does not match '.
                   10690:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10691:           }
                   10692:        } else {
                   10693: 	  &idput($udom,($uname => $uid));
                   10694:        }
                   10695:     }
                   10696: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10697:     my @tmp=&get('environment',
1.899     raeburn  10698: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10699:                     'permanentemail','inststatus'],
1.134     albertel 10700: 		   $udom,$uname);
1.1075    raeburn  10701:     my (%names,%oldnames);
1.313     matthew  10702:     if ($tmp[0] =~ m/^error:.*/) { 
                   10703:         %names=(); 
                   10704:     } else {
                   10705:         %names = @tmp;
1.1075    raeburn  10706:         %oldnames = %names;
1.313     matthew  10707:     }
1.388     www      10708: #
1.1058    raeburn  10709: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10710: # of users did not contain them), do not overwrite existing values
                   10711: # unless field is in $candelete array ref.  
                   10712: #
                   10713: 
                   10714:     my @fields = ('firstname','middlename','lastname','generation',
                   10715:                   'permanentemail','id');
                   10716:     my %newvalues;
                   10717:     if (ref($candelete) eq 'ARRAY') {
                   10718:         foreach my $field (@fields) {
                   10719:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10720:                 if ($field eq 'firstname') {
                   10721:                     $names{$field} = $first;
                   10722:                 } elsif ($field eq 'middlename') {
                   10723:                     $names{$field} = $middle;
                   10724:                 } elsif ($field eq 'lastname') {
                   10725:                     $names{$field} = $last;
                   10726:                 } elsif ($field eq 'generation') { 
                   10727:                     $names{$field} = $gene;
                   10728:                 } elsif ($field eq 'permanentemail') {
                   10729:                     $names{$field} = $email;
                   10730:                 } elsif ($field eq 'id') {
                   10731:                     $names{$field}  = $uid;
                   10732:                 }
                   10733:             }
                   10734:         }
                   10735:     }
1.388     www      10736:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10737:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10738:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10739:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10740:     if ($email) {
                   10741:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10742:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10743:     }
1.899     raeburn  10744:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10745:     if (defined($inststatus)) {
                   10746:         $names{'inststatus'} = '';
                   10747:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10748:         if (ref($usertypes) eq 'HASH') {
                   10749:             my @okstatuses; 
                   10750:             foreach my $item (split(/:/,$inststatus)) {
                   10751:                 if (defined($usertypes->{$item})) {
                   10752:                     push(@okstatuses,$item);  
                   10753:                 }
                   10754:             }
                   10755:             if (@okstatuses) {
                   10756:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10757:             }
                   10758:         }
                   10759:     }
1.1075    raeburn  10760:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10761:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10762:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10763:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10764:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10765:     } else {
                   10766:         $logmsg .= ' during self creation';
                   10767:     }
1.1075    raeburn  10768:     my $changed;
                   10769:     if ($newuser) {
                   10770:         $changed = 1;
                   10771:     } else {
                   10772:         foreach my $field (@fields) {
                   10773:             if ($names{$field} ne $oldnames{$field}) {
                   10774:                 $changed = 1;
                   10775:                 last;
                   10776:             }
                   10777:         }
                   10778:     }
                   10779:     unless ($changed) {
                   10780:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10781:         &logthis($logmsg);
                   10782:         return 'ok';
                   10783:     }
                   10784:     my $reply = &put('environment', \%names, $udom,$uname);
                   10785:     if ($reply ne 'ok') { 
                   10786:         return 'error: '.$reply;
                   10787:     }
1.1087    raeburn  10788:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10789:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10790:     }
1.1075    raeburn  10791:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10792:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10793:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10794:     &logthis($logmsg);
1.134     albertel 10795:     return 'ok';
1.80      www      10796: }
                   10797: 
1.81      www      10798: # -------------------------------------------------------------- Modify student
1.80      www      10799: 
1.81      www      10800: sub modifystudent {
                   10801:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10802:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1172.2.76  raeburn  10803:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10804:     if (!$cid) {
1.620     albertel 10805: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10806: 	    return 'not_in_class';
                   10807: 	}
1.80      www      10808:     }
                   10809: # --------------------------------------------------------------- Make the user
1.81      www      10810:     my $reply=&modifyuser
1.209     matthew  10811: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10812:          $desiredhome,$email,$inststatus);
1.80      www      10813:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10814:     # This will cause &modify_student_enrollment to get the uid from the
1.1172.2.31  raeburn  10815:     # student's environment
1.297     matthew  10816:     $uid = undef if (!$forceid);
1.455     albertel 10817:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1172.2.19  raeburn  10818: 					$gene,$usec,$end,$start,$type,$locktype,
1.1172.2.76  raeburn  10819:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10820:     return $reply;
                   10821: }
                   10822: 
                   10823: sub modify_student_enrollment {
1.1172.2.23  raeburn  10824:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1172.2.76  raeburn  10825:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10826:     my ($cdom,$cnum,$chome);
                   10827:     if (!$cid) {
1.620     albertel 10828: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10829: 	    return 'not_in_class';
                   10830: 	}
1.620     albertel 10831: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10832: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10833:     } else {
                   10834: 	($cdom,$cnum)=split(/_/,$cid);
                   10835:     }
1.620     albertel 10836:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10837:     if (!$chome) {
1.457     raeburn  10838: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10839:     }
1.455     albertel 10840:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10841:     # Make sure the user exists
1.81      www      10842:     my $uhome=&homeserver($uname,$udom);
                   10843:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10844: 	return 'error: no such user';
                   10845:     }
1.297     matthew  10846:     # Get student data if we were not given enough information
                   10847:     if (!defined($first)  || $first  eq '' || 
                   10848:         !defined($last)   || $last   eq '' || 
                   10849:         !defined($uid)    || $uid    eq '' || 
                   10850:         !defined($middle) || $middle eq '' || 
                   10851:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10852:         # They did not supply us with enough data to enroll the student, so
                   10853:         # we need to pick up more information.
1.297     matthew  10854:         my %tmp = &get('environment',
1.294     matthew  10855:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10856:                        ,$udom,$uname);
                   10857: 
1.800     albertel 10858:         #foreach my $key (keys(%tmp)) {
                   10859:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10860:         #}
1.294     matthew  10861:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10862:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10863:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10864:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10865:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10866:     }
1.556     albertel 10867:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10868:     my $user = "$uname:$udom";
                   10869:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10870:     my $reply=cput('classlist',
1.1148    raeburn  10871: 		   {$user => 
1.1172.2.76  raeburn  10872: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10873: 		   $cdom,$cnum);
1.1148    raeburn  10874:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10875:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10876:     } else { 
1.81      www      10877: 	return 'error: '.$reply;
                   10878:     }
1.297     matthew  10879:     # Add student role to user
1.83      www      10880:     my $uurl='/'.$cid;
1.81      www      10881:     $uurl=~s/\_/\//g;
                   10882:     if ($usec) {
                   10883: 	$uurl.='/'.$usec;
                   10884:     }
1.1148    raeburn  10885:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10886:                              $selfenroll,$context);
                   10887:     if ($result ne 'ok') {
                   10888:         if ($old_entry{$user} ne '') {
                   10889:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10890:         } else {
                   10891:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10892:         }
                   10893:     }
                   10894:     return $result; 
1.21      www      10895: }
                   10896: 
1.556     albertel 10897: sub format_name {
                   10898:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10899:     my $name;
                   10900:     if ($first ne 'lastname') {
                   10901: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10902:     } else {
                   10903: 	if ($lastname=~/\S/) {
                   10904: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10905: 	    $name=~s/\s+,/,/;
                   10906: 	} else {
                   10907: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10908: 	}
                   10909:     }
                   10910:     $name=~s/^\s+//;
                   10911:     $name=~s/\s+$//;
                   10912:     $name=~s/\s+/ /g;
                   10913:     return $name;
                   10914: }
                   10915: 
1.84      www      10916: # ------------------------------------------------- Write to course preferences
                   10917: 
                   10918: sub writecoursepref {
                   10919:     my ($courseid,%prefs)=@_;
                   10920:     $courseid=~s/^\///;
                   10921:     $courseid=~s/\_/\//g;
                   10922:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10923:     my $chome=homeserver($cnum,$cdomain);
                   10924:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10925: 	return 'error: no such course';
                   10926:     }
                   10927:     my $cstring='';
1.800     albertel 10928:     foreach my $pref (keys(%prefs)) {
                   10929: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10930:     }
1.84      www      10931:     $cstring=~s/\&$//;
                   10932:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10933: }
                   10934: 
                   10935: # ---------------------------------------------------------- Make/modify course
                   10936: 
                   10937: sub createcourse {
1.741     raeburn  10938:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1172.2.146.  .1(raebu 10939:22):         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      10940:     $url=&declutter($url);
                   10941:     my $cid='';
1.1028    raeburn  10942:     if ($context eq 'requestcourses') {
                   10943:         my $can_create = 0;
                   10944:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10945:         if ($udom eq $ownerdom) {
1.1172.2.146.  .1(raebu 10946:22):             my $reload;
                   10947:22):             if (($callercontext eq 'auto') &&
                   10948:22):                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   10949:22):                 $reload = 'reload';
                   10950:22):             }
                   10951:22):             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  10952:                                   $context)) {
                   10953:                 $can_create = 1;
                   10954:             }
                   10955:         } else {
                   10956:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10957:                                            $category);
                   10958:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10959:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10960:                 if (@curr > 0) {
                   10961:                     my @options = qw(approval validate autolimit);
                   10962:                     my $optregex = join('|',@options);
                   10963:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10964:                         $can_create = 1;
                   10965:                     }
                   10966:                 }
                   10967:             }
                   10968:         }
                   10969:         if ($can_create) {
                   10970:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10971:                 unless (&allowed('ccc',$udom)) {
                   10972:                     return 'refused'; 
                   10973:                 }
1.1017    raeburn  10974:             }
                   10975:         } else {
                   10976:             return 'refused';
                   10977:         }
1.1028    raeburn  10978:     } elsif (!&allowed('ccc',$udom)) {
                   10979:         return 'refused';
1.84      www      10980:     }
1.1011    raeburn  10981: # --------------------------------------------------------------- Get Unique ID
                   10982:     my $uname;
                   10983:     if ($cnum =~ /^$match_courseid$/) {
                   10984:         my $chome=&homeserver($cnum,$udom,'true');
                   10985:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10986:             $uname = $cnum;
                   10987:         } else {
1.1038    raeburn  10988:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10989:         }
                   10990:     } else {
1.1038    raeburn  10991:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10992:     }
                   10993:     return $uname if ($uname =~ /^error/);
                   10994: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10995:     if (!defined($course_server)) {
                   10996:         if (defined(&domain($udom,'primary'))) {
                   10997:             $course_server = &domain($udom,'primary');
                   10998:         } else {
                   10999:             $course_server = $env{'user.home'}; 
                   11000:         }
                   11001:     }
                   11002:     my %host_servers =
                   11003:         &Apache::lonnet::get_servers($udom,'library');
                   11004:     unless ($host_servers{$course_server}) {
                   11005:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  11006:     }
1.84      www      11007: # ------------------------------------------------------------- Make the course
                   11008:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  11009:                       $course_server);
1.84      www      11010:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  11011:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      11012:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   11013: 	return 'error: no such course';
                   11014:     }
1.271     www      11015: # ----------------------------------------------------------------- Course made
1.516     raeburn  11016: # log existence
1.1029    raeburn  11017:     my $now = time;
1.918     raeburn  11018:     my $newcourse = {
                   11019:                     $udom.'_'.$uname => {
1.921     raeburn  11020:                                      description => $description,
                   11021:                                      inst_code   => $inst_code,
                   11022:                                      owner       => $course_owner,
                   11023:                                      type        => $crstype,
1.1029    raeburn  11024:                                      creator     => $env{'user.name'}.':'.
                   11025:                                                     $env{'user.domain'},
                   11026:                                      created     => $now,
                   11027:                                      context     => $context,
1.918     raeburn  11028:                                                 },
                   11029:                     };
1.921     raeburn  11030:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      11031: # set toplevel url
1.271     www      11032:     my $topurl=$url;
                   11033:     unless ($nonstandard) {
                   11034: # ------------------------------------------ For standard courses, make top url
                   11035:         my $mapurl=&clutter($url);
1.278     www      11036:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 11037:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      11038: <map>
                   11039: <resource id="1" type="start"></resource>
                   11040: <resource id="2" src="$mapurl"></resource>
                   11041: <resource id="3" type="finish"></resource>
                   11042: <link index="1" from="1" to="2"></link>
                   11043: <link index="2" from="2" to="3"></link>
                   11044: </map>
                   11045: ENDINITMAP
                   11046:         $topurl=&declutter(
1.638     albertel 11047:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      11048:                           );
                   11049:     }
                   11050: # ----------------------------------------------------------- Write preferences
1.84      www      11051:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  11052:                      ('description'              => $description,
                   11053:                       'url'                      => $topurl,
                   11054:                       'internal.creator'         => $env{'user.name'}.':'.
                   11055:                                                     $env{'user.domain'},
                   11056:                       'internal.created'         => $now,
                   11057:                       'internal.creationcontext' => $context)
                   11058:                     );
1.84      www      11059:     return '/'.$udom.'/'.$uname;
                   11060: }
                   11061: 
1.1011    raeburn  11062: # ------------------------------------------------------------------- Create ID
                   11063: sub generate_coursenum {
1.1038    raeburn  11064:     my ($udom,$crstype) = @_;
1.1011    raeburn  11065:     my $domdesc = &domain($udom);
                   11066:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  11067:     my $first;
                   11068:     if ($crstype eq 'Community') {
                   11069:         $first = '0';
                   11070:     } else {
                   11071:         $first = int(1+rand(9)); 
                   11072:     } 
                   11073:     my $uname=$first.
1.1011    raeburn  11074:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   11075:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   11076:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   11077: # ----------------------------------------------- Make sure that does not exist
                   11078:     my $uhome=&homeserver($uname,$udom,'true');
                   11079:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  11080:         if ($crstype eq 'Community') {
                   11081:             $first = '0';
                   11082:         } else {
                   11083:             $first = int(1+rand(9));
                   11084:         }
                   11085:         $uname=$first.
1.1011    raeburn  11086:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   11087:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   11088:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   11089:         $uhome=&homeserver($uname,$udom,'true');
                   11090:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   11091:             return 'error: unable to generate unique course-ID';
                   11092:         }
                   11093:     }
                   11094:     return $uname;
                   11095: }
                   11096: 
1.813     albertel 11097: sub is_course {
1.1167    droeschl 11098:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   11099:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
1.1172.2.95  raeburn  11100:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   11101:     my $uhome=&homeserver($cnum,$cdom);
                   11102:     my $iscourse;
                   11103:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   11104:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
                   11105:     } else {
                   11106:         my $hashid = $cdom.':'.$cnum;
                   11107:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   11108:         unless (defined($cached)) {
                   11109:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   11110:                                         $cnum,undef,undef,'.');
                   11111:             $iscourse = 0;
                   11112:             if (exists($courses{$cdom.'_'.$cnum})) {
                   11113:                 $iscourse = 1;
                   11114:             }
                   11115:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   11116:         }
                   11117:     }
                   11118:     return unless($iscourse);
1.1167    droeschl 11119:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 11120: }
                   11121: 
1.1015    raeburn  11122: sub store_userdata {
                   11123:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  11124:     my $result;
1.1016    raeburn  11125:     if ($datakey ne '') {
1.1013    raeburn  11126:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  11127:             if ($udom eq '' || $uname eq '') {
                   11128:                 $udom = $env{'user.domain'};
                   11129:                 $uname = $env{'user.name'};
                   11130:             }
                   11131:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  11132:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   11133:                 $result = 'error: no_host';
                   11134:             } else {
1.1172.2.138  raeburn  11135:                 $storehash->{'ip'} = &get_requestor_ip();
1.1013    raeburn  11136:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   11137: 
                   11138:                 my $namevalue='';
                   11139:                 foreach my $key (keys(%{$storehash})) {
                   11140:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   11141:                 }
                   11142:                 $namevalue=~s/\&$//;
1.1172.2.26  raeburn  11143:                 unless ($namespace eq 'courserequests') {
                   11144:                     $datakey = &escape($datakey);
                   11145:                 }
1.1105    raeburn  11146:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   11147:                                   $namevalue,$uhome);
1.1013    raeburn  11148:             }
                   11149:         } else {
                   11150:             $result = 'error: data to store was not a hash reference'; 
                   11151:         }
                   11152:     } else {
                   11153:         $result= 'error: invalid requestkey'; 
                   11154:     }
                   11155:     return $result;
                   11156: }
                   11157: 
1.21      www      11158: # ---------------------------------------------------------- Assign Custom Role
                   11159: 
                   11160: sub assigncustomrole {
1.957     raeburn  11161:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11162:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  11163:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      11164: }
                   11165: 
                   11166: # ----------------------------------------------------------------- Revoke Role
                   11167: 
                   11168: sub revokerole {
1.957     raeburn  11169:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11170:     my $now=time;
1.965     raeburn  11171:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      11172: }
                   11173: 
                   11174: # ---------------------------------------------------------- Revoke Custom Role
                   11175: 
                   11176: sub revokecustomrole {
1.957     raeburn  11177:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11178:     my $now=time;
1.357     www      11179:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  11180:            $deleteflag,$selfenroll,$context);
1.17      www      11181: }
                   11182: 
1.533     banghart 11183: # ------------------------------------------------------------ Disk usage
1.535     albertel 11184: sub diskusage {
1.955     raeburn  11185:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   11186:     $directorypath =~ s/\/$//;
                   11187:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   11188:                        .&escape($getpropath).':'.&escape($uname).':'
                   11189:                        .&escape($udom),homeserver($uname,$udom));
                   11190:     if ($listing eq 'unknown_cmd') {
                   11191:         if ($getpropath) {
                   11192:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   11193:         }
                   11194:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   11195:     }
1.514     albertel 11196:     return $listing;
1.512     banghart 11197: }
                   11198: 
1.566     banghart 11199: sub is_locked {
1.1096    raeburn  11200:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 11201:     my @check;
                   11202:     my $is_locked;
1.1093    raeburn  11203:     push (@check,$file_name);
1.613     albertel 11204:     my %locked = &get('file_permissions',\@check,
1.620     albertel 11205: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 11206:     my ($tmp)=keys(%locked);
                   11207:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  11208:     
1.566     banghart 11209:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  11210:         $is_locked = 'false';
                   11211:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  11212:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  11213:                $is_locked = 'true';
1.1096    raeburn  11214:                if (ref($which) eq 'ARRAY') {
                   11215:                    push(@{$which},$entry);
                   11216:                } else {
                   11217:                    last;
                   11218:                }
1.745     raeburn  11219:            }
                   11220:        }
1.566     banghart 11221:     } else {
                   11222:         $is_locked = 'false';
                   11223:     }
1.1093    raeburn  11224:     return $is_locked;
1.566     banghart 11225: }
                   11226: 
1.759     albertel 11227: sub declutter_portfile {
                   11228:     my ($file) = @_;
1.833     albertel 11229:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 11230:     return $file;
                   11231: }
                   11232: 
1.559     banghart 11233: # ------------------------------------------------------------- Mark as Read Only
                   11234: 
                   11235: sub mark_as_readonly {
                   11236:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 11237:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11238:     my ($tmp)=keys(%current_permissions);
                   11239:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 11240:     foreach my $file (@{$files}) {
1.759     albertel 11241: 	$file = &declutter_portfile($file);
1.561     banghart 11242:         push(@{$current_permissions{$file}},$what);
1.559     banghart 11243:     }
1.613     albertel 11244:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11245:     return;
                   11246: }
                   11247: 
1.572     banghart 11248: # ------------------------------------------------------------Save Selected Files
                   11249: 
                   11250: sub save_selected_files {
                   11251:     my ($user, $path, @files) = @_;
                   11252:     my $filename = $user."savedfiles";
1.573     banghart 11253:     my @other_files = &files_not_in_path($user, $path);
1.1172.2.96  raeburn  11254:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 11255:     foreach my $file (@files) {
1.620     albertel 11256:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 11257:     }
                   11258:     foreach my $file (@other_files) {
1.574     banghart 11259:         print (OUT $file."\n");
1.572     banghart 11260:     }
1.574     banghart 11261:     close (OUT);
1.572     banghart 11262:     return 'ok';
                   11263: }
                   11264: 
1.574     banghart 11265: sub clear_selected_files {
                   11266:     my ($user) = @_;
                   11267:     my $filename = $user."savedfiles";
1.1172.2.96  raeburn  11268:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 11269:     print (OUT undef);
                   11270:     close (OUT);
                   11271:     return ("ok");    
                   11272: }
                   11273: 
1.572     banghart 11274: sub files_in_path {
                   11275:     my ($user, $path) = @_;
                   11276:     my $filename = $user."savedfiles";
                   11277:     my %return_files;
1.1172.2.96  raeburn  11278:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 11279:     while (my $line_in = <IN>) {
1.574     banghart 11280:         chomp ($line_in);
                   11281:         my @paths_and_file = split (m!/!, $line_in);
                   11282:         my $file_part = pop (@paths_and_file);
                   11283:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 11284:         $path_part.='/';
                   11285:         my $path_and_file = $path_part.$file_part;
                   11286:         if ($path_part eq $path) {
                   11287:             $return_files{$file_part}= 'selected';
                   11288:         }
                   11289:     }
1.574     banghart 11290:     close (IN);
                   11291:     return (\%return_files);
1.572     banghart 11292: }
                   11293: 
                   11294: # called in portfolio select mode, to show files selected NOT in current directory
                   11295: sub files_not_in_path {
                   11296:     my ($user, $path) = @_;
                   11297:     my $filename = $user."savedfiles";
                   11298:     my @return_files;
                   11299:     my $path_part;
1.1172.2.96  raeburn  11300:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 11301:     while (my $line = <IN>) {
1.572     banghart 11302:         #ok, I know it's clunky, but I want it to work
1.800     albertel 11303:         my @paths_and_file = split(m|/|, $line);
                   11304:         my $file_part = pop(@paths_and_file);
                   11305:         chomp($file_part);
                   11306:         my $path_part = join('/', @paths_and_file);
1.572     banghart 11307:         $path_part .= '/';
                   11308:         my $path_and_file = $path_part.$file_part;
                   11309:         if ($path_part ne $path) {
1.800     albertel 11310:             push(@return_files, ($path_and_file));
1.572     banghart 11311:         }
                   11312:     }
1.800     albertel 11313:     close(OUT);
1.574     banghart 11314:     return (@return_files);
1.572     banghart 11315: }
                   11316: 
1.745     raeburn  11317: #----------------------------------------------Get portfolio file permissions
1.629     banghart 11318: 
1.745     raeburn  11319: sub get_portfile_permissions {
                   11320:     my ($domain,$user) = @_;
1.613     albertel 11321:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11322:     my ($tmp)=keys(%current_permissions);
                   11323:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11324:     return \%current_permissions;
                   11325: }
                   11326: 
                   11327: #---------------------------------------------Get portfolio file access controls
                   11328: 
1.749     raeburn  11329: sub get_access_controls {
1.745     raeburn  11330:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 11331:     my %access;
                   11332:     my $real_file = $file;
                   11333:     $file =~ s/\.meta$//;
1.745     raeburn  11334:     if (defined($file)) {
1.749     raeburn  11335:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   11336:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 11337:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  11338:             }
                   11339:         }
1.745     raeburn  11340:     } else {
1.749     raeburn  11341:         foreach my $key (keys(%{$current_permissions})) {
                   11342:             if ($key =~ /\0accesscontrol$/) {
                   11343:                 if (defined($group)) {
                   11344:                     if ($key !~ m-^\Q$group\E/-) {
                   11345:                         next;
                   11346:                     }
                   11347:                 }
                   11348:                 my ($fullpath) = split(/\0/,$key);
                   11349:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   11350:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   11351:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   11352:                     }
                   11353:                 }
                   11354:             }
                   11355:         }
                   11356:     }
                   11357:     return %access;
                   11358: }
                   11359: 
                   11360: sub modify_access_controls {
                   11361:     my ($file_name,$changes,$domain,$user)=@_;
                   11362:     my ($outcome,$deloutcome);
                   11363:     my %store_permissions;
                   11364:     my %new_values;
                   11365:     my %new_control;
                   11366:     my %translation;
                   11367:     my @deletions = ();
                   11368:     my $now = time;
                   11369:     if (exists($$changes{'activate'})) {
                   11370:         if (ref($$changes{'activate'}) eq 'HASH') {
                   11371:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   11372:             my $numnew = scalar(@newitems);
                   11373:             for (my $i=0; $i<$numnew; $i++) {
                   11374:                 my $newkey = $newitems[$i];
                   11375:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  11376:                 if ($newkey =~ /^\d+:/) { 
                   11377:                     $newkey =~ s/^(\d+)/$newid/;
                   11378:                     $translation{$1} = $newid;
                   11379:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   11380:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   11381:                     $translation{$1} = $newid;
                   11382:                 }
1.749     raeburn  11383:                 $new_values{$file_name."\0".$newkey} = 
                   11384:                                           $$changes{'activate'}{$newitems[$i]};
                   11385:                 $new_control{$newkey} = $now;
                   11386:             }
                   11387:         }
                   11388:     }
                   11389:     my %todelete;
                   11390:     my %changed_items;
                   11391:     foreach my $action ('delete','update') {
                   11392:         if (exists($$changes{$action})) {
                   11393:             if (ref($$changes{$action}) eq 'HASH') {
                   11394:                 foreach my $key (keys(%{$$changes{$action}})) {
                   11395:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   11396:                     if ($action eq 'delete') { 
                   11397:                         $todelete{$itemnum} = 1;
                   11398:                     } else {
                   11399:                         $changed_items{$itemnum} = $key;
                   11400:                     }
                   11401:                 }
1.745     raeburn  11402:             }
                   11403:         }
1.749     raeburn  11404:     }
                   11405:     # get lock on access controls for file.
                   11406:     my $lockhash = {
                   11407:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   11408:                                                        ':'.$env{'user.domain'},
                   11409:                    }; 
                   11410:     my $tries = 0;
                   11411:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11412:    
1.1172.2.79  raeburn  11413:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  11414:         $tries ++;
1.1172.2.79  raeburn  11415:         sleep(0.1);
1.749     raeburn  11416:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11417:     }
                   11418:     if ($gotlock eq 'ok') {
                   11419:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   11420:         my ($tmp)=keys(%curr_permissions);
                   11421:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   11422:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   11423:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   11424:             if (ref($curr_controls) eq 'HASH') {
                   11425:                 foreach my $control_item (keys(%{$curr_controls})) {
                   11426:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   11427:                     if (defined($todelete{$itemnum})) {
                   11428:                         push(@deletions,$file_name."\0".$control_item);
                   11429:                     } else {
                   11430:                         if (defined($changed_items{$itemnum})) {
                   11431:                             $new_control{$changed_items{$itemnum}} = $now;
                   11432:                             push(@deletions,$file_name."\0".$control_item);
                   11433:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   11434:                         } else {
                   11435:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   11436:                         }
                   11437:                     }
1.745     raeburn  11438:                 }
                   11439:             }
                   11440:         }
1.970     raeburn  11441:         my ($group);
                   11442:         if (&is_course($domain,$user)) {
                   11443:             ($group,my $file) = split(/\//,$file_name,2);
                   11444:         }
1.749     raeburn  11445:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   11446:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   11447:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   11448:         #  remove lock
                   11449:         my @del_lock = ($file_name."\0".'locked_access_records');
                   11450:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  11451:         my $sqlresult =
1.970     raeburn  11452:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  11453:                                     $group);
1.749     raeburn  11454:     } else {
                   11455:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  11456:     }
1.749     raeburn  11457:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  11458: }
                   11459: 
1.827     raeburn  11460: sub make_public_indefinitely {
                   11461:     my ($requrl) = @_;
                   11462:     my $now = time;
                   11463:     my $action = 'activate';
                   11464:     my $aclnum = 0;
                   11465:     if (&is_portfolio_url($requrl)) {
                   11466:         my (undef,$udom,$unum,$file_name,$group) =
                   11467:             &parse_portfolio_url($requrl);
                   11468:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   11469:         my %access_controls = &get_access_controls($current_perms,
                   11470:                                                    $group,$file_name);
                   11471:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   11472:             my ($num,$scope,$end,$start) = 
                   11473:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   11474:             if ($scope eq 'public') {
                   11475:                 if ($start <= $now && $end == 0) {
                   11476:                     $action = 'none';
                   11477:                 } else {
                   11478:                     $action = 'update';
                   11479:                     $aclnum = $num;
                   11480:                 }
                   11481:                 last;
                   11482:             }
                   11483:         }
                   11484:         if ($action eq 'none') {
                   11485:              return 'ok';
                   11486:         } else {
                   11487:             my %changes;
                   11488:             my $newend = 0;
                   11489:             my $newstart = $now;
                   11490:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   11491:             $changes{$action}{$newkey} = {
                   11492:                 type => 'public',
                   11493:                 time => {
                   11494:                     start => $newstart,
                   11495:                     end   => $newend,
                   11496:                 },
                   11497:             };
                   11498:             my ($outcome,$deloutcome,$new_values,$translation) =
                   11499:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   11500:             return $outcome;
                   11501:         }
                   11502:     } else {
                   11503:         return 'invalid';
                   11504:     }
                   11505: }
                   11506: 
1.745     raeburn  11507: #------------------------------------------------------Get Marked as Read Only
                   11508: 
                   11509: sub get_marked_as_readonly {
                   11510:     my ($domain,$user,$what,$group) = @_;
                   11511:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 11512:     my @readonly_files;
1.629     banghart 11513:     my $cmp1=$what;
                   11514:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  11515:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11516:         if (defined($group)) {
                   11517:             if ($file_name !~ m-^\Q$group\E/-) {
                   11518:                 next;
                   11519:             }
                   11520:         }
1.561     banghart 11521:         if (ref($value) eq "ARRAY"){
                   11522:             foreach my $stored_what (@{$value}) {
1.629     banghart 11523:                 my $cmp2=$stored_what;
1.759     albertel 11524:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  11525:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  11526:                 }
1.629     banghart 11527:                 if ($cmp1 eq $cmp2) {
1.561     banghart 11528:                     push(@readonly_files, $file_name);
1.745     raeburn  11529:                     last;
1.563     banghart 11530:                 } elsif (!defined($what)) {
                   11531:                     push(@readonly_files, $file_name);
1.745     raeburn  11532:                     last;
1.561     banghart 11533:                 }
                   11534:             }
1.745     raeburn  11535:         }
1.561     banghart 11536:     }
                   11537:     return @readonly_files;
                   11538: }
1.577     banghart 11539: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 11540: 
1.577     banghart 11541: sub get_marked_as_readonly_hash {
1.745     raeburn  11542:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 11543:     my %readonly_files;
1.745     raeburn  11544:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11545:         if (defined($group)) {
                   11546:             if ($file_name !~ m-^\Q$group\E/-) {
                   11547:                 next;
                   11548:             }
                   11549:         }
1.577     banghart 11550:         if (ref($value) eq "ARRAY"){
                   11551:             foreach my $stored_what (@{$value}) {
1.745     raeburn  11552:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 11553:                     foreach my $lock_descriptor(@{$stored_what}) {
                   11554:                         if ($lock_descriptor eq 'graded') {
                   11555:                             $readonly_files{$file_name} = 'graded';
                   11556:                         } elsif ($lock_descriptor eq 'handback') {
                   11557:                             $readonly_files{$file_name} = 'handback';
                   11558:                         } else {
                   11559:                             if (!exists($readonly_files{$file_name})) {
                   11560:                                 $readonly_files{$file_name} = 'locked';
                   11561:                             }
                   11562:                         }
1.745     raeburn  11563:                     }
1.750     banghart 11564:                 } 
1.577     banghart 11565:             }
                   11566:         } 
                   11567:     }
                   11568:     return %readonly_files;
                   11569: }
1.559     banghart 11570: # ------------------------------------------------------------ Unmark as Read Only
                   11571: 
                   11572: sub unmark_as_readonly {
1.629     banghart 11573:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   11574:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  11575:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 11576:     $file_name = &declutter_portfile($file_name);
1.634     albertel 11577:     my $symb_crs = $what;
                   11578:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  11579:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 11580:     my ($tmp)=keys(%current_permissions);
                   11581:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11582:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 11583:     foreach my $file (@readonly_files) {
1.759     albertel 11584: 	my $clean_file = &declutter_portfile($file);
                   11585: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 11586: 	my $current_locks = $current_permissions{$file};
1.563     banghart 11587:         my @new_locks;
                   11588:         my @del_keys;
                   11589:         if (ref($current_locks) eq "ARRAY"){
                   11590:             foreach my $locker (@{$current_locks}) {
1.632     albertel 11591:                 my $compare=$locker;
1.749     raeburn  11592:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  11593:                     $compare=join('',@{$locker});
1.746     raeburn  11594:                     if ($compare ne $symb_crs) {
                   11595:                         push(@new_locks, $locker);
                   11596:                     }
1.563     banghart 11597:                 }
                   11598:             }
1.650     albertel 11599:             if (scalar(@new_locks) > 0) {
1.563     banghart 11600:                 $current_permissions{$file} = \@new_locks;
                   11601:             } else {
                   11602:                 push(@del_keys, $file);
1.613     albertel 11603:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11604:                 delete($current_permissions{$file});
1.563     banghart 11605:             }
                   11606:         }
1.561     banghart 11607:     }
1.613     albertel 11608:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11609:     return;
                   11610: }
1.512     banghart 11611: 
1.17      www      11612: # ------------------------------------------------------------ Directory lister
                   11613: 
                   11614: sub dirlist {
1.955     raeburn  11615:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11616:     $uri=~s/^\///;
                   11617:     $uri=~s/\/$//;
1.253     stredwic 11618:     my ($udom, $uname);
1.955     raeburn  11619:     if ($getuserdir) {
1.253     stredwic 11620:         $udom = $userdomain;
                   11621:         $uname = $username;
1.955     raeburn  11622:     } else {
                   11623:         (undef,$udom,$uname)=split(/\//,$uri);
                   11624:         if(defined($userdomain)) {
                   11625:             $udom = $userdomain;
                   11626:         }
                   11627:         if(defined($username)) {
                   11628:             $uname = $username;
                   11629:         }
1.253     stredwic 11630:     }
1.955     raeburn  11631:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11632: 
1.955     raeburn  11633:     $dirRoot = $perlvar{'lonDocRoot'};
                   11634:     if (defined($getpropath)) {
                   11635:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11636:         $dirRoot =~ s/\/$//;
1.955     raeburn  11637:     } elsif (defined($getuserdir)) {
                   11638:         my $subdir=$uname.'__';
                   11639:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11640:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11641:                    ."/$udom/$subdir/$uname";
                   11642:     } elsif (defined($alternateRoot)) {
                   11643:         $dirRoot = $alternateRoot;
1.751     banghart 11644:     }
1.253     stredwic 11645: 
                   11646:     if($udom) {
                   11647:         if($uname) {
1.1135    raeburn  11648:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11649:             if ($uhome eq 'no_host') {
                   11650:                 return ([],'no_host');
                   11651:             }
1.955     raeburn  11652:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11653:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11654:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11655:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11656:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11657:             } else {
                   11658:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11659:             }
1.605     matthew  11660:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11661:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11662:                 @listing_results = split(/:/,$listing);
                   11663:             } else {
                   11664:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11665:             }
1.1135    raeburn  11666:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11667:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11668:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11669:                 return ([],$listing);
                   11670:             } else {
                   11671:                 return (\@listing_results);
1.1135    raeburn  11672:             }
1.955     raeburn  11673:         } elsif(!$alternateRoot) {
1.1136    raeburn  11674:             my (%allusers,%listerror);
1.841     albertel 11675: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11676:  	    foreach my $tryserver (keys(%servers)) {
                   11677:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11678:                                   &escape($udom),$tryserver);
                   11679:                 if ($listing eq 'unknown_cmd') {
                   11680: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11681: 				      $udom, $tryserver);
                   11682:                 } else {
                   11683:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11684:                 }
1.841     albertel 11685: 		if ($listing eq 'unknown_cmd') {
                   11686: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11687: 				      $udom, $tryserver);
                   11688: 		    @listing_results = split(/:/,$listing);
                   11689: 		} else {
                   11690: 		    @listing_results =
                   11691: 			map { &unescape($_); } split(/:/,$listing);
                   11692: 		}
1.1136    raeburn  11693:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11694:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11695:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11696:                     $listerror{$tryserver} = $listing;
                   11697:                 } else {
1.841     albertel 11698: 		    foreach my $line (@listing_results) {
                   11699: 			my ($entry) = split(/&/,$line,2);
                   11700: 			$allusers{$entry} = 1;
                   11701: 		    }
                   11702: 		}
1.253     stredwic 11703:             }
1.1136    raeburn  11704:             my @alluserslist=();
1.800     albertel 11705:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11706:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11707:             }
1.1172.2.80  raeburn  11708:             if (!%listerror) {
                   11709:                 # no errors
                   11710:                 return (\@alluserslist);
                   11711:             } elsif (scalar(keys(%servers)) == 1) {
                   11712:                 # one library server, one error
                   11713:                 my ($key) = keys(%listerror);
                   11714:                 return (\@alluserslist, $listerror{$key});
                   11715:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11716:                 # con_lost indicates that we might miss data from at least one
                   11717:                 # library server
                   11718:                 return (\@alluserslist, 'con_lost');
                   11719:             } else {
                   11720:                 # multiple library servers and no con_lost -> data should be
                   11721:                 # complete.
                   11722:                 return (\@alluserslist);
                   11723:             }
                   11724: 
1.253     stredwic 11725:         } else {
1.1136    raeburn  11726:             return ([],'missing username');
1.253     stredwic 11727:         }
1.955     raeburn  11728:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11729:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11730:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11731:         return (\@all_domains);
1.955     raeburn  11732:     } else {
1.1136    raeburn  11733:         return ([],'missing domain');
1.275     stredwic 11734:     }
                   11735: }
                   11736: 
                   11737: # --------------------------------------------- GetFileTimestamp
                   11738: # This function utilizes dirlist and returns the date stamp for
                   11739: # when it was last modified.  It will also return an error of -1
                   11740: # if an error occurs
                   11741: 
                   11742: sub GetFileTimestamp {
1.955     raeburn  11743:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11744:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11745:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11746:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11747:                                     undef,$getuserdir);
                   11748:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11749:         return -1;
                   11750:     }
                   11751:     if (ref($fileref) eq 'ARRAY') {
                   11752:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11753:         # @stats contains first the filename, then the stat output
                   11754:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11755:     } else {
                   11756:         return -1;
1.253     stredwic 11757:     }
1.26      www      11758: }
                   11759: 
1.712     albertel 11760: sub stat_file {
                   11761:     my ($uri) = @_;
1.787     albertel 11762:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11763: 
1.955     raeburn  11764:     my ($udom,$uname,$file);
1.712     albertel 11765:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11766: 	($udom,$uname,$file) =
1.811     albertel 11767: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11768: 	$file = 'userfiles/'.$file;
                   11769:     }
                   11770:     if ($uri =~ m-^/res/-) {
                   11771: 	($udom,$uname) = 
1.807     albertel 11772: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11773: 	$file = $uri;
                   11774:     }
                   11775: 
                   11776:     if (!$udom || !$uname || !$file) {
                   11777: 	# unable to handle the uri
                   11778: 	return ();
                   11779:     }
1.956     raeburn  11780:     my $getpropath;
                   11781:     if ($file =~ /^userfiles\//) {
                   11782:         $getpropath = 1;
                   11783:     }
1.1136    raeburn  11784:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11785:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11786:         return ();
                   11787:     } else {
                   11788:         if (ref($listref) eq 'ARRAY') {
                   11789:             my @stats = split('&',$listref->[0]);
                   11790: 	    shift(@stats); #filename is first
                   11791: 	    return @stats;
                   11792:         }
1.712     albertel 11793:     }
                   11794:     return ();
                   11795: }
                   11796: 
1.26      www      11797: # -------------------------------------------------------- Value of a Condition
                   11798: 
1.713     albertel 11799: # gets the value of a specific preevaluated condition
                   11800: #    stored in the string  $env{user.state.<cid>}
                   11801: # or looks up a condition reference in the bighash and if if hasn't
                   11802: # already been evaluated recurses into docondval to get the value of
                   11803: # the condition, then memoizing it to 
                   11804: #   $env{user.state.<cid>.<condition>}
1.40      www      11805: sub directcondval {
                   11806:     my $number=shift;
1.620     albertel 11807:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11808: 	&Apache::lonuserstate::evalstate();
                   11809:     }
1.713     albertel 11810:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11811: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11812:     } elsif ($number =~ /^_/) {
                   11813: 	my $sub_condition;
                   11814: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11815: 		&GDBM_READER(),0640)) {
                   11816: 	    $sub_condition=$bighash{'conditions'.$number};
                   11817: 	    untie(%bighash);
                   11818: 	}
                   11819: 	my $value = &docondval($sub_condition);
1.949     raeburn  11820: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11821: 	return $value;
                   11822:     }
1.620     albertel 11823:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11824:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11825:     } else {
                   11826:        return 2;
                   11827:     }
                   11828: }
                   11829: 
1.713     albertel 11830: # get the collection of conditions for this resource
1.26      www      11831: sub condval {
                   11832:     my $condidx=shift;
1.54      www      11833:     my $allpathcond='';
1.713     albertel 11834:     foreach my $cond (split(/\|/,$condidx)) {
                   11835: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11836: 	    $allpathcond.=
                   11837: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11838: 	}
1.191     harris41 11839:     }
1.54      www      11840:     $allpathcond=~s/\|$//;
1.713     albertel 11841:     return &docondval($allpathcond);
                   11842: }
                   11843: 
                   11844: #evaluates an expression of conditions
                   11845: sub docondval {
                   11846:     my ($allpathcond) = @_;
                   11847:     my $result=0;
                   11848:     if ($env{'request.course.id'}
                   11849: 	&& defined($allpathcond)) {
                   11850: 	my $operand='|';
                   11851: 	my @stack;
                   11852: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11853: 	    if ($chunk eq '(') {
                   11854: 		push @stack,($operand,$result);
                   11855: 	    } elsif ($chunk eq ')') {
                   11856: 		my $before=pop @stack;
                   11857: 		if (pop @stack eq '&') {
                   11858: 		    $result=$result>$before?$before:$result;
                   11859: 		} else {
                   11860: 		    $result=$result>$before?$result:$before;
                   11861: 		}
                   11862: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11863: 		$operand=$chunk;
                   11864: 	    } else {
                   11865: 		my $new=directcondval($chunk);
                   11866: 		if ($operand eq '&') {
                   11867: 		    $result=$result>$new?$new:$result;
                   11868: 		} else {
                   11869: 		    $result=$result>$new?$result:$new;
                   11870: 		}
                   11871: 	    }
                   11872: 	}
1.26      www      11873:     }
                   11874:     return $result;
1.421     albertel 11875: }
                   11876: 
                   11877: # ---------------------------------------------------- Devalidate courseresdata
                   11878: 
                   11879: sub devalidatecourseresdata {
                   11880:     my ($coursenum,$coursedomain)=@_;
                   11881:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11882:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11883: }
                   11884: 
1.763     www      11885: 
1.200     www      11886: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11887: #
                   11888: #  Parameters:
                   11889: #      $coursenum    - Number of the course.
                   11890: #      $coursedomain - Domain at which the course was created.
                   11891: #  Returns:
                   11892: #     A hash of the course parameters along (I think) with timestamps
                   11893: #     and version info.
1.877     foxr     11894: 
1.624     albertel 11895: sub get_courseresdata {
                   11896:     my ($coursenum,$coursedomain)=@_;
1.200     www      11897:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11898:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11899:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11900:     my %dumpreply;
1.417     albertel 11901:     unless (defined($cached)) {
1.624     albertel 11902: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11903: 	$result=\%dumpreply;
1.251     albertel 11904: 	my ($tmp) = keys(%dumpreply);
                   11905: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11906: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11907: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11908: 	    return $tmp;
1.416     albertel 11909: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11910: 	    $result=undef;
1.599     albertel 11911: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11912: 	}
                   11913:     }
1.624     albertel 11914:     return $result;
                   11915: }
                   11916: 
1.633     albertel 11917: sub devalidateuserresdata {
                   11918:     my ($uname,$udom)=@_;
                   11919:     my $hashid="$udom:$uname";
                   11920:     &devalidate_cache_new('userres',$hashid);
                   11921: }
                   11922: 
1.624     albertel 11923: sub get_userresdata {
                   11924:     my ($uname,$udom)=@_;
                   11925:     #most student don\'t have any data set, check if there is some data
                   11926:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11927: 
                   11928:     my $hashid="$udom:$uname";
                   11929:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11930:     if (!defined($cached)) {
                   11931: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11932: 	$result=\%resourcedata;
                   11933: 	&do_cache_new('userres',$hashid,$result,600);
                   11934:     }
                   11935:     my ($tmp)=keys(%$result);
                   11936:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11937: 	return $result;
                   11938:     }
                   11939:     #error 2 occurs when the .db doesn't exist
                   11940:     if ($tmp!~/error: 2 /) {
1.1172.2.71  raeburn  11941:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11942: 	    &logthis("<font color=\"blue\">WARNING:".
                   11943: 		     " Trying to get resource data for ".
                   11944: 		     $uname." at ".$udom.": ".
                   11945: 		     $tmp."</font>");
                   11946:         }
1.624     albertel 11947:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11948: 	#&EXT_cache_set($udom,$uname);
                   11949: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11950: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11951:     }
                   11952:     return $tmp;
                   11953: }
1.879     foxr     11954: #----------------------------------------------- resdata - return resource data
                   11955: #  Purpose:
                   11956: #    Return resource data for either users or for a course.
                   11957: #  Parameters:
                   11958: #     $name      - Course/user name.
                   11959: #     $domain    - Name of the domain the user/course is registered on.
                   11960: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   11961: #     @which     - Array of names of resources desired.
                   11962: #  Returns:
                   11963: #     The value of the first reasource in @which that is found in the
                   11964: #     resource hash.
                   11965: #  Exceptional Conditions:
                   11966: #     If the $type passed in is not valid (not the string 'course' or 
                   11967: #     'user', an undefined  reference is returned.
                   11968: #     If none of the resources are found, an undef is returned
1.624     albertel 11969: sub resdata {
                   11970:     my ($name,$domain,$type,@which)=@_;
                   11971:     my $result;
                   11972:     if ($type eq 'course') {
                   11973: 	$result=&get_courseresdata($name,$domain);
                   11974:     } elsif ($type eq 'user') {
                   11975: 	$result=&get_userresdata($name,$domain);
                   11976:     }
                   11977:     if (!ref($result)) { return $result; }    
1.251     albertel 11978:     foreach my $item (@which) {
1.927     albertel 11979: 	if (defined($result->{$item->[0]})) {
                   11980: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11981: 	}
1.250     albertel 11982:     }
1.291     albertel 11983:     return undef;
1.200     www      11984: }
                   11985: 
1.1172.2.146.  .1(raebu 11986:22): sub get_domain_lti {
                   11987:22):     my ($cdom,$context) = @_;
          .4(raebu 11988:22):     my ($name,$cachename,%lti);
          .1(raebu 11989:22):     if ($context eq 'consumer') {
                   11990:22):         $name = 'ltitools';
                   11991:22):     } elsif ($context eq 'provider') {
                   11992:22):         $name = 'lti';
          .4(raebu 11993:22):     } elsif ($context eq 'linkprot') {
                   11994:22):         $name = 'ltisec';
          .1(raebu 11995:22):     } else {
                   11996:22):         return %lti;
                   11997:22):     }
          .4(raebu 11998:22):     if ($context eq 'linkprot') {
                   11999:22):         $cachename = $context;
                   12000:22):     } else {
                   12001:22):         $cachename = $name;
                   12002:22):     }
                   12003:22):     my ($result,$cached)=&is_cached_new($cachename,$cdom);
          .1(raebu 12004:22):     if (defined($cached)) {
                   12005:22):         if (ref($result) eq 'HASH') {
                   12006:22):             %lti = %{$result};
                   12007:22):         }
                   12008:22):     } else {
                   12009:22):         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   12010:22):         if (ref($domconfig{$name}) eq 'HASH') {
          .4(raebu 12011:22):             if ($context eq 'linkprot') {
                   12012:22):                 if (ref($domconfig{$name}{'linkprot'}) eq 'HASH') {
                   12013:22):                     %lti = %{$domconfig{$name}{'linkprot'}};
                   12014:22):                 }
                   12015:22):             } else {
                   12016:22):                 %lti = %{$domconfig{$name}};
                   12017:22):             }
          .1(raebu 12018:22):         }
                   12019:22):         my $cachetime = 24*60*60;
          .4(raebu 12020:22):         &do_cache_new($cachename,$cdom,\%lti,$cachetime);
          .1(raebu 12021:22):     }
                   12022:22):     return %lti;
                   12023:22): }
                   12024:22): 
                   12025:22): sub get_course_lti {
          .13(raeb 12026:-23):     my ($cnum,$cdom,$context) = @_;
                   12027:-23):     my ($name,$cachename,%lti);
                   12028:-23):     if ($context eq 'consumer') {
                   12029:-23):         $name = 'ltitools';
                   12030:-23):         $cachename = 'courseltitools';
                   12031:-23):     } elsif ($context eq 'provider') {
                   12032:-23):         $name = 'lti';
                   12033:-23):         $cachename = 'courselti';
                   12034:-23):     } else {
                   12035:-23):         return %lti;
                   12036:-23):     }
          .1(raebu 12037:22):     my $hashid=$cdom.'_'.$cnum;
          .13(raeb 12038:-23):     my ($result,$cached)=&is_cached_new($cachename,$hashid);
          .1(raebu 12039:22):     if (defined($cached)) {
                   12040:22):         if (ref($result) eq 'HASH') {
          .13(raeb 12041:-23):             %lti = %{$result};
          .1(raebu 12042:22):         }
                   12043:22):     } else {
          .13(raeb 12044:-23):         %lti = &dump($name,$cdom,$cnum,undef,undef,undef,1);
          .1(raebu 12045:22):         my $cachetime = 24*60*60;
          .13(raeb 12046:-23):         &do_cache_new($cachename,$hashid,\%lti,$cachetime);
          .1(raebu 12047:22):     }
          .13(raeb 12048:-23):     return %lti;
          .1(raebu 12049:22): }
                   12050:22): 
          .3(raebu 12051:22): sub courselti_itemid {
                   12052:22):     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
                   12053:22):     my ($chome,$itemid);
                   12054:22):     $chome = &homeserver($cnum,$cdom);
                   12055:22):     return if ($chome eq 'no_host');
                   12056:22):     if (ref($params) eq 'HASH') {
                   12057:22):         my $rep;
                   12058:22):         if (grep { $_ eq $chome } current_machine_ids()) {
                   12059:22):             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
                   12060:22):         } else {
                   12061:22):             my $escurl = &escape($url);
                   12062:22):             my $escmethod = &escape($method);
                   12063:22):             my $items = &freeze_escape($params);
                   12064:22):             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
                   12065:22):         }
                   12066:22):         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   12067:22):                 ($rep eq 'unknown_cmd')) {
                   12068:22):             $itemid = $rep;
                   12069:22):         }
                   12070:22):     }
                   12071:22):     return $itemid;
                   12072:22): }
                   12073:22): 
                   12074:22): sub domainlti_itemid {
                   12075:22):     my ($cdom,$url,$method,$params,$context) = @_;
                   12076:22):     my ($primary_id,$itemid);
                   12077:22):     $primary_id = &domain($cdom,'primary');
                   12078:22):     return if ($primary_id eq '');
                   12079:22):     if (ref($params) eq 'HASH') {
                   12080:22):         my $rep;
                   12081:22):         if (grep { $_ eq $primary_id } current_machine_ids()) {
                   12082:22):             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
                   12083:22):         } else {
                   12084:22):             my $cnum = '';
                   12085:22):             my $escurl = &escape($url);
                   12086:22):             my $escmethod = &escape($method);
                   12087:22):             my $items = &freeze_escape($params);
                   12088:22):             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
                   12089:22):         }
                   12090:22):         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   12091:22):                 ($rep eq 'unknown_cmd')) {
                   12092:22):             $itemid = $rep;
                   12093:22):         }
                   12094:22):     }
                   12095:22):     return $itemid;
                   12096:22): }
                   12097:22): 
          .9(raebu 12098:23): sub count_supptools {
                   12099:23):     my ($cnum,$cdom,$ignorecache,$reload)=@_;
1.1172.2.31  raeburn  12100:     my $hashid=$cnum.':'.$cdom;
1.1172.2.146.  .9(raebu 12101:23):     my ($numexttools,$cached);
1.1172.2.31  raeburn  12102:     unless ($ignorecache) {
1.1172.2.146.  .9(raebu 12103:23):         ($numexttools,$cached) = &is_cached_new('supptools',$hashid);
1.1172.2.31  raeburn  12104:     }
                   12105:     unless (defined($cached)) {
                   12106:         my $chome=&homeserver($cnum,$cdom);
1.1172.2.146.  .9(raebu 12107:23):         $numexttools = 0;
1.1172.2.31  raeburn  12108:         unless ($chome eq 'no_host') {
1.1172.2.146.  .9(raebu 12109:23):             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$reload);
                   12110:23):             if (ref($supplemental) eq 'HASH') {
                   12111:23):                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   12112:23):                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
                   12113:23):                         if ($key =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
                   12114:23):                             $numexttools ++;
                   12115:23):                         }
                   12116:23):                     }
                   12117:23):                 }
                   12118:23):             }
1.1172.2.31  raeburn  12119:         }
1.1172.2.146.  .9(raebu 12120:23):         &do_cache_new('supptools',$hashid,$numexttools,600);
1.1172.2.31  raeburn  12121:     }
1.1172.2.146.  .9(raebu 12122:23):     return $numexttools;
                   12123:23): }
                   12124:23): 
                   12125:23): sub has_unhidden_suppfiles {
                   12126:23):     my ($cnum,$cdom,$ignorecache,$possdel)=@_;
                   12127:23):     my $hashid=$cnum.':'.$cdom;
                   12128:23):     my ($showsupp,$cached);
                   12129:23):     unless ($ignorecache) {
                   12130:23):         ($showsupp,$cached) = &is_cached_new('showsupp',$hashid);
                   12131:23):     }
                   12132:23):     unless (defined($cached)) {
                   12133:23):         my $chome=&homeserver($cnum,$cdom);
                   12134:23):         unless ($chome eq 'no_host') {
                   12135:23):             my ($supplemental) = &Apache::loncommon::get_supplemental($cnum,$cdom,$ignorecache,$possdel);
                   12136:23):             if (ref($supplemental) eq 'HASH') {
                   12137:23):                 if ((ref($supplemental->{'ids'}) eq 'HASH') && (ref($supplemental->{'hidden'}) eq 'HASH')) {
                   12138:23):                     foreach my $key (keys(%{$supplemental->{'ids'}})) {
                   12139:23):                         next if ($key =~ /\.sequence$/);
                   12140:23):                         if (ref($supplemental->{'ids'}->{$key}) eq 'ARRAY') {
                   12141:23):                             foreach my $id (@{$supplemental->{'ids'}->{$key}}) {
                   12142:23):                                 unless ($supplemental->{'hidden'}->{$id}) {
                   12143:23):                                     $showsupp = 1;
                   12144:23):                                     last;
                   12145:23):                                 }
                   12146:23):                             }
                   12147:23):                         }
                   12148:23):                         last if ($showsupp);
                   12149:23):                     }
                   12150:23):                 }
                   12151:23):             }
                   12152:23):         }
                   12153:23):         &do_cache_new('showsupp',$hashid,$showsupp,600);
                   12154:23):     }
                   12155:23):     return $showsupp;
1.1172.2.31  raeburn  12156: }
                   12157: 
1.379     matthew  12158: #
                   12159: # EXT resource caching routines
                   12160: #
                   12161: 
1.1172.2.146.  .1(raebu 12162:22): {
                   12163:22): # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   12164:22): #
                   12165:22): # The course for which we cache
                   12166:22): my $cachedmapkey='';
                   12167:22): # The cached recursive maps for this course
                   12168:22): my %cachedmaps=();
                   12169:22): # When this was last done
                   12170:22): my $cachedmaptime='';
                   12171:22): 
1.379     matthew  12172: sub clear_EXT_cache_status {
1.383     albertel 12173:     &delenv('cache.EXT.');
1.379     matthew  12174: }
                   12175: 
                   12176: sub EXT_cache_status {
                   12177:     my ($target_domain,$target_user) = @_;
1.383     albertel 12178:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 12179:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  12180:         # We know already the user has no data
                   12181:         return 1;
                   12182:     } else {
                   12183:         return 0;
                   12184:     }
                   12185: }
                   12186: 
                   12187: sub EXT_cache_set {
                   12188:     my ($target_domain,$target_user) = @_;
1.383     albertel 12189:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  12190:     #&appenv({$cachename => time});
1.379     matthew  12191: }
                   12192: 
1.28      www      12193: # --------------------------------------------------------- Value of a Variable
1.58      www      12194: sub EXT {
1.715     albertel 12195: 
1.1172.2.28  raeburn  12196:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      12197:     unless ($varname) { return ''; }
1.218     albertel 12198:     #get real user name/domain, courseid and symb
                   12199:     my $courseid;
1.359     albertel 12200:     my $publicuser;
1.427     www      12201:     if ($symbparm) {
                   12202: 	$symbparm=&get_symb_from_alias($symbparm);
                   12203:     }
1.218     albertel 12204:     if (!($uname && $udom)) {
1.790     albertel 12205:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 12206:       if (!$symbparm) {	$symbparm=$cursymb; }
                   12207:     } else {
1.620     albertel 12208: 	$courseid=$env{'request.course.id'};
1.218     albertel 12209:     }
1.48      www      12210:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   12211:     my $rest;
1.320     albertel 12212:     if (defined($therest[0])) {
1.48      www      12213:        $rest=join('.',@therest);
                   12214:     } else {
                   12215:        $rest='';
                   12216:     }
1.320     albertel 12217: 
1.57      www      12218:     my $qualifierrest=$qualifier;
                   12219:     if ($rest) { $qualifierrest.='.'.$rest; }
                   12220:     my $spacequalifierrest=$space;
                   12221:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      12222:     if ($realm eq 'user') {
1.48      www      12223: # --------------------------------------------------------------- user.resource
                   12224: 	if ($space eq 'resource') {
1.651     albertel 12225: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   12226: 		  || defined($Apache::lonhomework::parsing_a_task))
                   12227: 		 &&
1.1172.2.142  raeburn  12228: 		 ($symbparm eq &symbread()) ) {
1.744     albertel 12229: 		# if we are in the middle of processing the resource the
                   12230: 		# get the value we are planning on committing
                   12231:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   12232:                     return $Apache::lonhomework::results{$qualifierrest};
                   12233:                 } else {
                   12234:                     return $Apache::lonhomework::history{$qualifierrest};
                   12235:                 }
1.335     albertel 12236: 	    } else {
1.359     albertel 12237: 		my %restored;
1.620     albertel 12238: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 12239: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   12240: 		} else {
                   12241: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   12242: 		}
1.335     albertel 12243: 		return $restored{$qualifierrest};
                   12244: 	    }
1.48      www      12245: # ----------------------------------------------------------------- user.access
                   12246:         } elsif ($space eq 'access') {
1.218     albertel 12247: 	    # FIXME - not supporting calls for a specific user
1.48      www      12248:             return &allowed($qualifier,$rest);
                   12249: # ------------------------------------------ user.preferences, user.environment
                   12250:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 12251: 	    if (($uname eq $env{'user.name'}) &&
                   12252: 		($udom eq $env{'user.domain'})) {
                   12253: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 12254: 	    } else {
1.359     albertel 12255: 		my %returnhash;
                   12256: 		if (!$publicuser) {
                   12257: 		    %returnhash=&userenvironment($udom,$uname,
                   12258: 						 $qualifierrest);
                   12259: 		}
1.218     albertel 12260: 		return $returnhash{$qualifierrest};
                   12261: 	    }
1.48      www      12262: # ----------------------------------------------------------------- user.course
                   12263:         } elsif ($space eq 'course') {
1.218     albertel 12264: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12265:             return $env{join('.',('request.course',$qualifier))};
1.48      www      12266: # ------------------------------------------------------------------- user.role
                   12267:         } elsif ($space eq 'role') {
1.218     albertel 12268: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12269:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      12270:             if ($qualifier eq 'value') {
                   12271: 		return $role;
                   12272:             } elsif ($qualifier eq 'extent') {
                   12273:                 return $where;
                   12274:             }
                   12275: # ----------------------------------------------------------------- user.domain
                   12276:         } elsif ($space eq 'domain') {
1.218     albertel 12277:             return $udom;
1.48      www      12278: # ------------------------------------------------------------------- user.name
                   12279:         } elsif ($space eq 'name') {
1.218     albertel 12280:             return $uname;
1.48      www      12281: # ---------------------------------------------------- Any other user namespace
1.29      www      12282:         } else {
1.359     albertel 12283: 	    my %reply;
                   12284: 	    if (!$publicuser) {
                   12285: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   12286: 	    }
                   12287: 	    return $reply{$qualifierrest};
1.48      www      12288:         }
1.236     www      12289:     } elsif ($realm eq 'query') {
                   12290: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 12291:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   12292: 						[$spacequalifierrest]);
1.620     albertel 12293: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      12294:    } elsif ($realm eq 'request') {
1.48      www      12295: # ------------------------------------------------------------- request.browser
                   12296:         if ($space eq 'browser') {
1.1145    bisitz   12297:             return $env{'browser.'.$qualifier};
1.57      www      12298: # ------------------------------------------------------------ request.filename
                   12299:         } else {
1.620     albertel 12300:             return $env{'request.'.$spacequalifierrest};
1.29      www      12301:         }
1.28      www      12302:     } elsif ($realm eq 'course') {
1.48      www      12303: # ---------------------------------------------------------- course.description
1.620     albertel 12304:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      12305:     } elsif ($realm eq 'resource') {
1.165     www      12306: 
1.620     albertel 12307: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 12308: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   12309: 	}
1.693     albertel 12310: 
1.1172.2.30  raeburn  12311:         if ($qualifier eq '') {
                   12312: 	    if ($space eq 'title') {
                   12313: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   12314: 	        return &gettitle($symbparm);
                   12315: 	    }
1.693     albertel 12316: 	
1.1172.2.30  raeburn  12317: 	    if ($space eq 'map') {
                   12318: 	        my ($map) = &decode_symb($symbparm);
                   12319: 	        return &symbread($map);
                   12320: 	    }
                   12321:             if ($space eq 'maptitle') {
                   12322:                 my ($map) = &decode_symb($symbparm);
                   12323:                 return &gettitle($map);
                   12324:             }
                   12325: 	    if ($space eq 'filename') {
                   12326: 	        if ($symbparm) {
                   12327: 		    return &clutter((&decode_symb($symbparm))[2]);
                   12328: 	        }
                   12329: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 12330: 	    }
1.1172.2.30  raeburn  12331: 
                   12332:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   12333:                 if ($space eq 'visibleparts') {
                   12334:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   12335:                     my $item;
                   12336:                     if (ref($navmap)) {
                   12337:                         my $res = $navmap->getBySymb($symbparm);
                   12338:                         my $parts = $res->parts();
                   12339:                         if (ref($parts) eq 'ARRAY') {
                   12340:                             $item = join(',',@{$parts});
                   12341:                         }
                   12342:                         undef($navmap);
                   12343:                     }
                   12344:                     return $item;
                   12345:                 }
                   12346:             }
                   12347:         }
1.693     albertel 12348: 
                   12349: 	my ($section, $group, @groups);
1.593     albertel 12350: 	my ($courselevelm,$courselevel);
1.1172.2.28  raeburn  12351:         if (($courseid eq '') && ($cid)) {
                   12352:             $courseid = $cid;
                   12353:         }
                   12354: 	if (($symbparm && $courseid) && 
                   12355: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
1.165     www      12356: 
1.218     albertel 12357: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      12358: 
1.60      www      12359: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 12360: 	    my $symbp=$symbparm;
1.735     albertel 12361: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 12362: 
                   12363: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   12364: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   12365: 
1.620     albertel 12366: 	    if (($env{'user.name'} eq $uname) &&
                   12367: 		($env{'user.domain'} eq $udom)) {
                   12368: 		$section=$env{'request.course.sec'};
1.733     raeburn  12369:                 @groups = split(/:/,$env{'request.course.groups'});  
                   12370:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 12371: 	    } else {
1.539     albertel 12372: 		if (! defined($usection)) {
1.551     albertel 12373: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 12374: 		} else {
                   12375: 		    $section = $usection;
                   12376: 		}
1.733     raeburn  12377:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 12378: 	    }
                   12379: 
                   12380: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   12381: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   12382: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   12383: 
1.593     albertel 12384: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 12385: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 12386: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      12387: 
1.60      www      12388: # ----------------------------------------------------------- first, check user
1.624     albertel 12389: 
                   12390: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 12391: 				       ([$courselevelr,'resource'],
                   12392: 					[$courselevelm,'map'     ],
                   12393: 					[$courselevel, 'course'  ]));
1.931     albertel 12394: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      12395: 
1.594     albertel 12396: # ------------------------------------------------ second, check some of course
1.684     raeburn  12397:             my $coursereply;
1.691     raeburn  12398:             if (@groups > 0) {
                   12399:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   12400:                                        $mapparm,$spacequalifierrest);
1.927     albertel 12401:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  12402:             }
1.96      www      12403: 
1.684     raeburn  12404: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 12405: 				  $env{'course.'.$courseid.'.domain'},
                   12406: 				  'course',
                   12407: 				  ([$seclevelr,   'resource'],
                   12408: 				   [$seclevelm,   'map'     ],
                   12409: 				   [$seclevel,    'course'  ],
                   12410: 				   [$courselevelr,'resource']));
                   12411: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      12412: 
1.60      www      12413: # ------------------------------------------------------ third, check map parms
1.218     albertel 12414: 	    my %parmhash=();
                   12415: 	    my $thisparm='';
                   12416: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 12417: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 12418: 		    &GDBM_READER(),0640)) {
1.218     albertel 12419: 		$thisparm=$parmhash{$symbparm};
                   12420: 		untie(%parmhash);
                   12421: 	    }
1.927     albertel 12422: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 12423: 	}
1.594     albertel 12424: # ------------------------------------------ fourth, look in resource metadata
1.71      www      12425: 
1.1172.2.146.  .13(raeb 12426:-23):         my $what = $spacequalifierrest;
                   12427:-23):         $what=~s/\./\_/;
                   12428:-23):         my $filename;
1.282     albertel 12429: 	if (!$symbparm) { $symbparm=&symbread(); }
                   12430: 	if ($symbparm) {
1.409     www      12431: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 12432: 	} else {
1.620     albertel 12433: 	    $filename=$env{'request.filename'};
1.282     albertel 12434: 	}
1.1172.2.146.  .13(raeb 12435:-23):         my $toolsymb;
                   12436:-23):         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   12437:-23):             $toolsymb = $symbparm;
                   12438:-23):         }
                   12439:-23): 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 12440: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1172.2.146.  .13(raeb 12441:-23): 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 12442: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      12443: 
1.1172.2.146.  .13(raeb 12444:-23): # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 12445: 	if ($symbparm && defined($courseid) && 
1.620     albertel 12446: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 12447: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   12448: 				     $env{'course.'.$courseid.'.domain'},
                   12449: 				     'course',
1.927     albertel 12450: 				     ([$courselevelm,'map'   ],
                   12451: 				      [$courselevel, 'course']));
                   12452: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 12453: 	}
1.145     www      12454: # ------------------------------------------------------------------ Cascade up
1.218     albertel 12455: 	unless ($space eq '0') {
1.336     albertel 12456: 	    my @parts=split(/_/,$space);
                   12457: 	    my $id=pop(@parts);
                   12458: 	    my $part=join('_',@parts);
                   12459: 	    if ($part eq '') { $part='0'; }
1.927     albertel 12460: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 12461: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  12462: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 12463: 	}
1.395     albertel 12464: 	if ($recurse) { return undef; }
1.1172.2.146.  .13(raeb 12465:-23): 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 12466: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      12467: # ---------------------------------------------------- Any other user namespace
                   12468:     } elsif ($realm eq 'environment') {
                   12469: # ----------------------------------------------------------------- environment
1.620     albertel 12470: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   12471: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 12472: 	} else {
1.770     albertel 12473: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   12474: 		return '';
                   12475: 	    }
1.219     albertel 12476: 	    my %returnhash=&userenvironment($udom,$uname,
                   12477: 					    $spacequalifierrest);
                   12478: 	    return $returnhash{$spacequalifierrest};
                   12479: 	}
1.28      www      12480:     } elsif ($realm eq 'system') {
1.48      www      12481: # ----------------------------------------------------------------- system.time
                   12482: 	if ($space eq 'time') {
                   12483: 	    return time;
                   12484:         }
1.696     albertel 12485:     } elsif ($realm eq 'server') {
                   12486: # ----------------------------------------------------------------- system.time
                   12487: 	if ($space eq 'name') {
                   12488: 	    return $ENV{'SERVER_NAME'};
                   12489:         }
1.1172.2.146.  .1(raebu 12490:22):     } elsif ($realm eq 'client') {
                   12491:22):         if ($space eq 'remote_addr') {
                   12492:22):             return &get_requestor_ip();
                   12493:22):         }
1.28      www      12494:     }
1.48      www      12495:     return '';
1.61      www      12496: }
                   12497: 
1.927     albertel 12498: sub get_reply {
                   12499:     my ($reply_value) = @_;
1.940     raeburn  12500:     if (ref($reply_value) eq 'ARRAY') {
                   12501:         if (wantarray) {
                   12502: 	    return @$reply_value;
                   12503:         }
                   12504:         return $reply_value->[0];
                   12505:     } else {
                   12506:         return $reply_value;
1.927     albertel 12507:     }
                   12508: }
                   12509: 
1.691     raeburn  12510: sub check_group_parms {
                   12511:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   12512:     my @groupitems = ();
                   12513:     my $resultitem;
1.927     albertel 12514:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  12515:     foreach my $group (@{$groups}) {
                   12516:         foreach my $level (@levels) {
1.927     albertel 12517:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   12518:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  12519:         }
                   12520:     }
                   12521:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   12522:                             $env{'course.'.$courseid.'.domain'},
                   12523:                                      'course',@groupitems);
                   12524:     return $coursereply;
                   12525: }
                   12526: 
1.1172.2.146.  .1(raebu 12527:22): sub get_map_hierarchy {
                   12528:22):     my ($mapname,$courseid) = @_;
                   12529:22):     my @recurseup = ();
                   12530:22):     if ($mapname) {
                   12531:22):         if (($cachedmapkey eq $courseid) &&
                   12532:22):             (abs($cachedmaptime-time)<5)) {
                   12533:22):             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   12534:22):                 return @{$cachedmaps{$mapname}};
                   12535:22):             }
                   12536:22):         }
                   12537:22):         my $navmap = Apache::lonnavmaps::navmap->new();
                   12538:22):         if (ref($navmap)) {
                   12539:22):             @recurseup = $navmap->recurseup_maps($mapname);
                   12540:22):             undef($navmap);
                   12541:22):             $cachedmaps{$mapname} = \@recurseup;
                   12542:22):             $cachedmaptime=time;
                   12543:22):             $cachedmapkey=$courseid;
                   12544:22):         }
                   12545:22):     }
                   12546:22):     return @recurseup;
                   12547:22): }
                   12548:22): 
          .2(raebu 12549:22): }
          .1(raebu 12550:22): 
1.691     raeburn  12551: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  12552:     my ($courseid,@groups) = @_;
                   12553:     @groups = sort(@groups);
1.691     raeburn  12554:     return @groups;
                   12555: }
                   12556: 
1.395     albertel 12557: sub packages_tab_default {
1.1172.2.146.  .13(raeb 12558:-23):     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 12559:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 12560: 
                   12561:     my (@extension,@specifics,$do_default);
1.1172.2.146.  .13(raeb 12562:-23):     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 12563: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 12564: 	if ($pack_type eq 'default') {
                   12565: 	    $do_default=1;
                   12566: 	} elsif ($pack_type eq 'extension') {
                   12567: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 12568: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 12569: 	    # only look at packages defaults for packages that this id is
1.738     albertel 12570: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   12571: 	}
                   12572:     }
                   12573:     # first look for a package that matches the requested part id
                   12574:     foreach my $package (@specifics) {
                   12575: 	my (undef,$pack_type,$pack_part)=@{$package};
                   12576: 	next if ($pack_part ne $part);
                   12577: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12578: 	    return $packagetab{"$pack_type&$name&default"};
                   12579: 	}
                   12580:     }
                   12581:     # look for any possible matching non extension_ package
                   12582:     foreach my $package (@specifics) {
                   12583: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 12584: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12585: 	    return $packagetab{"$pack_type&$name&default"};
                   12586: 	}
1.585     albertel 12587: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 12588: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   12589: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 12590: 	}
                   12591:     }
1.738     albertel 12592:     # look for any posible extension_ match
                   12593:     foreach my $package (@extension) {
                   12594: 	my ($package,$pack_type)=@{$package};
                   12595: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12596: 	    return $packagetab{"$pack_type&$name&default"};
                   12597: 	}
                   12598: 	if (defined($packagetab{$package."&$name&default"})) {
                   12599: 	    return $packagetab{$package."&$name&default"};
                   12600: 	}
                   12601:     }
                   12602:     # look for a global default setting
                   12603:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   12604: 	return $packagetab{"default&$name&default"};
                   12605:     }
1.395     albertel 12606:     return undef;
                   12607: }
                   12608: 
1.334     albertel 12609: sub add_prefix_and_part {
                   12610:     my ($prefix,$part)=@_;
                   12611:     my $keyroot;
                   12612:     if (defined($prefix) && $prefix !~ /^__/) {
                   12613: 	# prefix that has a part already
                   12614: 	$keyroot=$prefix;
                   12615:     } elsif (defined($prefix)) {
                   12616: 	# prefix that is missing a part
                   12617: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   12618:     } else {
                   12619: 	# no prefix at all
                   12620: 	if (defined($part)) { $keyroot='_'.$part; }
                   12621:     }
                   12622:     return $keyroot;
                   12623: }
                   12624: 
1.71      www      12625: # ---------------------------------------------------------------- Get metadata
                   12626: 
1.599     albertel 12627: my %metaentry;
1.1070    www      12628: my %importedpartids;
1.1172.2.99  raeburn  12629: my %importedrespids;
1.71      www      12630: sub metadata {
1.1172.2.146.  .13(raeb 12631:-23):     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      12632:     $uri=&declutter($uri);
1.288     albertel 12633:     # if it is a non metadata possible uri return quickly
1.529     albertel 12634:     if (($uri eq '') || 
                   12635: 	(($uri =~ m|^/*adm/|) && 
1.1172.2.146.  .1(raebu 12636:22): 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  12637:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 12638: 	return undef;
                   12639:     }
1.1172.2.49  raeburn  12640:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 12641: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 12642: 	return undef;
1.288     albertel 12643:     }
1.73      www      12644:     my $filename=$uri;
                   12645:     $uri=~s/\.meta$//;
1.172     www      12646: #
                   12647: # Is the metadata already cached?
1.177     www      12648: # Look at timestamp of caching
1.172     www      12649: # Everything is cached by the main uri, libraries are never directly cached
                   12650: #
1.428     albertel 12651:     if (!defined($liburi)) {
1.599     albertel 12652: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 12653: 	if (defined($cached)) { return $result->{':'.$what}; }
                   12654:     }
1.1172.2.146.  .13(raeb 12655:-23): 
                   12656:-23): #
                   12657:-23): # If the uri is for an external tool the file from
                   12658:-23): # which metadata should be retrieved depends on whether
                   12659:-23): # the tool had been configured to be gradable (set in the Course
                   12660:-23): # Editor or Resource Editor).
                   12661:-23): #
                   12662:-23): # If a valid symb has been included as the third arg in the call
                   12663:-23): # to &metadata() that can be used to retrieve the value of
                   12664:-23): # parameter_0_gradable set for the resource, and included in the
                   12665:-23): # uploaded map containing the tool. The value is retrieved via
                   12666:-23): # &EXT(), if a valid symb is available.  Otherwise the value of
                   12667:-23): # gradable in the exttool_$marker.db file for the tool instance
                   12668:-23): # is retrieved via &get().
                   12669:-23): #
                   12670:-23): # When lonuserstate::traceroute() calls lonnet::EXT() for
                   12671:-23): # hiddenresource and encrypturl (during course initialization)
                   12672:-23): # the map-level parameter for resource.0.gradable included in the
                   12673:-23): # uploaded map containing the tool will not yet have been stored
                   12674:-23): # in the user_course_parms.db file for the user's session, so in
                   12675:-23): # this case fall back to retrieving gradable status from the
                   12676:-23): # exttool_$marker.db file.
                   12677:-23): #
                   12678:-23): # In order to avoid an infinite loop, &metadata() will return
                   12679:-23): # before a call to &EXT(), if the uri is for an external tool
                   12680:-23): # and the $what for which metadata is being requested is
                   12681:-23): # parameter_0_gradable or 0_gradable.
                   12682:-23): #
                   12683:-23): 
                   12684:-23):     if ($uri =~ /ext\.tool$/) {
                   12685:-23):         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   12686:-23):             return;
                   12687:-23):         } else {
                   12688:-23):             my ($checked,$use_passback);
                   12689:-23):             if ($toolsymb ne '') {
                   12690:-23):                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
                   12691:-23):                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
                   12692:-23):                     $checked = 1;
                   12693:-23):                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   12694:-23):                         $use_passback = 1;
                   12695:-23):                     }
                   12696:-23):                 }
                   12697:-23):             }
                   12698:-23):             unless ($checked) {
                   12699:-23):                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   12700:-23):                 $marker=~s/\D//g;
                   12701:-23):                 if ($marker) {
                   12702:-23):                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   12703:-23):                     $use_passback = $toolsettings{'gradable'};
                   12704:-23):                 }
                   12705:-23):             }
                   12706:-23):             if ($use_passback) {
                   12707:-23):                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   12708:-23):             } else {
                   12709:-23):                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   12710:-23):             }
                   12711:-23):         }
                   12712:-23):     }
                   12713:-23): 
1.428     albertel 12714:     {
1.1069    www      12715: # Imported parts would go here
1.1172.2.99  raeburn  12716:         my @origfiletagids=();
1.1069    www      12717:         my $importedparts=0;
1.1172.2.99  raeburn  12718: 
                   12719: # Imported responseids would go here
                   12720:         my $importedresponses=0;
1.172     www      12721: #
                   12722: # Is this a recursive call for a library?
                   12723: #
1.599     albertel 12724: #	if (! exists($metacache{$uri})) {
                   12725: #	    $metacache{$uri}={};
                   12726: #	}
1.924     albertel 12727: 	my $cachetime = 60*60;
1.171     www      12728:         if ($liburi) {
                   12729: 	    $liburi=&declutter($liburi);
                   12730:             $filename=$liburi;
1.401     bowersj2 12731:         } else {
1.599     albertel 12732: 	    &devalidate_cache_new('meta',$uri);
                   12733: 	    undef(%metaentry);
1.401     bowersj2 12734: 	}
1.140     www      12735:         my %metathesekeys=();
1.73      www      12736:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 12737: 	my $metastring;
1.1140    www      12738: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 12739: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 12740: 	    $metastring = 
1.929     albertel 12741: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 12742: 					  ('grade_target' => 'meta'));
                   12743: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  12744: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   12745:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 12746: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 12747: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 12748: 	    $metastring=&getfile($file);
1.489     albertel 12749: 	}
1.208     albertel 12750:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      12751:         my $token;
1.140     www      12752:         undef %metathesekeys;
1.71      www      12753:         while ($token=$parser->get_token) {
1.339     albertel 12754: 	    if ($token->[0] eq 'S') {
                   12755: 		if (defined($token->[2]->{'package'})) {
1.172     www      12756: #
                   12757: # This is a package - get package info
                   12758: #
1.339     albertel 12759: 		    my $package=$token->[2]->{'package'};
                   12760: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12761: 		    if (defined($token->[2]->{'id'})) { 
                   12762: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   12763: 		    }
1.599     albertel 12764: 		    if ($metaentry{':packages'}) {
                   12765: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 12766: 		    } else {
1.599     albertel 12767: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 12768: 		    }
1.736     albertel 12769: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 12770: 			my $part=$keyroot;
                   12771: 			$part=~s/^\_//;
1.736     albertel 12772: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   12773: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   12774: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 12775: 			    # ignore package.tab specified default values
                   12776:                             # here &package_tab_default() will fetch those
                   12777: 			    if ($subp eq 'default') { next; }
1.736     albertel 12778: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 12779: 			    my $unikey;
                   12780: 			    if ($pack =~ /_0$/) {
                   12781: 				$unikey='parameter_0_'.$name;
                   12782: 				$part=0;
                   12783: 			    } else {
                   12784: 				$unikey='parameter'.$keyroot.'_'.$name;
                   12785: 			    }
1.339     albertel 12786: 			    if ($subp eq 'display') {
                   12787: 				$value.=' [Part: '.$part.']';
                   12788: 			    }
1.599     albertel 12789: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 12790: 			    $metathesekeys{$unikey}=1;
1.599     albertel 12791: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12792: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 12793: 			    }
1.599     albertel 12794: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   12795: 				$metaentry{':'.$unikey}=
                   12796: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 12797: 			    }
1.339     albertel 12798: 			}
                   12799: 		    }
                   12800: 		} else {
1.172     www      12801: #
                   12802: # This is not a package - some other kind of start tag
1.339     albertel 12803: #
                   12804: 		    my $entry=$token->[1];
1.1068    www      12805: 		    my $unikey='';
1.175     www      12806: 
1.339     albertel 12807: 		    if ($entry eq 'import') {
1.175     www      12808: #
                   12809: # Importing a library here
1.339     albertel 12810: #
1.1067    www      12811:                         my $location=$parser->get_text('/import');
                   12812:                         my $dir=$filename;
                   12813:                         $dir=~s|[^/]*$||;
                   12814:                         $location=&filelocation($dir,$location);
1.1172.2.99  raeburn  12815: 
                   12816:                         my $importid=$token->[2]->{'id'};
1.1068    www      12817:                         my $importmode=$token->[2]->{'importmode'};
1.1172.2.99  raeburn  12818: #
                   12819: # Check metadata for imported file to
                   12820: # see if it contained response items
                   12821: #
                   12822:                         my %currmetaentry = %metaentry;
                   12823:                         my $libresponseorder = &metadata($location,'responseorder');
                   12824:                         my $origfile;
                   12825:                         if ($libresponseorder ne '') {
                   12826:                             if ($#origfiletagids<0) {
                   12827:                                 undef(%importedrespids);
                   12828:                                 undef(%importedpartids);
                   12829:                             }
                   12830:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
                   12831:                             if (@{$importedrespids{$importid}} > 0) {
                   12832:                                 $importedresponses = 1;
                   12833: # We need to get the original file and the imported file to get the response order correct
                   12834: # Load and inspect original file
                   12835:                                 if ($#origfiletagids<0) {
                   12836:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12837:                                     $origfile=&getfile($origfilelocation);
                   12838:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12839:                                 }
                   12840:                             }
                   12841:                         }
                   12842: # Do not overwrite contents of %metaentry hash for resource itself with 
                   12843: # hash populated for imported library file
                   12844:                         %metaentry = %currmetaentry;
                   12845:                         undef(%currmetaentry);
1.1068    www      12846:                         if ($importmode eq 'problem') {
1.1069    www      12847: # Import as problem/response
1.1068    www      12848:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12849:                         } elsif ($importmode eq 'part') {
                   12850: # Import as part(s)
1.1069    www      12851:                            $importedparts=1;
                   12852: # We need to get the original file and the imported file to get the part order correct
                   12853: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1172.2.99  raeburn  12854: # Load and inspect original file if we didn't do that already
                   12855:                            if ($#origfiletagids<0) {
                   12856:                                undef(%importedrespids);
                   12857:                                undef(%importedpartids);
                   12858:                                if ($origfile eq '') {
                   12859:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   12860:                                    $origfile=&getfile($origfilelocation);
                   12861:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12862:                                }
1.1070    www      12863:                            }
                   12864: 
1.1069    www      12865: # Load and inspect imported file
                   12866:                            my $impfile=&getfile($location);
                   12867:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12868:                            if ($#impfilepartids>=0) {
                   12869: # This problem had parts
1.1070    www      12870:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12871:                            } else {
                   12872: # Importing by turning a single problem into a problem part
                   12873: # It gets the import-tags ID as part-ID
                   12874:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12875:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12876:                            }
1.1068    www      12877:                         } else {
                   12878: # Normal import
                   12879:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12880:                            if (defined($token->[2]->{'id'})) {
                   12881:                               $unikey.='_'.$token->[2]->{'id'};
                   12882:                            }
1.1067    www      12883:                         }
                   12884: 
1.339     albertel 12885: 			if ($depthcount<20) {
1.736     albertel 12886: 			    my $metadata = 
1.1172.2.146.  .13(raeb 12887:-23): 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 12888: 					  $depthcount+1);
                   12889: 			    foreach my $meta (split(',',$metadata)) {
                   12890: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12891: 				$metathesekeys{$meta}=1;
1.339     albertel 12892: 			    }
1.1068    www      12893: 			
                   12894:                         }
1.1067    www      12895: 		    } else {
                   12896: #
                   12897: # Not importing, some other kind of non-package, non-library start tag
                   12898: # 
                   12899:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12900:                         if (defined($token->[2]->{'id'})) {
                   12901:                             $unikey.='_'.$token->[2]->{'id'};
                   12902:                         }
1.339     albertel 12903: 			if (defined($token->[2]->{'name'})) { 
                   12904: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12905: 			}
                   12906: 			$metathesekeys{$unikey}=1;
1.736     albertel 12907: 			foreach my $param (@{$token->[3]}) {
                   12908: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12909: 				$token->[2]->{$param};
1.339     albertel 12910: 			}
                   12911: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12912: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12913: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12914: 		 # only ws inside the tag, and not in default, so use default
                   12915: 		 # as value
1.599     albertel 12916: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12917: 			} elsif ( $internaltext =~ /\S/ ) {
                   12918: 		  # something interesting inside the tag
                   12919: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12920: 			} else {
1.908     albertel 12921: 		  # no interesting values, don't set a default
1.339     albertel 12922: 			}
1.172     www      12923: # end of not-a-package not-a-library import
1.339     albertel 12924: 		    }
1.172     www      12925: # end of not-a-package start tag
1.339     albertel 12926: 		}
1.172     www      12927: # the next is the end of "start tag"
1.339     albertel 12928: 	    }
                   12929: 	}
1.483     albertel 12930: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12931: 	$extension = lc($extension);
                   12932: 	if ($extension eq 'htm') { $extension='html'; }
                   12933: 
1.737     albertel 12934: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12935: 	    #no specific packages #how's our extension
                   12936: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12937: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12938: 					 \%metathesekeys);
                   12939: 	}
1.883     albertel 12940: 
                   12941: 	if (!exists($metaentry{':packages'})
                   12942: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12943: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12944: 		#no specific packages well let's get default then
                   12945: 		if ($key!~/^default&/) { next; }
1.488     albertel 12946: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12947: 					     \%metathesekeys);
                   12948: 	    }
                   12949: 	}
1.338     www      12950: # are there custom rights to evaluate
1.599     albertel 12951: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12952: 
1.338     www      12953:     #
                   12954:     # Importing a rights file here
1.339     albertel 12955:     #
                   12956: 	    unless ($depthcount) {
1.599     albertel 12957: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12958: 		my $dir=$filename;
                   12959: 		$dir=~s|[^/]*$||;
                   12960: 		$location=&filelocation($dir,$location);
1.736     albertel 12961: 		my $rights_metadata =
1.1172.2.146.  .13(raeb 12962:-23): 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 12963: 			      $depthcount+1);
                   12964: 		foreach my $rights (split(',',$rights_metadata)) {
                   12965: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12966: 		    $metathesekeys{$rights}=1;
1.339     albertel 12967: 		}
                   12968: 	    }
                   12969: 	}
1.737     albertel 12970: 	# uniqifiy package listing
                   12971: 	my %seen;
                   12972: 	my @uniq_packages =
                   12973: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12974: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12975: 
1.1172.2.99  raeburn  12976:         if (($importedresponses) || ($importedparts)) {
                   12977:             if ($importedparts) {
1.1070    www      12978: # We had imported parts and need to rebuild partorder
1.1172.2.99  raeburn  12979:                 $metaentry{':partorder'}='';
                   12980:                 $metathesekeys{'partorder'}=1;
                   12981:             }
                   12982:             if ($importedresponses) {
                   12983: # We had imported responses and need to rebuild responseorder
                   12984:                 $metaentry{':responseorder'}='';
                   12985:                 $metathesekeys{'responseorder'}=1;
                   12986:             }
                   12987:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12988:                 my $origid = $origfiletagids[$index+1];
                   12989:                 if ($origfiletagids[$index] eq 'part') {
                   12990: # Original part, part of the problem
                   12991:                     if ($importedparts) {
                   12992:                         $metaentry{':partorder'}.=','.$origid;
                   12993:                     }
                   12994:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12995:                     if ($importedparts) {
                   12996: # We have imported parts at this position
                   12997:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12998:                     }
                   12999:                     if ($importedresponses) {
                   13000: # We have imported responses at this position
                   13001:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   13002:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   13003:                         }
                   13004:                     }
                   13005:                 } else {
                   13006: # Original response item, part of the problem
                   13007:                     if ($importedresponses) {
                   13008:                         $metaentry{':responseorder'}.=','.$origid;
                   13009:                     }
                   13010:                 }
                   13011:             }
                   13012:             if ($importedparts) {
                   13013:                 $metaentry{':partorder'}=~s/^\,//;
                   13014:             }
                   13015:             if ($importedresponses) {
                   13016:                 $metaentry{':responseorder'}=~s/^\,//;
                   13017:             }
1.1070    www      13018:         }
                   13019: 
1.737     albertel 13020: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 13021: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1172.2.58  raeburn  13022: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 13023: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      13024: # this is the end of "was not already recently cached
1.71      www      13025:     }
1.599     albertel 13026:     return $metaentry{':'.$what};
1.261     albertel 13027: }
                   13028: 
1.488     albertel 13029: sub metadata_create_package_def {
1.483     albertel 13030:     my ($uri,$key,$package,$metathesekeys)=@_;
                   13031:     my ($pack,$name,$subp)=split(/\&/,$key);
                   13032:     if ($subp eq 'default') { next; }
                   13033:     
1.599     albertel 13034:     if (defined($metaentry{':packages'})) {
                   13035: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 13036:     } else {
1.599     albertel 13037: 	$metaentry{':packages'}=$package;
1.483     albertel 13038:     }
                   13039:     my $value=$packagetab{$key};
                   13040:     my $unikey;
                   13041:     $unikey='parameter_0_'.$name;
1.599     albertel 13042:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 13043:     $$metathesekeys{$unikey}=1;
1.599     albertel 13044:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   13045: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 13046:     }
1.599     albertel 13047:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   13048: 	$metaentry{':'.$unikey}=
                   13049: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 13050:     }
                   13051: }
                   13052: 
1.261     albertel 13053: sub metadata_generate_part0 {
                   13054:     my ($metadata,$metacache,$uri) = @_;
                   13055:     my %allnames;
1.737     albertel 13056:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 13057: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 13058: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   13059: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 13060: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 13061: 	    $allnames{$name}=$part;
                   13062: 	  }
                   13063: 	}
                   13064:     }
                   13065:     foreach my $name (keys(%allnames)) {
                   13066:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 13067:       my $key=":parameter_0_$name";
1.261     albertel 13068:       $$metacache{"$key.part"}='0';
                   13069:       $$metacache{"$key.name"}=$name;
1.428     albertel 13070:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 13071: 					   $allnames{$name}.'_'.$name.
                   13072: 					   '.type'};
1.428     albertel 13073:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 13074: 			     '.display'};
1.644     www      13075:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 13076:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 13077:       $$metacache{"$key.display"}=$olddis;
                   13078:     }
1.71      www      13079: }
                   13080: 
1.764     albertel 13081: # ------------------------------------------------------ Devalidate title cache
                   13082: 
                   13083: sub devalidate_title_cache {
                   13084:     my ($url)=@_;
                   13085:     if (!$env{'request.course.id'}) { return; }
                   13086:     my $symb=&symbread($url);
                   13087:     if (!$symb) { return; }
                   13088:     my $key=$env{'request.course.id'}."\0".$symb;
                   13089:     &devalidate_cache_new('title',$key);
                   13090: }
                   13091: 
1.1014    droeschl 13092: # ------------------------------------------------- Get the title of a course
                   13093: 
                   13094: sub current_course_title {
                   13095:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   13096: }
1.301     www      13097: # ------------------------------------------------- Get the title of a resource
                   13098: 
                   13099: sub gettitle {
                   13100:     my $urlsymb=shift;
                   13101:     my $symb=&symbread($urlsymb);
1.534     albertel 13102:     if ($symb) {
1.620     albertel 13103: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 13104: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 13105: 	if (defined($cached)) { 
                   13106: 	    return $result;
                   13107: 	}
1.534     albertel 13108: 	my ($map,$resid,$url)=&decode_symb($symb);
                   13109: 	my $title='';
1.907     albertel 13110: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   13111: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   13112: 	} else {
                   13113: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   13114: 		    &GDBM_READER(),0640)) {
                   13115: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   13116: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   13117: 		untie(%bighash);
                   13118: 	    }
1.534     albertel 13119: 	}
                   13120: 	$title=~s/\&colon\;/\:/gs;
                   13121: 	if ($title) {
1.1159    www      13122: # Remember both $symb and $title for dynamic metadata
                   13123:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      13124:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      13125: # Cache this title and then return it
1.599     albertel 13126: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 13127: 	}
                   13128: 	$urlsymb=$url;
                   13129:     }
                   13130:     my $title=&metadata($urlsymb,'title');
                   13131:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   13132:     return $title;
1.301     www      13133: }
1.613     albertel 13134: 
1.614     albertel 13135: sub get_slot {
                   13136:     my ($which,$cnum,$cdom)=@_;
                   13137:     if (!$cnum || !$cdom) {
1.790     albertel 13138: 	(undef,my $courseid)=&whichuser();
1.620     albertel 13139: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   13140: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 13141:     }
1.703     albertel 13142:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   13143:     my %slotinfo;
                   13144:     if (exists($remembered{$key})) {
                   13145: 	$slotinfo{$which} = $remembered{$key};
                   13146:     } else {
                   13147: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   13148: 	&Apache::lonhomework::showhash(%slotinfo);
                   13149: 	my ($tmp)=keys(%slotinfo);
                   13150: 	if ($tmp=~/^error:/) { return (); }
                   13151: 	$remembered{$key} = $slotinfo{$which};
                   13152:     }
1.616     albertel 13153:     if (ref($slotinfo{$which}) eq 'HASH') {
                   13154: 	return %{$slotinfo{$which}};
                   13155:     }
                   13156:     return $slotinfo{$which};
1.614     albertel 13157: }
1.1150    raeburn  13158: 
                   13159: sub get_reservable_slots {
                   13160:     my ($cnum,$cdom,$uname,$udom) = @_;
                   13161:     my $now = time;
                   13162:     my $reservable_info;
                   13163:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   13164:     if (exists($remembered{$key})) {
                   13165:         $reservable_info = $remembered{$key};
                   13166:     } else {
                   13167:         my %resv;
                   13168:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   13169:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   13170:         $reservable_info = \%resv;
                   13171:         $remembered{$key} = $reservable_info;
                   13172:     }
                   13173:     return $reservable_info;
                   13174: }
                   13175: 
                   13176: sub get_course_slots {
                   13177:     my ($cnum,$cdom) = @_;
                   13178:     my $hashid=$cnum.':'.$cdom;
                   13179:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   13180:     if (defined($cached)) {
                   13181:         if (ref($result) eq 'HASH') {
                   13182:             return %{$result};
                   13183:         }
                   13184:     } else {
                   13185:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   13186:         my ($tmp) = keys(%slots);
                   13187:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1172.2.23  raeburn  13188:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  13189:             return %slots;
                   13190:         }
                   13191:     }
                   13192:     return;
                   13193: }
                   13194: 
                   13195: sub devalidate_slots_cache {
                   13196:     my ($cnum,$cdom)=@_;
                   13197:     my $hashid=$cnum.':'.$cdom;
                   13198:     &devalidate_cache_new('allslots',$hashid);
                   13199: }
                   13200: 
1.1172.2.8  raeburn  13201: sub get_coursechange {
                   13202:     my ($cdom,$cnum) = @_;
                   13203:     if ($cdom eq '' || $cnum eq '') {
                   13204:         return unless ($env{'request.course.id'});
                   13205:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   13206:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   13207:     }
                   13208:     my $hashid=$cdom.'_'.$cnum;
                   13209:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   13210:     if ((defined($cached)) && ($change ne '')) {
                   13211:         return $change;
                   13212:     } else {
                   13213:         my %crshash;
                   13214:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   13215:         if ($crshash{'internal.contentchange'} eq '') {
                   13216:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   13217:             if ($change eq '') {
                   13218:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   13219:                 $change = $crshash{'internal.created'};
                   13220:             }
                   13221:         } else {
                   13222:             $change = $crshash{'internal.contentchange'};
                   13223:         }
                   13224:         my $cachetime = 600;
                   13225:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   13226:     }
                   13227:     return $change;
                   13228: }
                   13229: 
                   13230: sub devalidate_coursechange_cache {
1.1172.2.146.  .9(raebu 13231:23):     my ($cdom,$cnum)=@_;
                   13232:23):     my $hashid=$cdom.'_'.$cnum;
1.1172.2.8  raeburn  13233:     &devalidate_cache_new('crschange',$hashid);
                   13234: }
                   13235: 
1.1172.2.146.  .9(raebu 13236:23): sub get_suppchange {
                   13237:23):     my ($cdom,$cnum) = @_;
                   13238:23):     if ($cdom eq '' || $cnum eq '') {
                   13239:23):         return unless ($env{'request.course.id'});
                   13240:23):         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   13241:23):         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   13242:23):     }
                   13243:23):     my $hashid=$cdom.'_'.$cnum;
                   13244:23):     my ($change,$cached)=&is_cached_new('suppchange',$hashid);
                   13245:23):     if ((defined($cached)) && ($change ne '')) {
                   13246:23):         return $change;
                   13247:23):     } else {
                   13248:23):         my %crshash = &get('environment',['internal.supplementalchange'],$cdom,$cnum);
                   13249:23):         if ($crshash{'internal.supplementalchange'} eq '') {
                   13250:23):             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   13251:23):             if ($change eq '') {
                   13252:23):                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   13253:23):                 $change = $crshash{'internal.created'};
                   13254:23):             }
                   13255:23):         } else {
                   13256:23):             $change = $crshash{'internal.supplementalchange'};
                   13257:23):         }
                   13258:23):         my $cachetime = 600;
                   13259:23):         &do_cache_new('suppchange',$hashid,$change,$cachetime);
                   13260:23):     }
                   13261:23):     return $change;
                   13262:23): }
                   13263:23): 
                   13264:23): sub devalidate_suppchange_cache {
                   13265:23):     my ($cdom,$cnum)=@_;
                   13266:23):     my $hashid=$cdom.'_'.$cnum;
                   13267:23):     &devalidate_cache_new('suppchange',$hashid);
                   13268:23): }
                   13269:23): 
                   13270:23): sub update_supp_caches {
                   13271:23):     my ($cdom,$cnum) = @_;
                   13272:23):     my %servers = &internet_dom_servers($cdom);
                   13273:23):     my @ids=&current_machine_ids();
                   13274:23):     foreach my $server (keys(%servers)) {
                   13275:23):         next if (grep(/^\Q$server\E$/,@ids));
                   13276:23):         my $hashid=$cnum.':'.$cdom;
                   13277:23):         my $cachekey = &escape('showsupp').':'.&escape($hashid);
                   13278:23):         &remote_devalidate_cache($server,[$cachekey]);
                   13279:23):     }
                   13280:23):     &has_unhidden_suppfiles($cnum,$cdom,1,1);
                   13281:23):     &count_supptools($cnum,$cdom,1);
                   13282:23):     my $now = time;
                   13283:23):     if ($env{'request.course.id'} eq $cdom.'_'.$cnum) {
                   13284:23):         &Apache::lonnet::appenv({'request.course.suppupdated' => $now});
                   13285:23):     }
                   13286:23):     &put('environment',{'internal.supplementalchange' => $now},
                   13287:23):          $cdom,$cnum);
                   13288:23):     &Apache::lonnet::appenv(
                   13289:23):         {'course.'.$cdom.'_'.$cnum.'.internal.supplementalchange' => $now});
                   13290:23):     &do_cache_new('suppchange',$cdom.'_'.$cnum,$now,600);
                   13291:23): }
                   13292:23): 
1.31      www      13293: # ------------------------------------------------- Update symbolic store links
                   13294: 
                   13295: sub symblist {
                   13296:     my ($mapname,%newhash)=@_;
1.438     www      13297:     $mapname=&deversion(&declutter($mapname));
1.31      www      13298:     my %hash;
1.620     albertel 13299:     if (($env{'request.course.fn'}) && (%newhash)) {
                   13300:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 13301:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  13302: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 13303: 		next if ($url eq 'last_known'
                   13304: 			 && $env{'form.no_update_last_known'});
                   13305: 		$hash{declutter($url)}=&encode_symb($mapname,
                   13306: 						    $newhash{$url}->[1],
                   13307: 						    $newhash{$url}->[0]);
1.191     harris41 13308:             }
1.31      www      13309:             if (untie(%hash)) {
                   13310: 		return 'ok';
                   13311:             }
                   13312:         }
                   13313:     }
                   13314:     return 'error';
1.212     www      13315: }
                   13316: 
                   13317: # --------------------------------------------------------------- Verify a symb
                   13318: 
                   13319: sub symbverify {
1.1172.2.11  raeburn  13320:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      13321:     my $thisfn=$thisurl;
1.439     www      13322:     $thisfn=&declutter($thisfn);
1.215     www      13323: # direct jump to resource in page or to a sequence - will construct own symbs
                   13324:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   13325: # check URL part
1.409     www      13326:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      13327: 
1.431     www      13328:     unless ($url eq $thisfn) { return 0; }
1.213     www      13329: 
1.216     www      13330:     $symb=&symbclean($symb);
1.510     www      13331:     $thisurl=&deversion($thisurl);
1.439     www      13332:     $thisfn=&deversion($thisfn);
1.213     www      13333: 
                   13334:     my %bighash;
                   13335:     my $okay=0;
1.431     www      13336: 
1.620     albertel 13337:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13338:                             &GDBM_READER(),0640)) {
1.1032    raeburn  13339:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   13340:             $thisurl =~ s/\?.+$//;
1.1172.2.13  raeburn  13341:             if ($map =~ m{^uploaded/.+\.page$}) {
                   13342:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   13343:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   13344:             }
                   13345:         }
                   13346:         my $ids;
1.1172.2.122  raeburn  13347:         if ($map =~ m{^uploaded/.+\.page$}) {
                   13348:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1172.2.13  raeburn  13349:         } else {
                   13350:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  13351:         }
1.1102    raeburn  13352:         unless ($ids) {
1.1172.2.13  raeburn  13353:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
1.1102    raeburn  13354:             $ids=$bighash{$idkey};
1.216     www      13355:         }
                   13356:         if ($ids) {
                   13357: # ------------------------------------------------------------------- Has ID(s)
1.1172.2.13  raeburn  13358:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   13359:                 $symb =~ s/\?.+$//;
                   13360:             }
1.800     albertel 13361: 	    foreach my $id (split(/\,/,$ids)) {
                   13362: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      13363:                if (
                   13364:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1172.2.13  raeburn  13365:    eq $symb) {
1.1172.2.11  raeburn  13366:                    if (ref($encstate)) {
                   13367:                        $$encstate = $bighash{'encrypted_'.$id};
                   13368:                    }
1.1172.2.13  raeburn  13369:                    if (($env{'request.role.adv'}) ||
                   13370:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
1.1101    raeburn  13371:                        ($thisurl eq '/adm/navmaps')) {
1.1172.2.13  raeburn  13372:                        $okay=1;
                   13373:                        last;
                   13374:                    }
                   13375:                }
                   13376:            }
1.216     www      13377:         }
1.213     www      13378: 	untie(%bighash);
                   13379:     }
                   13380:     return $okay;
1.31      www      13381: }
                   13382: 
1.210     www      13383: # --------------------------------------------------------------- Clean-up symb
                   13384: 
                   13385: sub symbclean {
                   13386:     my $symb=shift;
1.568     albertel 13387:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      13388: # remove version from map
                   13389:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      13390: 
1.210     www      13391: # remove version from URL
                   13392:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      13393: 
1.507     www      13394: # remove wrapper
                   13395: 
1.510     www      13396:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 13397:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      13398:     return $symb;
1.409     www      13399: }
                   13400: 
                   13401: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 13402: 
                   13403: sub encode_symb {
                   13404:     my ($map,$resid,$url)=@_;
                   13405:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   13406: }
1.409     www      13407: 
                   13408: sub decode_symb {
1.568     albertel 13409:     my $symb=shift;
                   13410:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   13411:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      13412:     return (&fixversion($map),$resid,&fixversion($url));
                   13413: }
                   13414: 
                   13415: sub fixversion {
                   13416:     my $fn=shift;
1.609     banghart 13417:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      13418:     my %bighash;
                   13419:     my $uri=&clutter($fn);
1.620     albertel 13420:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      13421: # is this cached?
1.599     albertel 13422:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      13423:     if (defined($cached)) { return $result; }
                   13424: # unfortunately not cached, or expired
1.620     albertel 13425:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      13426: 	    &GDBM_READER(),0640)) {
                   13427:  	if ($bighash{'version_'.$uri}) {
                   13428:  	    my $version=$bighash{'version_'.$uri};
1.444     www      13429:  	    unless (($version eq 'mostrecent') || 
                   13430: 		    ($version==&getversion($uri))) {
1.440     www      13431:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   13432:  	    }
                   13433:  	}
                   13434:  	untie %bighash;
1.413     www      13435:     }
1.599     albertel 13436:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      13437: }
                   13438: 
                   13439: sub deversion {
                   13440:     my $url=shift;
                   13441:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   13442:     return $url;
1.210     www      13443: }
                   13444: 
1.31      www      13445: # ------------------------------------------------------ Return symb list entry
                   13446: 
                   13447: sub symbread {
1.1172.2.126  raeburn  13448:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1172.2.128  raeburn  13449:         $ignoresymbdb,$noenccheck)=@_;
1.1172.2.54  raeburn  13450:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1172.2.128  raeburn  13451:     if (defined($env{$cache_str})) {
1.1172.2.126  raeburn  13452:         unless (ref($possibles) eq 'HASH') {
                   13453:             if ($ignorecachednull) {
                   13454:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   13455:             } else {
                   13456:                 return $env{$cache_str};
                   13457:             }
1.1172.2.66  raeburn  13458:         }
                   13459:     }
1.242     www      13460: # no filename provided? try from environment
1.1172.2.54  raeburn  13461:     unless ($thisfn) {
1.620     albertel 13462:         if ($env{'request.symb'}) {
1.1172.2.128  raeburn  13463:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.1172.2.13  raeburn  13464:         }
                   13465:         $thisfn=$env{'request.filename'};
1.44      www      13466:     }
1.569     albertel 13467:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      13468: # is that filename actually a symb? Verify, clean, and return
                   13469:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 13470: 	if (&symbverify($thisfn,$1)) {
1.1172.2.128  raeburn  13471: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 13472: 	}
1.242     www      13473:     }
1.44      www      13474:     $thisfn=declutter($thisfn);
1.31      www      13475:     my %hash;
1.37      www      13476:     my %bighash;
                   13477:     my $syval='';
1.620     albertel 13478:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.1172.2.128  raeburn  13479:         unless ($ignoresymbdb) {
1.1172.2.126  raeburn  13480:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   13481:                           &GDBM_READER(),0640)) {
1.1172.2.146.  .7(raebu 13482:22): 	        $syval=$hash{$thisfn};
1.1172.2.126  raeburn  13483:                 untie(%hash);
                   13484:             }
1.1172.2.128  raeburn  13485:             if ($syval && $checkforblock) {
                   13486:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1172.2.126  raeburn  13487:                 if (@blockers) {
                   13488:                     $syval='';
                   13489:                 }
                   13490:             }
1.37      www      13491:         }
                   13492: # ---------------------------------------------------------- There was an entry
                   13493:         if ($syval) {
1.601     albertel 13494: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 13495: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  13496: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13497: 		    #return $env{$cache_str}='';
1.601     albertel 13498: 		#}    
                   13499: 		#$syval.=$1;
                   13500: 	    #}
1.37      www      13501:         } else {
                   13502: # ------------------------------------------------------- Was not in symb table
1.620     albertel 13503:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13504:                             &GDBM_READER(),0640)) {
1.37      www      13505: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      13506:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      13507:               unless ($ids) { 
                   13508:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      13509:               }
                   13510:               unless ($ids) {
                   13511: # alias?
                   13512: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      13513:               }
1.37      www      13514:               if ($ids) {
                   13515: # ------------------------------------------------------------------- Has ID(s)
                   13516:                  my @possibilities=split(/\,/,$ids);
1.39      www      13517:                  if ($#possibilities==0) {
                   13518: # ----------------------------------------------- There is only one possibility
1.37      www      13519: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 13520: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13521: 						    $resid,$thisfn);
1.1172.2.66  raeburn  13522:                      if (ref($possibles) eq 'HASH') {
1.1172.2.126  raeburn  13523:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   13524:                              $possibles->{$syval} = 1;
                   13525:                          }
1.1172.2.66  raeburn  13526:                      }
                   13527:                      if ($checkforblock) {
1.1172.2.126  raeburn  13528:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1172.2.127  raeburn  13529:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1172.2.126  raeburn  13530:                              if (@blockers) {
                   13531:                                  $syval = '';
                   13532:                                  untie(%bighash);
                   13533:                                  return $env{$cache_str}='';
                   13534:                              }
1.1172.2.66  raeburn  13535:                          }
                   13536:                      }
                   13537:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
1.39      www      13538: # ------------------------------------------ There is more than one possibility
                   13539:                      my $realpossible=0;
1.800     albertel 13540:                      foreach my $id (@possibilities) {
                   13541: 			 my $file=$bighash{'src_'.$id};
1.1172.2.66  raeburn  13542:                          my $canaccess;
                   13543:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   13544:                              $canaccess = 1;
                   13545:                          } else {
                   13546:                              $canaccess = &allowed('bre',$file);
                   13547:                          }
                   13548:                          if ($canaccess) {
                   13549:          		     my ($mapid,$resid)=split(/\./,$id);
                   13550:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   13551:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13552:                                                              $resid,$thisfn);
1.1172.2.126  raeburn  13553:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1172.2.127  raeburn  13554:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1172.2.66  raeburn  13555:                                  if ($checkforblock) {
1.1172.2.127  raeburn  13556:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1172.2.126  raeburn  13557:                                      if (@blockers > 0) {
                   13558:                                          $syval = '';
                   13559:                                      } else {
1.1172.2.66  raeburn  13560:                                          $syval = $poss_syval;
                   13561:                                          $realpossible++;
                   13562:                                      }
                   13563:                                  } else {
                   13564:                                      $syval = $poss_syval;
                   13565:                                      $realpossible++;
                   13566:                                  }
1.1172.2.126  raeburn  13567:                                  if ($syval) {
                   13568:                                      if (ref($possibles) eq 'HASH') {
                   13569:                                          $possibles->{$syval} = 1;
                   13570:                                      }
                   13571:                                  }
1.1172.2.66  raeburn  13572:                              }
1.39      www      13573: 			 }
1.191     harris41 13574:                      }
1.39      www      13575: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      13576:                  } else {
                   13577:                      $syval='';
1.37      www      13578:                  }
                   13579: 	      }
1.1172.2.66  raeburn  13580:               untie(%bighash);
1.481     raeburn  13581:            }
1.31      www      13582:         }
1.62      www      13583:         if ($syval) {
1.1172.2.128  raeburn  13584: 	    return $env{$cache_str}=$syval;
1.62      www      13585:         }
1.31      www      13586:     }
1.949     raeburn  13587:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13588:     return $env{$cache_str}='';
1.31      www      13589: }
                   13590: 
                   13591: # ---------------------------------------------------------- Return random seed
                   13592: 
1.32      www      13593: sub numval {
                   13594:     my $txt=shift;
                   13595:     $txt=~tr/A-J/0-9/;
                   13596:     $txt=~tr/a-j/0-9/;
                   13597:     $txt=~tr/K-T/0-9/;
                   13598:     $txt=~tr/k-t/0-9/;
                   13599:     $txt=~tr/U-Z/0-5/;
                   13600:     $txt=~tr/u-z/0-5/;
                   13601:     $txt=~s/\D//g;
1.564     albertel 13602:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      13603:     return int($txt);
1.368     albertel 13604: }
                   13605: 
1.484     albertel 13606: sub numval2 {
                   13607:     my $txt=shift;
                   13608:     $txt=~tr/A-J/0-9/;
                   13609:     $txt=~tr/a-j/0-9/;
                   13610:     $txt=~tr/K-T/0-9/;
                   13611:     $txt=~tr/k-t/0-9/;
                   13612:     $txt=~tr/U-Z/0-5/;
                   13613:     $txt=~tr/u-z/0-5/;
                   13614:     $txt=~s/\D//g;
                   13615:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13616:     my $total;
                   13617:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 13618:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 13619:     return int($total);
                   13620: }
                   13621: 
1.575     albertel 13622: sub numval3 {
                   13623:     use integer;
                   13624:     my $txt=shift;
                   13625:     $txt=~tr/A-J/0-9/;
                   13626:     $txt=~tr/a-j/0-9/;
                   13627:     $txt=~tr/K-T/0-9/;
                   13628:     $txt=~tr/k-t/0-9/;
                   13629:     $txt=~tr/U-Z/0-5/;
                   13630:     $txt=~tr/u-z/0-5/;
                   13631:     $txt=~s/\D//g;
                   13632:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13633:     my $total;
                   13634:     foreach my $val (@txts) { $total+=$val; }
                   13635:     if ($_64bit) { $total=(($total<<32)>>32); }
                   13636:     return $total;
                   13637: }
                   13638: 
1.675     albertel 13639: sub digest {
                   13640:     my ($data)=@_;
                   13641:     my $digest=&Digest::MD5::md5($data);
                   13642:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   13643:     my ($e,$f);
                   13644:     {
                   13645:         use integer;
                   13646:         $e=($a+$b);
                   13647:         $f=($c+$d);
                   13648:         if ($_64bit) {
                   13649:             $e=(($e<<32)>>32);
                   13650:             $f=(($f<<32)>>32);
                   13651:         }
                   13652:     }
                   13653:     if (wantarray) {
                   13654: 	return ($e,$f);
                   13655:     } else {
                   13656: 	my $g;
                   13657: 	{
                   13658: 	    use integer;
                   13659: 	    $g=($e+$f);
                   13660: 	    if ($_64bit) {
                   13661: 		$g=(($g<<32)>>32);
                   13662: 	    }
                   13663: 	}
                   13664: 	return $g;
                   13665:     }
                   13666: }
                   13667: 
1.368     albertel 13668: sub latest_rnd_algorithm_id {
1.675     albertel 13669:     return '64bit5';
1.366     albertel 13670: }
1.32      www      13671: 
1.503     albertel 13672: sub get_rand_alg {
                   13673:     my ($courseid)=@_;
1.790     albertel 13674:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 13675:     if ($courseid) {
1.620     albertel 13676: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 13677:     }
                   13678:     return &latest_rnd_algorithm_id();
                   13679: }
                   13680: 
1.562     albertel 13681: sub validCODE {
                   13682:     my ($CODE)=@_;
                   13683:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   13684:     return 0;
                   13685: }
                   13686: 
1.491     albertel 13687: sub getCODE {
1.620     albertel 13688:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 13689:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   13690: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   13691: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 13692: 	return $Apache::lonhomework::history{'resource.CODE'};
                   13693:     }
                   13694:     return undef;
                   13695: }
1.1133    foxr     13696: #
                   13697: #  Determines the random seed for a specific context:
                   13698: #
                   13699: # parameters:
                   13700: #   symb      - in course context the symb for the seed.
                   13701: #   course_id - The course id of the form domain_coursenum.
                   13702: #   domain    - Domain for the user.
                   13703: #   course    - Course for the user.
                   13704: #   cenv      - environment of the course.
                   13705: #
                   13706: # NOTE:
                   13707: #   All parameters are picked out of the environment if missing
                   13708: #   or not defined.
                   13709: #   If a symb cannot be determined the current time is used instead.
                   13710: #
                   13711: #  For a given well defined symb, courside, domain, username,
                   13712: #  and course environment, the seed is reproducible.
                   13713: #
1.31      www      13714: sub rndseed {
1.1133    foxr     13715:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 13716:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 13717:     if (!defined($symb)) {
1.366     albertel 13718: 	unless ($symb=$wsymb) { return time; }
                   13719:     }
1.1146    foxr     13720:     if (!defined $courseid) { 
                   13721: 	$courseid=$wcourseid; 
                   13722:     }
                   13723:     if (!defined $domain) { $domain=$wdomain; }
                   13724:     if (!defined $username) { $username=$wusername }
1.1133    foxr     13725: 
                   13726:     my $which;
                   13727:     if (defined($cenv->{'rndseed'})) {
                   13728: 	$which = $cenv->{'rndseed'};
                   13729:     } else {
                   13730: 	$which =&get_rand_alg($courseid);
                   13731:     }
1.491     albertel 13732:     if (defined(&getCODE())) {
1.675     albertel 13733: 	if ($which eq '64bit5') {
                   13734: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   13735: 	} elsif ($which eq '64bit4') {
1.575     albertel 13736: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   13737: 	} else {
                   13738: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   13739: 	}
1.675     albertel 13740:     } elsif ($which eq '64bit5') {
                   13741: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 13742:     } elsif ($which eq '64bit4') {
                   13743: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 13744:     } elsif ($which eq '64bit3') {
                   13745: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 13746:     } elsif ($which eq '64bit2') {
                   13747: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 13748:     } elsif ($which eq '64bit') {
                   13749: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   13750:     }
                   13751:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   13752: }
                   13753: 
                   13754: sub rndseed_32bit {
                   13755:     my ($symb,$courseid,$domain,$username)=@_;
                   13756:     {
                   13757: 	use integer;
                   13758: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   13759: 	my $symbseed=numval($symb) << 22;
                   13760: 	my $namechck=unpack("%32C*",$username) << 17;
                   13761: 	my $nameseed=numval($username) << 12;
                   13762: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   13763: 	my $courseseed=unpack("%32C*",$courseid);
                   13764: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 13765: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13766: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13767: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 13768: 	return $num;
                   13769:     }
                   13770: }
                   13771: 
                   13772: sub rndseed_64bit {
                   13773:     my ($symb,$courseid,$domain,$username)=@_;
                   13774:     {
                   13775: 	use integer;
                   13776: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   13777: 	my $symbseed=numval($symb) << 10;
                   13778: 	my $namechck=unpack("%32S*",$username);
                   13779: 	
                   13780: 	my $nameseed=numval($username) << 21;
                   13781: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   13782: 	my $courseseed=unpack("%32S*",$courseid);
                   13783: 	
                   13784: 	my $num1=$symbchck+$symbseed+$namechck;
                   13785: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13786: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13787: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 13788: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 13789: 	return "$num1,$num2";
1.155     albertel 13790:     }
1.366     albertel 13791: }
                   13792: 
1.443     albertel 13793: sub rndseed_64bit2 {
                   13794:     my ($symb,$courseid,$domain,$username)=@_;
                   13795:     {
                   13796: 	use integer;
                   13797: 	# strings need to be an even # of cahracters long, it it is odd the
                   13798:         # last characters gets thrown away
                   13799: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13800: 	my $symbseed=numval($symb) << 10;
                   13801: 	my $namechck=unpack("%32S*",$username.' ');
                   13802: 	
                   13803: 	my $nameseed=numval($username) << 21;
1.501     albertel 13804: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13805: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13806: 	
                   13807: 	my $num1=$symbchck+$symbseed+$namechck;
                   13808: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13809: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13810: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 13811: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 13812: 	return "$num1,$num2";
                   13813:     }
                   13814: }
                   13815: 
                   13816: sub rndseed_64bit3 {
                   13817:     my ($symb,$courseid,$domain,$username)=@_;
                   13818:     {
                   13819: 	use integer;
                   13820: 	# strings need to be an even # of cahracters long, it it is odd the
                   13821:         # last characters gets thrown away
                   13822: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13823: 	my $symbseed=numval2($symb) << 10;
                   13824: 	my $namechck=unpack("%32S*",$username.' ');
                   13825: 	
                   13826: 	my $nameseed=numval2($username) << 21;
1.443     albertel 13827: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13828: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13829: 	
                   13830: 	my $num1=$symbchck+$symbseed+$namechck;
                   13831: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13832: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13833: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 13834: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13835: 	
1.503     albertel 13836: 	return "$num1:$num2";
1.443     albertel 13837:     }
                   13838: }
                   13839: 
1.575     albertel 13840: sub rndseed_64bit4 {
                   13841:     my ($symb,$courseid,$domain,$username)=@_;
                   13842:     {
                   13843: 	use integer;
                   13844: 	# strings need to be an even # of cahracters long, it it is odd the
                   13845:         # last characters gets thrown away
                   13846: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   13847: 	my $symbseed=numval3($symb) << 10;
                   13848: 	my $namechck=unpack("%32S*",$username.' ');
                   13849: 	
                   13850: 	my $nameseed=numval3($username) << 21;
                   13851: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   13852: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13853: 	
                   13854: 	my $num1=$symbchck+$symbseed+$namechck;
                   13855: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 13856: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   13857: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 13858: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      13859: 	
1.575     albertel 13860: 	return "$num1:$num2";
                   13861:     }
                   13862: }
                   13863: 
1.675     albertel 13864: sub rndseed_64bit5 {
                   13865:     my ($symb,$courseid,$domain,$username)=@_;
                   13866:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   13867:     return "$num1:$num2";
                   13868: }
                   13869: 
1.366     albertel 13870: sub rndseed_CODE_64bit {
                   13871:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 13872:     {
1.366     albertel 13873: 	use integer;
1.443     albertel 13874: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 13875: 	my $symbseed=numval2($symb);
1.491     albertel 13876: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13877: 	my $CODEseed=numval(&getCODE());
1.443     albertel 13878: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 13879: 	my $num1=$symbseed+$CODEchck;
                   13880: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13881: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13882: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 13883: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13884: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 13885: 	return "$num1:$num2";
1.366     albertel 13886:     }
                   13887: }
                   13888: 
1.575     albertel 13889: sub rndseed_CODE_64bit4 {
                   13890:     my ($symb,$courseid,$domain,$username)=@_;
                   13891:     {
                   13892: 	use integer;
                   13893: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   13894: 	my $symbseed=numval3($symb);
                   13895: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   13896: 	my $CODEseed=numval3(&getCODE());
                   13897: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   13898: 	my $num1=$symbseed+$CODEchck;
                   13899: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 13900: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   13901: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 13902: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   13903: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   13904: 	return "$num1:$num2";
                   13905:     }
                   13906: }
                   13907: 
1.675     albertel 13908: sub rndseed_CODE_64bit5 {
                   13909:     my ($symb,$courseid,$domain,$username)=@_;
                   13910:     my $code = &getCODE();
                   13911:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   13912:     return "$num1:$num2";
                   13913: }
                   13914: 
1.366     albertel 13915: sub setup_random_from_rndseed {
                   13916:     my ($rndseed)=@_;
1.503     albertel 13917:     if ($rndseed =~/([,:])/) {
1.1172.2.51  raeburn  13918: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13919:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13920:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13921:         } else {
                   13922:             &Math::Random::random_set_seed($num1,$num2);
                   13923:         }
1.366     albertel 13924:     } else {
                   13925: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13926:     }
1.36      albertel 13927: }
                   13928: 
1.474     albertel 13929: sub latest_receipt_algorithm_id {
1.835     albertel 13930:     return 'receipt3';
1.474     albertel 13931: }
                   13932: 
1.480     www      13933: sub recunique {
                   13934:     my $fucourseid=shift;
                   13935:     my $unique;
1.835     albertel 13936:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13937: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13938: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13939:     } else {
                   13940: 	$unique=$perlvar{'lonReceipt'};
                   13941:     }
                   13942:     return unpack("%32C*",$unique);
                   13943: }
                   13944: 
                   13945: sub recprefix {
                   13946:     my $fucourseid=shift;
                   13947:     my $prefix;
1.835     albertel 13948:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13949: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13950: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13951:     } else {
                   13952: 	$prefix=$perlvar{'lonHostID'};
                   13953:     }
                   13954:     return unpack("%32C*",$prefix);
                   13955: }
                   13956: 
1.76      www      13957: sub ireceipt {
1.474     albertel 13958:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13959: 
                   13960:     my $return =&recprefix($fucourseid).'-';
                   13961: 
                   13962:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13963: 	$env{'request.state'} eq 'construct') {
                   13964: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13965: 	return $return;
                   13966:     }
                   13967: 
1.76      www      13968:     my $cuname=unpack("%32C*",$funame);
                   13969:     my $cudom=unpack("%32C*",$fudom);
                   13970:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13971:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13972:     my $cunique=&recunique($fucourseid);
1.474     albertel 13973:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13974:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13975: 
1.790     albertel 13976: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13977: 			       
                   13978: 	$return.= ($cunique%$cuname+
                   13979: 		   $cunique%$cudom+
                   13980: 		   $cusymb%$cuname+
                   13981: 		   $cusymb%$cudom+
                   13982: 		   $cucourseid%$cuname+
                   13983: 		   $cucourseid%$cudom+
                   13984: 		   $cpart%$cuname+
                   13985: 		   $cpart%$cudom);
                   13986:     } else {
                   13987: 	$return.= ($cunique%$cuname+
                   13988: 		   $cunique%$cudom+
                   13989: 		   $cusymb%$cuname+
                   13990: 		   $cusymb%$cudom+
                   13991: 		   $cucourseid%$cuname+
                   13992: 		   $cucourseid%$cudom);
                   13993:     }
                   13994:     return $return;
1.76      www      13995: }
                   13996: 
                   13997: sub receipt {
1.474     albertel 13998:     my ($part)=@_;
1.790     albertel 13999:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 14000:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      14001: }
1.260     ng       14002: 
1.790     albertel 14003: sub whichuser {
                   14004:     my ($passedsymb)=@_;
                   14005:     my ($symb,$courseid,$domain,$name,$publicuser);
                   14006:     if (defined($env{'form.grade_symb'})) {
                   14007: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   14008: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   14009: 	if (!$allowed &&
                   14010: 	    exists($env{'request.course.sec'}) &&
                   14011: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   14012: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   14013: 			      '/'.$env{'request.course.sec'});
                   14014: 	}
                   14015: 	if ($allowed) {
                   14016: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   14017: 	    $courseid=$tmp_courseid;
                   14018: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   14019: 	    ($name)=&get_env_multiple('form.grade_username');
                   14020: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   14021: 	}
                   14022:     }
                   14023:     if (!$passedsymb) {
                   14024: 	$symb=&symbread();
                   14025:     } else {
                   14026: 	$symb=$passedsymb;
                   14027:     }
                   14028:     $courseid=$env{'request.course.id'};
                   14029:     $domain=$env{'user.domain'};
                   14030:     $name=$env{'user.name'};
                   14031:     if ($name eq 'public' && $domain eq 'public') {
                   14032: 	if (!defined($env{'form.username'})) {
                   14033: 	    $env{'form.username'}.=time.rand(10000000);
                   14034: 	}
                   14035: 	$name.=$env{'form.username'};
                   14036:     }
                   14037:     return ($symb,$courseid,$domain,$name,$publicuser);
                   14038: 
                   14039: }
                   14040: 
1.36      albertel 14041: # ------------------------------------------------------------ Serves up a file
1.472     albertel 14042: # returns either the contents of the file or 
                   14043: # -1 if the file doesn't exist
1.481     raeburn  14044: #
                   14045: # if the target is a file that was uploaded via DOCS, 
                   14046: # a check will be made to see if a current copy exists on the local server,
                   14047: # if it does this will be served, otherwise a copy will be retrieved from
                   14048: # the home server for the course and stored in /home/httpd/html/userfiles on
                   14049: # the local server.   
1.472     albertel 14050: 
1.36      albertel 14051: sub getfile {
1.538     albertel 14052:     my ($file) = @_;
1.609     banghart 14053:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 14054:     &repcopy($file);
                   14055:     return &readfile($file);
                   14056: }
                   14057: 
                   14058: sub repcopy_userfile {
                   14059:     my ($file)=@_;
1.1142    raeburn  14060:     my $londocroot = $perlvar{'lonDocRoot'};
                   14061:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  14062:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 14063:     my ($cdom,$cnum,$filename) = 
1.811     albertel 14064: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 14065:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   14066:     if (-e "$file") {
1.828     www      14067: # we already have a local copy, check it out
1.538     albertel 14068: 	my @fileinfo = stat($file);
1.828     www      14069: 	my $rtncode;
                   14070: 	my $info;
1.538     albertel 14071: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 14072: 	if ($lwpresp ne 'ok') {
1.828     www      14073: # there is no such file anymore, even though we had a local copy
1.482     albertel 14074: 	    if ($rtncode eq '404') {
1.538     albertel 14075: 		unlink($file);
1.482     albertel 14076: 	    }
                   14077: 	    return -1;
                   14078: 	}
                   14079: 	if ($info < $fileinfo[9]) {
1.828     www      14080: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  14081: 	    return 'ok';
1.828     www      14082: 	} else {
                   14083: # the file is outdated, get rid of it
                   14084: 	    unlink($file);
1.482     albertel 14085: 	}
1.828     www      14086:     }
                   14087: # one way or the other, at this point, we don't have the file
                   14088: # construct the correct path for the file
                   14089:     my @parts = ($cdom,$cnum); 
                   14090:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   14091: 	push @parts, split(/\//,$1);
                   14092:     }
                   14093:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   14094:     foreach my $part (@parts) {
                   14095: 	$path .= '/'.$part;
                   14096: 	if (!-e $path) {
                   14097: 	    mkdir($path,0770);
1.482     albertel 14098: 	}
                   14099:     }
1.828     www      14100: # now the path exists for sure
                   14101: # get a user agent
                   14102:     my $ua=new LWP::UserAgent;
                   14103:     my $transferfile=$file.'.in.transfer';
                   14104: # FIXME: this should flock
                   14105:     if (-e $transferfile) { return 'ok'; }
                   14106:     my $request;
                   14107:     $uri=~s/^\///;
1.980     raeburn  14108:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  14109:     my $hostname = &hostname($homeserver);
1.980     raeburn  14110:     my $protocol = $protocol{$homeserver};
                   14111:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  14112:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.828     www      14113:     my $response=$ua->request($request,$transferfile);
                   14114: # did it work?
                   14115:     if ($response->is_error()) {
                   14116: 	unlink($transferfile);
                   14117: 	&logthis("Userfile repcopy failed for $uri");
                   14118: 	return -1;
                   14119:     }
                   14120: # worked, rename the transfer file
                   14121:     rename($transferfile,$file);
1.607     raeburn  14122:     return 'ok';
1.481     raeburn  14123: }
                   14124: 
1.517     albertel 14125: sub tokenwrapper {
                   14126:     my $uri=shift;
1.980     raeburn  14127:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 14128:     $uri=~s|^/||;
1.620     albertel 14129:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 14130:     my $token=$1;
1.552     albertel 14131:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   14132:     if ($udom && $uname && $file) {
                   14133: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  14134:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  14135:         my $homeserver = &homeserver($uname,$udom);
1.1172.2.120  raeburn  14136:         my $hostname = &hostname($homeserver);
1.980     raeburn  14137:         my $protocol = $protocol{$homeserver};
                   14138:         $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  14139:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 14140:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   14141:                                '&tokenissued='.$perlvar{'lonHostID'};
                   14142:     } else {
                   14143:         return '/adm/notfound.html';
                   14144:     }
                   14145: }
                   14146: 
1.828     www      14147: # call with reqtype HEAD: get last modification time
                   14148: # call with reqtype GET: get the file contents
                   14149: # Do not call this with reqtype GET for large files! It loads everything into memory
                   14150: #
1.481     raeburn  14151: sub getuploaded {
                   14152:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   14153:     $uri=~s/^\///;
1.980     raeburn  14154:     my $homeserver = &homeserver($cnum,$cdom);
1.1172.2.120  raeburn  14155:     my $hostname = &hostname($homeserver);
1.980     raeburn  14156:     my $protocol = $protocol{$homeserver};
                   14157:     $protocol = 'http' if ($protocol ne 'https');
1.1172.2.120  raeburn  14158:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  14159:     my $ua=new LWP::UserAgent;
                   14160:     my $request=new HTTP::Request($reqtype,$uri);
                   14161:     my $response=$ua->request($request);
                   14162:     $$rtncode = $response->code;
1.482     albertel 14163:     if (! $response->is_success()) {
                   14164: 	return 'failed';
                   14165:     }      
                   14166:     if ($reqtype eq 'HEAD') {
1.486     www      14167: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 14168:     } elsif ($reqtype eq 'GET') {
                   14169: 	$$info = $response->content;
1.472     albertel 14170:     }
1.482     albertel 14171:     return 'ok';
1.36      albertel 14172: }
                   14173: 
1.481     raeburn  14174: sub readfile {
                   14175:     my $file = shift;
                   14176:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   14177:     my $fh;
1.1172.2.96  raeburn  14178:     open($fh,"<",$file);
1.481     raeburn  14179:     my $a='';
1.800     albertel 14180:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  14181:     return $a;
                   14182: }
                   14183: 
1.36      albertel 14184: sub filelocation {
1.590     banghart 14185:     my ($dir,$file) = @_;
                   14186:     my $location;
                   14187:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 14188: 
                   14189:     if ($file =~ m-^/adm/-) {
                   14190: 	$file=~s-^/adm/wrapper/-/-;
                   14191: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   14192:     }
1.882     albertel 14193: 
1.1139    www      14194:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  14195:         $location = $file;
1.609     banghart 14196:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 14197:         my ($udom,$uname,$filename)=
1.811     albertel 14198:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 14199:         my $home=&homeserver($uname,$udom);
                   14200:         my $is_me=0;
                   14201:         my @ids=&current_machine_ids();
                   14202:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   14203:         if ($is_me) {
1.1117    foxr     14204:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 14205:         } else {
                   14206:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   14207:   	      $udom.'/'.$uname.'/'.$filename;
                   14208:         }
1.882     albertel 14209:     } elsif ($file =~ m-^/adm/-) {
                   14210: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 14211:     } else {
                   14212:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      14213:         $file=~s:^/(res|priv)/:/:;
                   14214:         my $space=$1;
1.590     banghart 14215:         if ( !( $file =~ m:^/:) ) {
                   14216:             $location = $dir. '/'.$file;
                   14217:         } else {
1.1142    raeburn  14218:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 14219:         }
1.59      albertel 14220:     }
1.590     banghart 14221:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 14222:     while ($location=~m{/\.\./}) {
                   14223: 	if ($location =~ m{/[^/]+/\.\./}) {
                   14224: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   14225: 	} else {
                   14226: 	    $location=~ s{/\.\./}{/}g;
                   14227: 	}
                   14228:     } #remove dir/..
1.590     banghart 14229:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   14230:     return $location;
1.46      www      14231: }
1.36      albertel 14232: 
1.46      www      14233: sub hreflocation {
                   14234:     my ($dir,$file)=@_;
1.980     raeburn  14235:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 14236: 	$file=filelocation($dir,$file);
1.700     albertel 14237:     } elsif ($file=~m-^/adm/-) {
                   14238: 	$file=~s-^/adm/wrapper/-/-;
                   14239: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 14240:     }
                   14241:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   14242: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   14243:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  14244: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   14245: 	        {/uploaded/$1/$2/}x;
1.46      www      14246:     }
1.913     albertel 14247:     if ($file=~ m{^/userfiles/}) {
                   14248: 	$file =~ s{^/userfiles/}{/uploaded/};
                   14249:     }
1.462     albertel 14250:     return $file;
1.465     albertel 14251: }
                   14252: 
1.1139    www      14253: 
                   14254: 
                   14255: 
                   14256: 
1.465     albertel 14257: sub current_machine_domains {
1.853     albertel 14258:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   14259: }
                   14260: 
                   14261: sub machine_domains {
                   14262:     my ($hostname) = @_;
1.465     albertel 14263:     my @domains;
1.838     albertel 14264:     my %hostname = &all_hostnames();
1.465     albertel 14265:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  14266: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 14267: 	if ($hostname eq $name) {
1.844     albertel 14268: 	    push(@domains,&host_domain($id));
1.465     albertel 14269: 	}
                   14270:     }
                   14271:     return @domains;
                   14272: }
                   14273: 
                   14274: sub current_machine_ids {
1.853     albertel 14275:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   14276: }
                   14277: 
                   14278: sub machine_ids {
                   14279:     my ($hostname) = @_;
                   14280:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 14281:     my @ids;
1.888     albertel 14282:     my %name_to_host = &all_names();
1.889     albertel 14283:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   14284: 	return @{ $name_to_host{$hostname} };
                   14285:     }
                   14286:     return;
1.31      www      14287: }
                   14288: 
1.824     raeburn  14289: sub additional_machine_domains {
                   14290:     my @domains;
1.1172.2.142  raeburn  14291:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
                   14292:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
                   14293:             while( my $line = <$fh>) {
                   14294:                 chomp($line);
                   14295:                 $line =~ s/\s//g;
                   14296:                 push(@domains,$line);
                   14297:             }
                   14298:             close($fh);
                   14299:         }
1.824     raeburn  14300:     }
                   14301:     return @domains;
                   14302: }
                   14303: 
                   14304: sub default_login_domain {
                   14305:     my $domain = $perlvar{'lonDefDomain'};
                   14306:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   14307:     foreach my $posdom (&current_machine_domains(),
                   14308:                         &additional_machine_domains()) {
                   14309:         if (lc($posdom) eq lc($testdomain)) {
                   14310:             $domain=$posdom;
                   14311:             last;
                   14312:         }
                   14313:     }
                   14314:     return $domain;
                   14315: }
                   14316: 
1.1172.2.106  raeburn  14317: sub shared_institution {
1.1172.2.136  raeburn  14318:     my ($dom,$lonhost) = @_;
                   14319:     if ($lonhost eq '') {
                   14320:         $lonhost = $perlvar{'lonHostID'};
                   14321:     }
1.1172.2.106  raeburn  14322:     my $same_intdom;
1.1172.2.136  raeburn  14323:     my $hostintdom = &internet_dom($lonhost);
1.1172.2.106  raeburn  14324:     if ($hostintdom ne '') {
                   14325:         my %iphost = &get_iphost();
                   14326:         my $primary_id = &domain($dom,'primary');
                   14327:         my $primary_ip = &get_host_ip($primary_id);
                   14328:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   14329:             foreach my $id (@{$iphost{$primary_ip}}) {
                   14330:                 my $intdom = &internet_dom($id);
                   14331:                 if ($intdom eq $hostintdom) {
                   14332:                     $same_intdom = 1;
                   14333:                     last;
                   14334:                 }
                   14335:             }
                   14336:         }
                   14337:     }
                   14338:     return $same_intdom;
                   14339: }
                   14340: 
1.1172.2.120  raeburn  14341: sub uses_sts {
                   14342:     my ($ignore_cache) = @_;
                   14343:     my $lonhost = $perlvar{'lonHostID'};
                   14344:     my $hostname = &hostname($lonhost);
                   14345:     my $sts_on;
                   14346:     if ($protocol{$lonhost} eq 'https') {
                   14347:         my $cachetime = 12*3600;
                   14348:         if (!$ignore_cache) {
                   14349:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   14350:             if (defined($cached)) {
                   14351:                 return $sts_on;
                   14352:             }
                   14353:         }
1.1172.2.121  raeburn  14354:         my $ua=new LWP::UserAgent;
1.1172.2.120  raeburn  14355:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   14356:         my $request=new HTTP::Request('HEAD',$url);
1.1172.2.121  raeburn  14357:         my $response=$ua->request($request);
1.1172.2.120  raeburn  14358:         if ($response->is_success) {
                   14359:             my $has_sts = $response->header('Strict-Transport-Security');
                   14360:             if ($has_sts eq '') {
                   14361:                 $sts_on = 0;
                   14362:             } else {
                   14363:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   14364:                     my $maxage = $1;
                   14365:                     if ($maxage) {
                   14366:                         $sts_on = 1;
                   14367:                     } else {
                   14368:                         $sts_on = 0;
                   14369:                     }
                   14370:                 } else {
                   14371:                     $sts_on = 0;
                   14372:                 }
                   14373:             }
                   14374:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   14375:         }
                   14376:     }
                   14377:     return;
                   14378: }
                   14379: 
1.1172.2.142  raeburn  14380: sub waf_allssl {
                   14381:     my ($host_name) = @_;
                   14382:     my $alias = &get_proxy_alias();
                   14383:     if ($host_name eq '') {
                   14384:         $host_name = $ENV{'SERVER_NAME'};
                   14385:     }
                   14386:     if (($host_name ne '') && ($alias eq $host_name)) {
                   14387:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
                   14388:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   14389:         if ($defdomdefaults{'waf_sslopt'}) {
                   14390:             return $defdomdefaults{'waf_sslopt'};
                   14391:         }
                   14392:     }
                   14393:     return;
                   14394: }
                   14395: 
1.1172.2.134  raeburn  14396: sub get_requestor_ip {
                   14397:     my ($r,$nolookup,$noproxy) = @_;
                   14398:     my $from_ip;
                   14399:     if (ref($r)) {
1.1172.2.142  raeburn  14400:         if ($r->can('useragent_ip')) {
                   14401:             if ($noproxy && $r->can('client_ip')) {
                   14402:                 $from_ip = $r->client_ip();
                   14403:             } else {
                   14404:                 $from_ip = $r->useragent_ip();
                   14405:             }
                   14406:         } elsif ($r->connection->can('remote_ip')) {
                   14407:             $from_ip = $r->connection->remote_ip();
                   14408:         } else {
                   14409:             $from_ip = $r->get_remote_host($nolookup);
                   14410:         }
1.1172.2.134  raeburn  14411:     } else {
                   14412:         $from_ip = $ENV{'REMOTE_ADDR'};
                   14413:     }
1.1172.2.142  raeburn  14414:     return $from_ip if ($noproxy);
                   14415:    # Who controls proxy settings for server
                   14416:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14417:     my $proxyinfo = &get_proxy_settings($dom_in_use);
                   14418:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
                   14419:         if ($proxyinfo->{'vpnint'}) {
                   14420:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
                   14421:                 return $from_ip;
                   14422:             }
                   14423:         }
                   14424:         if ($proxyinfo->{'trusted'}) {
                   14425:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
                   14426:                 my $ipheader = $proxyinfo->{'ipheader'};
                   14427:                 my ($ip,$xfor);
                   14428:                 if (ref($r)) {
                   14429:                     if ($ipheader) {
                   14430:                         $ip = $r->headers_in->{$ipheader};
                   14431:                     }
                   14432:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
                   14433:                 } else {
                   14434:                     if ($ipheader) {
                   14435:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
                   14436:                     }
                   14437:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
                   14438:                 }
                   14439:                 if (($ip eq '') && ($xfor ne '')) {
                   14440:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
                   14441:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
                   14442:                             $ip = $poss_ip;
                   14443:                             last;
                   14444:                         }
                   14445:                     }
                   14446:                 }
                   14447:                 if ($ip ne '') {
                   14448:                     return $ip;
                   14449:                 }
                   14450:             }
                   14451:         }
                   14452:     }
1.1172.2.134  raeburn  14453:     return $from_ip;
                   14454: }
                   14455: 
1.1172.2.142  raeburn  14456: sub get_proxy_settings {
                   14457:     my ($dom_in_use) = @_;
                   14458:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   14459:     my $proxyinfo = {
                   14460:                        ipheader => $domdefaults{'waf_ipheader'},
                   14461:                        trusted  => $domdefaults{'waf_trusted'},
                   14462:                        vpnint   => $domdefaults{'waf_vpnint'},
                   14463:                        vpnext   => $domdefaults{'waf_vpnext'},
                   14464:                        sslopt   => $domdefaults{'waf_sslopt'},
                   14465:                     };
                   14466:     return $proxyinfo;
                   14467: }
                   14468: 
                   14469: sub ip_match {
                   14470:     my ($ip,$pattern_str) = @_;
                   14471:     $ip=Net::CIDR::cidrvalidate($ip);
                   14472:     if ($ip) {
                   14473:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
                   14474:     }
                   14475:     return;
                   14476: }
                   14477: 
                   14478: sub get_proxy_alias {
                   14479:     my ($lonid) = @_;
                   14480:     if ($lonid eq '') {
                   14481:         $lonid = $perlvar{'lonHostID'};
                   14482:     }
                   14483:     if (!defined(&hostname($lonid))) {
                   14484:         return;
                   14485:     }
                   14486:     if ($lonid ne '') {
                   14487:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
                   14488:         if ($cached) {
                   14489:             return $alias;
                   14490:         }
                   14491:         my $dom = &Apache::lonnet::host_domain($lonid);
                   14492:         if ($dom ne '') {
                   14493:             my $cachetime = 60*60*24;
                   14494:             my %domconfig =
                   14495:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14496:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14497:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
                   14498:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
                   14499:                 }
                   14500:             }
                   14501:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
                   14502:         }
                   14503:     }
                   14504:     return;
                   14505: }
                   14506: 
                   14507: sub use_proxy_alias {
                   14508:     my ($r,$lonid) = @_;
                   14509:     my $alias = &get_proxy_alias($lonid);
                   14510:     if ($alias) {
                   14511:         my $dom = &host_domain($lonid);
                   14512:         if ($dom ne '') {
                   14513:             my $proxyinfo = &get_proxy_settings($dom);
                   14514:             my ($vpnint,$remote_ip);
                   14515:             if (ref($proxyinfo) eq 'HASH') {
                   14516:                 $vpnint = $proxyinfo->{'vpnint'};
                   14517:                 if ($vpnint) {
                   14518:                     $remote_ip = &get_requestor_ip($r,1,1);
                   14519:                 }
                   14520:             }
                   14521:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
                   14522:                 return $alias;
                   14523:             }
                   14524:         }
                   14525:     }
                   14526:     return;
                   14527: }
                   14528: 
                   14529: sub alias_sso {
                   14530:     my ($lonid) = @_;
                   14531:     if ($lonid eq '') {
                   14532:         $lonid = $perlvar{'lonHostID'};
                   14533:     }
                   14534:     if (!defined(&hostname($lonid))) {
                   14535:         return;
                   14536:     }
                   14537:     if ($lonid ne '') {
                   14538:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
                   14539:         if ($cached) {
                   14540:             return $use_alias;
                   14541:         }
                   14542:         my $dom = &Apache::lonnet::host_domain($lonid);
                   14543:         if ($dom ne '') {
                   14544:             my $cachetime = 60*60*24;
                   14545:             my %domconfig =
                   14546:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14547:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14548:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
                   14549:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
                   14550:                 }
                   14551:             }
                   14552:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
                   14553:         }
                   14554:     }
                   14555:     return;
                   14556: }
                   14557: 
                   14558: sub get_saml_landing {
                   14559:     my ($lonid) = @_;
                   14560:     if ($lonid eq '') {
                   14561:         my $defdom = &default_login_domain();
                   14562:         my @hosts = &current_machine_ids();
                   14563:         if (@hosts > 1) {
                   14564:             foreach my $hostid (@hosts) {
                   14565:                 if (&host_domain($hostid) eq $defdom) {
                   14566:                     $lonid = $hostid;
                   14567:                     last;
                   14568:                 }
                   14569:             }
                   14570:         } else {
                   14571:             $lonid = $perlvar{'lonHostID'};
                   14572:         }
                   14573:         if ($lonid) {
                   14574:             unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
                   14575:                 return;
                   14576:             }
                   14577:         } else {
                   14578:             return;
                   14579:         }
                   14580:     } elsif (!defined(&hostname($lonid))) {
                   14581:         return;
                   14582:     }
                   14583:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
                   14584:     if ($cached) {
                   14585:         return $landing;
                   14586:     }
                   14587:     my $dom = &Apache::lonnet::host_domain($lonid);
                   14588:     if ($dom ne '') {
                   14589:         my $cachetime = 60*60*24;
                   14590:         my %domconfig =
                   14591:             &Apache::lonnet::get_dom('configuration',['login'],$dom);
                   14592:         if (ref($domconfig{'login'}) eq 'HASH') {
                   14593:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
                   14594:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
                   14595:                     $landing = 1;
                   14596:                 }
                   14597:             }
                   14598:         }
                   14599:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
                   14600:     }
                   14601:     return;
                   14602: }
                   14603: 
1.31      www      14604: # ------------------------------------------------------------- Declutters URLs
                   14605: 
                   14606: sub declutter {
                   14607:     my $thisfn=shift;
1.569     albertel 14608:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1172.2.49  raeburn  14609:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   14610:         $thisfn=~s{^/home/httpd/html}{};
                   14611:     }
1.31      www      14612:     $thisfn=~s/^\///;
1.697     albertel 14613:     $thisfn=~s|^adm/wrapper/||;
                   14614:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      14615:     $thisfn=~s/^res\///;
1.1172    bisitz   14616:     $thisfn=~s/^priv\///;
1.1032    raeburn  14617:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   14618:         $thisfn=~s/\?.+$//;
                   14619:     }
1.268     www      14620:     return $thisfn;
                   14621: }
                   14622: 
                   14623: # ------------------------------------------------------------- Clutter up URLs
                   14624: 
                   14625: sub clutter {
                   14626:     my $thisfn='/'.&declutter(shift);
1.887     albertel 14627:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 14628: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      14629:        $thisfn='/res'.$thisfn; 
                   14630:     }
1.1031    raeburn  14631:     if ($thisfn !~m|^/adm|) {
                   14632: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 14633: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 14634: 	} else {
                   14635: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   14636: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 14637: 	    if ($embstyle eq 'ssi'
                   14638: 		|| ($embstyle eq 'hdn')
                   14639: 		|| ($embstyle eq 'rat')
                   14640: 		|| ($embstyle eq 'prv')
                   14641: 		|| ($embstyle eq 'ign')) {
                   14642: 		#do nothing with these
                   14643: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 14644: 		|| ($embstyle eq 'emb')
                   14645: 		|| ($embstyle eq 'wrp')) {
                   14646: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 14647: 	    } elsif ($embstyle eq 'unk'
                   14648: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 14649: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 14650: 	    } else {
1.718     www      14651: #		&logthis("Got a blank emb style");
1.695     albertel 14652: 	    }
1.694     albertel 14653: 	}
1.1172.2.146.  .1(raebu 14654:22):     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
                   14655:22):         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 14656:     }
1.31      www      14657:     return $thisfn;
1.12      www      14658: }
                   14659: 
1.787     albertel 14660: sub clutter_with_no_wrapper {
                   14661:     my $uri = &clutter(shift);
                   14662:     if ($uri =~ m-^/adm/-) {
                   14663: 	$uri =~ s-^/adm/wrapper/-/-;
                   14664: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   14665:     }
                   14666:     return $uri;
                   14667: }
                   14668: 
1.557     albertel 14669: sub freeze_escape {
                   14670:     my ($value)=@_;
                   14671:     if (ref($value)) {
                   14672: 	$value=&nfreeze($value);
                   14673: 	return '__FROZEN__'.&escape($value);
                   14674:     }
                   14675:     return &escape($value);
                   14676: }
                   14677: 
1.11      www      14678: 
1.557     albertel 14679: sub thaw_unescape {
                   14680:     my ($value)=@_;
                   14681:     if ($value =~ /^__FROZEN__/) {
                   14682: 	substr($value,0,10,undef);
                   14683: 	$value=&unescape($value);
                   14684: 	return &thaw($value);
                   14685:     }
                   14686:     return &unescape($value);
                   14687: }
                   14688: 
1.436     albertel 14689: sub correct_line_ends {
                   14690:     my ($result)=@_;
                   14691:     $$result =~s/\r\n/\n/mg;
                   14692:     $$result =~s/\r/\n/mg;
1.415     albertel 14693: }
1.1       albertel 14694: # ================================================================ Main Program
                   14695: 
1.184     www      14696: sub goodbye {
1.204     albertel 14697:    &logthis("Starting Shut down");
1.443     albertel 14698: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 14699:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 14700: #converted
1.599     albertel 14701: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 14702:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   14703: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   14704: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 14705: #1.1 only
1.870     albertel 14706: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   14707: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   14708: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   14709: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   14710:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 14711:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   14712:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      14713:    &flushcourselogs();
                   14714:    &logthis("Shutting down");
                   14715: }
                   14716: 
1.852     albertel 14717: sub get_dns {
1.1172.2.17  raeburn  14718:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 14719:     if (!$ignore_cache) {
                   14720: 	my ($content,$cached)=
                   14721: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   14722: 	if ($cached) {
1.1172.2.17  raeburn  14723: 	    &$func($content,$hashref);
1.869     albertel 14724: 	    return;
                   14725: 	}
                   14726:     }
                   14727: 
                   14728:     my %alldns;
1.1172.2.96  raeburn  14729:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   14730:         foreach my $dns (<$config>) {
                   14731: 	    next if ($dns !~ /^\^(\S*)/x);
                   14732:             my $line = $1;
                   14733:             my ($host,$protocol) = split(/:/,$line);
                   14734:             if ($protocol ne 'https') {
                   14735:                 $protocol = 'http';
                   14736:             }
                   14737: 	    $alldns{$host} = $protocol;
1.979     raeburn  14738:         }
1.1172.2.96  raeburn  14739:         close($config);
1.869     albertel 14740:     }
                   14741:     while (%alldns) {
1.1172.2.52  raeburn  14742: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1172.2.142  raeburn  14743:         my @content;
                   14744:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
                   14745:             my $command = (split('/',$url))[3];
                   14746:             my ($dir,$file) = &parse_getdns_url($command,$url);
                   14747:             delete($alldns{$dns});
                   14748:             next if (($dir eq '') || ($file eq ''));
                   14749:             if (open(my $config,'<',"$dir/$file")) {
                   14750:                 @content = <$config>;
                   14751:                 close($config);
                   14752:             }
                   14753:         } else {
                   14754: 	    my $ua=new LWP::UserAgent;
                   14755:             $ua->timeout(30);
                   14756: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
                   14757: 	    my $response=$ua->request($request);
                   14758:             delete($alldns{$dns});
                   14759: 	    next if ($response->is_error());
                   14760: 	    @content = split("\n",$response->content);
                   14761:         }
1.1172.2.17  raeburn  14762:         unless ($nocache) {
1.1172.2.23  raeburn  14763: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1172.2.17  raeburn  14764:         }
                   14765: 	&$func(\@content,$hashref);
1.869     albertel 14766: 	return;
1.852     albertel 14767:     }
1.871     albertel 14768:     my $which = (split('/',$url))[3];
                   14769:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1172.2.105  raeburn  14770:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   14771:         my @content = <$config>;
                   14772:         &$func(\@content,$hashref);
                   14773:     }
1.1172.2.17  raeburn  14774:     return;
                   14775: }
                   14776: 
                   14777: # ------------------------------------------------------Get DNS checksums file
                   14778: sub parse_dns_checksums_tab {
                   14779:     my ($lines,$hashref) = @_;
1.1172.2.53  raeburn  14780:     my $lonhost = $perlvar{'lonHostID'};
                   14781:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1172.2.17  raeburn  14782:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1172.2.53  raeburn  14783:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   14784:     my $webconfdir = '/etc/httpd/conf';
                   14785:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   14786:         $webconfdir = '/etc/apache2';
                   14787:     } elsif ($distro =~ /^sles(\d+)$/) {
                   14788:         if ($1 >= 10) {
                   14789:             $webconfdir = '/etc/apache2';
                   14790:         }
                   14791:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   14792:         if ($1 >= 10.0) {
                   14793:             $webconfdir = '/etc/apache2';
                   14794:         }
                   14795:     }
1.1172.2.17  raeburn  14796:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14797:     my (%chksum,%revnum);
                   14798:     if (ref($lines) eq 'ARRAY') {
                   14799:         chomp(@{$lines});
1.1172.2.34  raeburn  14800:         my $version = shift(@{$lines});
                   14801:         if ($version eq $release) {
1.1172.2.17  raeburn  14802:             foreach my $line (@{$lines}) {
1.1172.2.34  raeburn  14803:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1172.2.53  raeburn  14804:                 if ($file =~ m{^/etc/httpd/conf}) {
                   14805:                     if ($webconfdir eq '/etc/apache2') {
                   14806:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   14807:                     }
                   14808:                 }
1.1172.2.34  raeburn  14809:                 $chksum{$file} = $shasum;
                   14810:                 $revnum{$file} = $version;
1.1172.2.17  raeburn  14811:             }
                   14812:             if (ref($hashref) eq 'HASH') {
                   14813:                 %{$hashref} = (
                   14814:                                 sums     => \%chksum,
                   14815:                                 versions => \%revnum,
                   14816:                               );
                   14817:             }
                   14818:         }
                   14819:     }
1.869     albertel 14820:     return;
1.852     albertel 14821: }
1.1172.2.17  raeburn  14822: 
                   14823: sub fetch_dns_checksums {
                   14824:     my %checksums;
1.1172.2.34  raeburn  14825:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1172.2.48  raeburn  14826:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1172.2.34  raeburn  14827:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   14828:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1172.2.17  raeburn  14829:              \%checksums);
                   14830:     return \%checksums;
                   14831: }
                   14832: 
1.1172.2.142  raeburn  14833: sub parse_getdns_url {
                   14834:     my ($command,$url) = @_;
                   14835:     my $dir = $perlvar{'lonTabDir'};
                   14836:     my $file;
                   14837:     if ($command eq 'hosts') {
                   14838:         $file = 'dns_hosts.tab';
                   14839:     } elsif ($command eq 'domain') {
                   14840:         $file = 'dns_domain.tab';
                   14841:     } elsif ($command eq 'checksums') {
                   14842:         my $version = (split('/',$url))[4];
                   14843:         $file = "dns_checksums/$version.tab",
                   14844:     }
                   14845:     return ($dir,$file);
                   14846: }
                   14847: 
1.327     albertel 14848: # ------------------------------------------------------------ Read domain file
                   14849: {
1.852     albertel 14850:     my $loaded;
1.846     albertel 14851:     my %domain;
                   14852: 
1.852     albertel 14853:     sub parse_domain_tab {
                   14854: 	my ($lines) = @_;
                   14855: 	foreach my $line (@$lines) {
                   14856: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      14857: 
1.846     albertel 14858: 	    chomp($line);
1.852     albertel 14859: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 14860: 	    my %this_domain;
                   14861: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   14862: 			       'lang_def', 'city', 'longi', 'lati',
                   14863: 			       'primary') {
                   14864: 		$this_domain{$field} = shift(@elements);
                   14865: 	    }
                   14866: 	    $domain{$name} = \%this_domain;
1.852     albertel 14867: 	}
                   14868:     }
1.864     albertel 14869: 
                   14870:     sub reset_domain_info {
                   14871: 	undef($loaded);
                   14872: 	undef(%domain);
                   14873:     }
                   14874: 
1.852     albertel 14875:     sub load_domain_tab {
1.1172.2.70  raeburn  14876: 	my ($ignore_cache,$nocache) = @_;
                   14877: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 14878: 	my $fh;
1.1172.2.96  raeburn  14879: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 14880: 	    my @lines = <$fh>;
                   14881: 	    &parse_domain_tab(\@lines);
1.448     albertel 14882: 	}
1.852     albertel 14883: 	close($fh);
                   14884: 	$loaded = 1;
1.327     albertel 14885:     }
1.846     albertel 14886: 
                   14887:     sub domain {
1.852     albertel 14888: 	&load_domain_tab() if (!$loaded);
                   14889: 
1.846     albertel 14890: 	my ($name,$what) = @_;
                   14891: 	return if ( !exists($domain{$name}) );
                   14892: 
                   14893: 	if (!$what) {
                   14894: 	    return $domain{$name}{'description'};
                   14895: 	}
                   14896: 	return $domain{$name}{$what};
                   14897:     }
1.974     raeburn  14898: 
                   14899:     sub domain_info {
                   14900:         &load_domain_tab() if (!$loaded);
                   14901:         return %domain;
                   14902:     }
                   14903: 
1.327     albertel 14904: }
                   14905: 
                   14906: 
1.1       albertel 14907: # ------------------------------------------------------------- Read hosts file
                   14908: {
1.838     albertel 14909:     my %hostname;
1.844     albertel 14910:     my %hostdom;
1.845     albertel 14911:     my %libserv;
1.852     albertel 14912:     my $loaded;
1.888     albertel 14913:     my %name_to_host;
1.1074    raeburn  14914:     my %internetdom;
1.1107    raeburn  14915:     my %LC_dns_serv;
1.852     albertel 14916: 
                   14917:     sub parse_hosts_tab {
                   14918: 	my ($file) = @_;
                   14919: 	foreach my $configline (@$file) {
                   14920: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  14921:             chomp($configline);
                   14922: 	    if ($configline =~ /^\^/) {
                   14923:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   14924:                     $LC_dns_serv{$1} = 1;
                   14925:                 }
                   14926:                 next;
                   14927:             }
1.1074    raeburn  14928: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 14929: 	    $name=~s/\s//g;
                   14930: 	    if ($id && $domain && $role && $name) {
1.1172.2.96  raeburn  14931:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   14932:                     my $curr = $hostname{$id};
                   14933:                     my $skip;
                   14934:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   14935:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   14936:                             $skip = 1;
                   14937:                         } else {
                   14938:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   14939:                         }
                   14940:                     }
                   14941:                     unless ($skip) {
                   14942:                         push(@{$name_to_host{$name}},$id);
                   14943:                     }
                   14944:                 } else {
                   14945:                     push(@{$name_to_host{$name}},$id);
                   14946:                 }
1.852     albertel 14947: 		$hostname{$id}=$name;
                   14948: 		$hostdom{$id}=$domain;
                   14949: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  14950:                 if (defined($protocol)) {
                   14951:                     if ($protocol eq 'https') {
                   14952:                         $protocol{$id} = $protocol;
                   14953:                     } else {
                   14954:                         $protocol{$id} = 'http'; 
                   14955:                     }
1.968     raeburn  14956:                 } else {
1.969     raeburn  14957:                     $protocol{$id} = 'http';
1.968     raeburn  14958:                 }
1.1074    raeburn  14959:                 if (defined($intdom)) {
                   14960:                     $internetdom{$id} = $intdom;
                   14961:                 }
1.852     albertel 14962: 	    }
                   14963: 	}
                   14964:     }
1.864     albertel 14965:     
                   14966:     sub reset_hosts_info {
1.897     albertel 14967: 	&purge_remembered();
1.864     albertel 14968: 	&reset_domain_info();
                   14969: 	&reset_hosts_ip_info();
1.892     albertel 14970: 	undef(%name_to_host);
1.864     albertel 14971: 	undef(%hostname);
                   14972: 	undef(%hostdom);
                   14973: 	undef(%libserv);
                   14974: 	undef($loaded);
                   14975:     }
1.1       albertel 14976: 
1.852     albertel 14977:     sub load_hosts_tab {
1.1172.2.70  raeburn  14978: 	my ($ignore_cache,$nocache) = @_;
                   14979: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1172.2.96  raeburn  14980: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 14981: 	my @config = <$config>;
                   14982: 	&parse_hosts_tab(\@config);
                   14983: 	close($config);
                   14984: 	$loaded=1;
1.1       albertel 14985:     }
1.852     albertel 14986: 
1.838     albertel 14987:     sub hostname {
1.852     albertel 14988: 	&load_hosts_tab() if (!$loaded);
                   14989: 
1.838     albertel 14990: 	my ($lonid) = @_;
                   14991: 	return $hostname{$lonid};
                   14992:     }
1.845     albertel 14993: 
1.838     albertel 14994:     sub all_hostnames {
1.852     albertel 14995: 	&load_hosts_tab() if (!$loaded);
                   14996: 
1.838     albertel 14997: 	return %hostname;
                   14998:     }
1.845     albertel 14999: 
1.888     albertel 15000:     sub all_names {
1.1172.2.70  raeburn  15001:         my ($ignore_cache,$nocache) = @_;
                   15002: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 15003: 
                   15004: 	return %name_to_host;
                   15005:     }
                   15006: 
1.974     raeburn  15007:     sub all_host_domain {
                   15008:         &load_hosts_tab() if (!$loaded);
                   15009:         return %hostdom;
                   15010:     }
                   15011: 
1.845     albertel 15012:     sub is_library {
1.852     albertel 15013: 	&load_hosts_tab() if (!$loaded);
                   15014: 
1.845     albertel 15015: 	return exists($libserv{$_[0]});
                   15016:     }
                   15017: 
                   15018:     sub all_library {
1.852     albertel 15019: 	&load_hosts_tab() if (!$loaded);
                   15020: 
1.845     albertel 15021: 	return %libserv;
                   15022:     }
                   15023: 
1.1062    droeschl 15024:     sub unique_library {
                   15025: 	#2x reverse removes all hostnames that appear more than once
                   15026:         my %unique = reverse &all_library();
                   15027:         return reverse %unique;
                   15028:     }
                   15029: 
1.841     albertel 15030:     sub get_servers {
1.852     albertel 15031: 	&load_hosts_tab() if (!$loaded);
                   15032: 
1.841     albertel 15033: 	my ($domain,$type) = @_;
                   15034: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   15035: 	                                          : %hostname;
                   15036: 	my %result;
1.842     albertel 15037: 	if (ref($domain) eq 'ARRAY') {
                   15038: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 15039: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 15040: 		    $result{$host} = $hostname;
                   15041: 		}
                   15042: 	    }
                   15043: 	} else {
                   15044: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   15045: 		if ($hostdom{$host} eq $domain) {
                   15046: 		    $result{$host} = $hostname;
                   15047: 		}
1.841     albertel 15048: 	    }
                   15049: 	}
                   15050: 	return %result;
                   15051:     }
1.845     albertel 15052: 
1.1062    droeschl 15053:     sub get_unique_servers {
                   15054:         my %unique = reverse &get_servers(@_);
                   15055: 	return reverse %unique;
                   15056:     }
                   15057: 
1.844     albertel 15058:     sub host_domain {
1.852     albertel 15059: 	&load_hosts_tab() if (!$loaded);
                   15060: 
1.844     albertel 15061: 	my ($lonid) = @_;
                   15062: 	return $hostdom{$lonid};
                   15063:     }
                   15064: 
1.841     albertel 15065:     sub all_domains {
1.852     albertel 15066: 	&load_hosts_tab() if (!$loaded);
                   15067: 
1.841     albertel 15068: 	my %seen;
                   15069: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   15070: 	return @uniq;
                   15071:     }
1.1074    raeburn  15072: 
                   15073:     sub internet_dom {
                   15074:         &load_hosts_tab() if (!$loaded);
                   15075: 
                   15076:         my ($lonid) = @_;
                   15077:         return $internetdom{$lonid};
                   15078:     }
1.1107    raeburn  15079: 
                   15080:     sub is_LC_dns {
                   15081:         &load_hosts_tab() if (!$loaded);
                   15082: 
                   15083:         my ($hostname) = @_;
                   15084:         return exists($LC_dns_serv{$hostname});
                   15085:     }
                   15086: 
1.1       albertel 15087: }
                   15088: 
1.847     albertel 15089: { 
                   15090:     my %iphost;
1.856     albertel 15091:     my %name_to_ip;
                   15092:     my %lonid_to_ip;
1.869     albertel 15093: 
1.847     albertel 15094:     sub get_hosts_from_ip {
                   15095: 	my ($ip) = @_;
                   15096: 	my %iphosts = &get_iphost();
                   15097: 	if (ref($iphosts{$ip})) {
                   15098: 	    return @{$iphosts{$ip}};
                   15099: 	}
                   15100: 	return;
1.839     albertel 15101:     }
1.864     albertel 15102:     
                   15103:     sub reset_hosts_ip_info {
                   15104: 	undef(%iphost);
                   15105: 	undef(%name_to_ip);
                   15106: 	undef(%lonid_to_ip);
                   15107:     }
1.856     albertel 15108: 
                   15109:     sub get_host_ip {
                   15110: 	my ($lonid) = @_;
                   15111: 	if (exists($lonid_to_ip{$lonid})) {
                   15112: 	    return $lonid_to_ip{$lonid};
                   15113: 	}
                   15114: 	my $name=&hostname($lonid);
                   15115:    	my $ip = gethostbyname($name);
                   15116: 	return if (!$ip || length($ip) ne 4);
                   15117: 	$ip=inet_ntoa($ip);
                   15118: 	$name_to_ip{$name}   = $ip;
                   15119: 	$lonid_to_ip{$lonid} = $ip;
                   15120: 	return $ip;
                   15121:     }
1.847     albertel 15122:     
                   15123:     sub get_iphost {
1.1172.2.70  raeburn  15124: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 15125: 
1.869     albertel 15126: 	if (!$ignore_cache) {
                   15127: 	    if (%iphost) {
                   15128: 		return %iphost;
                   15129: 	    }
                   15130: 	    my ($ip_info,$cached)=
                   15131: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   15132: 	    if ($cached) {
                   15133: 		%iphost      = %{$ip_info->[0]};
                   15134: 		%name_to_ip  = %{$ip_info->[1]};
                   15135: 		%lonid_to_ip = %{$ip_info->[2]};
                   15136: 		return %iphost;
                   15137: 	    }
                   15138: 	}
1.894     albertel 15139: 
                   15140: 	# get yesterday's info for fallback
                   15141: 	my %old_name_to_ip;
                   15142: 	my ($ip_info,$cached)=
                   15143: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   15144: 	if ($cached) {
                   15145: 	    %old_name_to_ip = %{$ip_info->[1]};
                   15146: 	}
                   15147: 
1.1172.2.70  raeburn  15148: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 15149: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 15150: 	    my $ip;
                   15151: 	    if (!exists($name_to_ip{$name})) {
                   15152: 		$ip = gethostbyname($name);
                   15153: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 15154: 		    if (defined($old_name_to_ip{$name})) {
                   15155: 			$ip = $old_name_to_ip{$name};
                   15156: 			&logthis("Can't find $name defaulting to old $ip");
                   15157: 		    } else {
                   15158: 			&logthis("Name $name no IP found");
                   15159: 			next;
                   15160: 		    }
                   15161: 		} else {
                   15162: 		    $ip=inet_ntoa($ip);
1.847     albertel 15163: 		}
                   15164: 		$name_to_ip{$name} = $ip;
                   15165: 	    } else {
                   15166: 		$ip = $name_to_ip{$name};
1.653     albertel 15167: 	    }
1.888     albertel 15168: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   15169: 		$lonid_to_ip{$id} = $ip;
                   15170: 	    }
                   15171: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 15172: 	}
1.1172.2.70  raeburn  15173:         unless ($nocache) {
                   15174: 	    &do_cache_new('iphost','iphost',
                   15175: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   15176: 		          48*60*60);
                   15177:         }
1.869     albertel 15178: 
1.847     albertel 15179: 	return %iphost;
1.598     albertel 15180:     }
                   15181: 
1.992     raeburn  15182:     #
                   15183:     #  Given a DNS returns the loncapa host name for that DNS 
                   15184:     # 
                   15185:     sub host_from_dns {
                   15186:         my ($dns) = @_;
                   15187:         my @hosts;
                   15188:         my $ip;
                   15189: 
1.993     raeburn  15190:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  15191:             $ip = $name_to_ip{$dns};
                   15192:         }
                   15193:         if (!$ip) {
                   15194:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   15195:             if (length($ip) == 4) { 
                   15196: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   15197:             }
                   15198:         }
                   15199:         if ($ip) {
                   15200: 	    @hosts = get_hosts_from_ip($ip);
                   15201: 	    return $hosts[0];
                   15202:         }
                   15203:         return undef;
1.986     foxr     15204:     }
1.992     raeburn  15205: 
1.1074    raeburn  15206:     sub get_internet_names {
                   15207:         my ($lonid) = @_;
                   15208:         return if ($lonid eq '');
                   15209:         my ($idnref,$cached)=
                   15210:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   15211:         if ($cached) {
                   15212:             return $idnref;
                   15213:         }
                   15214:         my $ip = &get_host_ip($lonid);
                   15215:         my @hosts = &get_hosts_from_ip($ip);
                   15216:         my %iphost = &get_iphost();
                   15217:         my (@idns,%seen);
                   15218:         foreach my $id (@hosts) {
                   15219:             my $dom = &host_domain($id);
                   15220:             my $prim_id = &domain($dom,'primary');
                   15221:             my $prim_ip = &get_host_ip($prim_id);
                   15222:             next if ($seen{$prim_ip});
                   15223:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   15224:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   15225:                     my $intdom = &internet_dom($id);
                   15226:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   15227:                         push(@idns,$intdom);
                   15228:                     }
                   15229:                 }
                   15230:             }
                   15231:             $seen{$prim_ip} = 1;
                   15232:         }
1.1172.2.23  raeburn  15233:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  15234:     }
                   15235: 
1.986     foxr     15236: }
                   15237: 
1.1079    raeburn  15238: sub all_loncaparevs {
1.1172.2.39  raeburn  15239:     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  15240: }
                   15241: 
1.1172.2.27  raeburn  15242: # ------------------------------------------------------- Read loncaparev table
                   15243: {
                   15244:     sub load_loncaparevs {
                   15245:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1172.2.96  raeburn  15246:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1172.2.27  raeburn  15247:                 while (my $configline=<$config>) {
                   15248:                     chomp($configline);
                   15249:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   15250:                     $loncaparevs{$hostid}=$loncaparev;
                   15251:                 }
                   15252:                 close($config);
                   15253:             }
                   15254:         }
                   15255:     }
                   15256: }
                   15257: 
                   15258: # ----------------------------------------------------- Read serverhostID table
                   15259: {
                   15260:     sub load_serverhomeIDs {
                   15261:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1172.2.96  raeburn  15262:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1172.2.27  raeburn  15263:                 while (my $configline=<$config>) {
                   15264:                     chomp($configline);
                   15265:                     my ($name,$id)=split(/:/,$configline);
                   15266:                     $serverhomeIDs{$name}=$id;
                   15267:                 }
                   15268:                 close($config);
                   15269:             }
                   15270:         }
                   15271:     }
                   15272: }
                   15273: 
                   15274: 
1.862     albertel 15275: BEGIN {
                   15276: 
                   15277: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   15278:     unless ($readit) {
                   15279: {
                   15280:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   15281:     %perlvar = (%perlvar,%{$configvars});
                   15282: }
                   15283: 
                   15284: 
1.1       albertel 15285: # ------------------------------------------------------ Read spare server file
                   15286: {
1.1172.2.96  raeburn  15287:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 15288: 
                   15289:     while (my $configline=<$config>) {
                   15290:        chomp($configline);
1.284     matthew  15291:        if ($configline) {
1.784     albertel 15292: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 15293: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 15294: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 15295:        }
                   15296:     }
1.448     albertel 15297:     close($config);
1.1       albertel 15298: }
1.11      www      15299: # ------------------------------------------------------------ Read permissions
                   15300: {
1.1172.2.96  raeburn  15301:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      15302: 
                   15303:     while (my $configline=<$config>) {
1.448     albertel 15304: 	chomp($configline);
                   15305: 	if ($configline) {
                   15306: 	    my ($role,$perm)=split(/ /,$configline);
                   15307: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   15308: 	}
1.11      www      15309:     }
1.448     albertel 15310:     close($config);
1.11      www      15311: }
                   15312: 
                   15313: # -------------------------------------------- Read plain texts for permissions
                   15314: {
1.1172.2.96  raeburn  15315:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      15316: 
                   15317:     while (my $configline=<$config>) {
1.448     albertel 15318: 	chomp($configline);
                   15319: 	if ($configline) {
1.742     raeburn  15320: 	    my ($short,@plain)=split(/:/,$configline);
                   15321:             %{$prp{$short}} = ();
                   15322: 	    if (@plain > 0) {
                   15323:                 $prp{$short}{'std'} = $plain[0];
                   15324:                 for (my $i=1; $i<@plain; $i++) {
                   15325:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   15326:                 }
                   15327:             }
1.448     albertel 15328: 	}
1.135     www      15329:     }
1.448     albertel 15330:     close($config);
1.135     www      15331: }
                   15332: 
                   15333: # ---------------------------------------------------------- Read package table
                   15334: {
1.1172.2.96  raeburn  15335:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      15336: 
                   15337:     while (my $configline=<$config>) {
1.483     albertel 15338: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 15339: 	chomp($configline);
                   15340: 	my ($short,$plain)=split(/:/,$configline);
                   15341: 	my ($pack,$name)=split(/\&/,$short);
                   15342: 	if ($plain ne '') {
                   15343: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   15344: 	    $packagetab{$short}=$plain; 
                   15345: 	}
1.11      www      15346:     }
1.448     albertel 15347:     close($config);
1.329     matthew  15348: }
                   15349: 
1.1172.2.27  raeburn  15350: # --------------------------------------------------------- Read loncaparev table
1.1073    raeburn  15351: 
1.1172.2.27  raeburn  15352: &load_loncaparevs();
                   15353: 
                   15354: # ------------------------------------------------------- Read serverhostID table
                   15355: 
                   15356: &load_serverhomeIDs();
1.1074    raeburn  15357: 
1.1172.2.27  raeburn  15358: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  15359: {
                   15360:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   15361:     if (-e $file) {
                   15362:         my $parser = HTML::LCParser->new($file);
                   15363:         while (my $token = $parser->get_token()) {
                   15364:             if ($token->[0] eq 'S') {
                   15365:                 my $item = $token->[1];
                   15366:                 my $name = $token->[2]{'name'};
                   15367:                 my $value = $token->[2]{'value'};
                   15368:                 if ($item ne '' && $name ne '' && $value ne '') {
                   15369:                     my $release = $parser->get_text();
                   15370:                     $release =~ s/(^\s*|\s*$ )//gx;
                   15371:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   15372:                 }
                   15373:             }
                   15374:         }
                   15375:     }
1.1073    raeburn  15376: }
                   15377: 
1.1138    raeburn  15378: # ---------------------------------------------------------- Read managers table
                   15379: {
                   15380:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1172.2.96  raeburn  15381:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  15382:             while (my $configline=<$config>) {
                   15383:                 chomp($configline);
                   15384:                 next if ($configline =~ /^\#/);
                   15385:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   15386:                     $managerstab{$configline} = 1;
                   15387:                 }
                   15388:             }
                   15389:             close($config);
                   15390:         }
                   15391:     }
                   15392: }
                   15393: 
1.329     matthew  15394: # ------------- set up temporary directory
                   15395: {
1.1117    foxr     15396:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  15397: 
1.11      www      15398: }
                   15399: 
1.1172.2.104  raeburn  15400: # ------------- set default texengine (domain default overrides this)
                   15401: {
                   15402:     $deftex = LONCAPA::texengine();
                   15403: }
                   15404: 
1.1172.2.114  raeburn  15405: # ------------- set default minimum length for passwords for internal auth users
                   15406: {
                   15407:     $passwdmin = LONCAPA::passwd_min();
                   15408: }
                   15409: 
1.794     albertel 15410: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   15411: 				'compress_threshold'=> 20_000,
                   15412:  			        });
1.185     www      15413: 
1.281     www      15414: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      15415: $dumpcount=0;
1.958     www      15416: $locknum=0;
1.22      www      15417: 
1.163     harris41 15418: &logtouch();
1.672     albertel 15419: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      15420: $readit=1;
1.564     albertel 15421:     {
                   15422: 	use integer;
                   15423: 	my $test=(2**32)+1;
1.568     albertel 15424: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 15425: 	&logthis(" Detected 64bit platform ($_64bit)");
                   15426:     }
1.195     www      15427: }
1.1       albertel 15428: }
1.179     www      15429: 
1.1       albertel 15430: 1;
1.191     harris41 15431: __END__
                   15432: 
1.243     albertel 15433: =pod
                   15434: 
1.191     harris41 15435: =head1 NAME
                   15436: 
1.243     albertel 15437: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 15438: 
                   15439: =head1 SYNOPSIS
                   15440: 
1.243     albertel 15441: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 15442: 
                   15443:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   15444: 
1.243     albertel 15445: Common parameters:
                   15446: 
                   15447: =over 4
                   15448: 
                   15449: =item *
                   15450: 
                   15451: $uname : an internal username (if $cname expecting a course Id specifically)
                   15452: 
                   15453: =item *
                   15454: 
                   15455: $udom : a domain (if $cdom expecting a course's domain specifically)
                   15456: 
                   15457: =item *
                   15458: 
                   15459: $symb : a resource instance identifier
                   15460: 
                   15461: =item *
                   15462: 
                   15463: $namespace : the name of a .db file that contains the data needed or
                   15464: being set.
                   15465: 
                   15466: =back
                   15467: 
1.394     bowersj2 15468: =head1 OVERVIEW
1.191     harris41 15469: 
1.394     bowersj2 15470: lonnet provides subroutines which interact with the
                   15471: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   15472: about classes, users, and resources.
1.243     albertel 15473: 
                   15474: For many of these objects you can also use this to store data about
                   15475: them or modify them in various ways.
1.191     harris41 15476: 
1.394     bowersj2 15477: =head2 Symbs
1.191     harris41 15478: 
1.394     bowersj2 15479: To identify a specific instance of a resource, LON-CAPA uses symbols
                   15480: or "symbs"X<symb>. These identifiers are built from the URL of the
                   15481: map, the resource number of the resource in the map, and the URL of
                   15482: the resource itself. The latter is somewhat redundant, but might help
                   15483: if maps change.
                   15484: 
                   15485: An example is
                   15486: 
                   15487:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   15488: 
                   15489: The respective map entry is
                   15490: 
                   15491:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   15492:   title="Problem 2">
                   15493:  </resource>
                   15494: 
                   15495: Symbs are used by the random number generator, as well as to store and
                   15496: restore data specific to a certain instance of for example a problem.
                   15497: 
                   15498: =head2 Storing And Retrieving Data
                   15499: 
                   15500: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   15501: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   15502: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   15503: is is the non-critical message twin of cstore. These functions are for
                   15504: handlers to store a perl hash to a user's permanent data space in an
                   15505: easy manner, and to retrieve it again on another call. It is expected
                   15506: that a handler would use this once at the beginning to retrieve data,
                   15507: and then again once at the end to send only the new data back.
                   15508: 
                   15509: The data is stored in the user's data directory on the user's
                   15510: homeserver under the ID of the course.
                   15511: 
                   15512: The hash that is returned by restore will have all of the previous
                   15513: value for all of the elements of the hash.
                   15514: 
                   15515: Example:
                   15516: 
                   15517:  #creating a hash
                   15518:  my %hash;
                   15519:  $hash{'foo'}='bar';
                   15520: 
                   15521:  #storing it
                   15522:  &Apache::lonnet::cstore(\%hash);
                   15523: 
                   15524:  #changing a value
                   15525:  $hash{'foo'}='notbar';
                   15526: 
                   15527:  #adding a new value
                   15528:  $hash{'bar'}='foo';
                   15529:  &Apache::lonnet::cstore(\%hash);
                   15530: 
                   15531:  #retrieving the hash
                   15532:  my %history=&Apache::lonnet::restore();
                   15533: 
                   15534:  #print the hash
                   15535:  foreach my $key (sort(keys(%history))) {
                   15536:    print("\%history{$key} = $history{$key}");
                   15537:  }
                   15538: 
                   15539: Will print out:
1.191     harris41 15540: 
1.394     bowersj2 15541:  %history{1:foo} = bar
                   15542:  %history{1:keys} = foo:timestamp
                   15543:  %history{1:timestamp} = 990455579
                   15544:  %history{2:bar} = foo
                   15545:  %history{2:foo} = notbar
                   15546:  %history{2:keys} = foo:bar:timestamp
                   15547:  %history{2:timestamp} = 990455580
                   15548:  %history{bar} = foo
                   15549:  %history{foo} = notbar
                   15550:  %history{timestamp} = 990455580
                   15551:  %history{version} = 2
                   15552: 
                   15553: Note that the special hash entries C<keys>, C<version> and
                   15554: C<timestamp> were added to the hash. C<version> will be equal to the
                   15555: total number of versions of the data that have been stored. The
                   15556: C<timestamp> attribute will be the UNIX time the hash was
                   15557: stored. C<keys> is available in every historical section to list which
                   15558: keys were added or changed at a specific historical revision of a
                   15559: hash.
                   15560: 
                   15561: B<Warning>: do not store the hash that restore returns directly. This
                   15562: will cause a mess since it will restore the historical keys as if the
                   15563: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 15564: 
1.394     bowersj2 15565: Calling convention:
1.191     harris41 15566: 
1.1172.2.27  raeburn  15567:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1172.2.64  raeburn  15568:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 15569: 
1.394     bowersj2 15570: For more detailed information, see lonnet specific documentation.
1.191     harris41 15571: 
1.394     bowersj2 15572: =head1 RETURN MESSAGES
1.191     harris41 15573: 
1.394     bowersj2 15574: =over 4
1.191     harris41 15575: 
1.394     bowersj2 15576: =item * B<con_lost>: unable to contact remote host
1.191     harris41 15577: 
1.394     bowersj2 15578: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   15579: when the connection is brought back up
1.191     harris41 15580: 
1.394     bowersj2 15581: =item * B<con_failed>: unable to contact remote host and unable to save message
                   15582: for later delivery
1.191     harris41 15583: 
1.967     bisitz   15584: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 15585: 
1.394     bowersj2 15586: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 15587: that was requested
1.191     harris41 15588: 
1.243     albertel 15589: =back
1.191     harris41 15590: 
1.243     albertel 15591: =head1 PUBLIC SUBROUTINES
1.191     harris41 15592: 
1.243     albertel 15593: =head2 Session Environment Functions
1.191     harris41 15594: 
1.243     albertel 15595: =over 4
1.191     harris41 15596: 
1.394     bowersj2 15597: =item * 
                   15598: X<appenv()>
1.949     raeburn  15599: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 15600: the user envirnoment file, and will be restored for each access this
1.620     albertel 15601: user makes during this session, also modifies the %env for the current
1.949     raeburn  15602: process. Optional rolesarrayref - if defined contains a reference to an array
                   15603: of roles which are exempt from the restriction on modifying user.role entries 
                   15604: in the user's environment.db and in %env.    
1.191     harris41 15605: 
                   15606: =item *
1.394     bowersj2 15607: X<delenv()>
1.987     raeburn  15608: B<delenv($delthis,$regexp)>: removes all items from the session
                   15609: environment file that begin with $delthis. If the 
                   15610: optional second arg - $regexp - is true, $delthis is treated as a 
                   15611: regular expression, otherwise \Q$delthis\E is used. 
                   15612: The values are also deleted from the current processes %env.
1.191     harris41 15613: 
1.795     albertel 15614: =item * get_env_multiple($name) 
                   15615: 
                   15616: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   15617: values may be defined and end up as an array ref.
                   15618: 
                   15619: returns an array of values
                   15620: 
1.243     albertel 15621: =back
                   15622: 
                   15623: =head2 User Information
1.191     harris41 15624: 
1.243     albertel 15625: =over 4
1.191     harris41 15626: 
                   15627: =item *
1.394     bowersj2 15628: X<queryauthenticate()>
                   15629: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 15630: authentication scheme
                   15631: 
                   15632: =item *
1.394     bowersj2 15633: X<authenticate()>
1.1073    raeburn  15634: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 15635: authenticate user from domain's lib servers (first use the current
                   15636: one). C<$upass> should be the users password.
1.1073    raeburn  15637: $checkdefauth is optional (value is 1 if a check should be made to
                   15638:    authenticate user using default authentication method, and allow
                   15639:    account creation if username does not have account in the domain).
                   15640: $clientcancheckhost is optional (value is 1 if checking whether the
                   15641:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 15642: 
                   15643: =item *
1.394     bowersj2 15644: X<homeserver()>
                   15645: B<homeserver($uname,$udom)>: find the server which has
                   15646: the user's directory and files (there must be only one), this caches
                   15647: the answer, and also caches if there is a borken connection.
1.191     harris41 15648: 
                   15649: =item *
1.394     bowersj2 15650: X<idget()>
                   15651: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   15652: (IDs are a unique resource in a domain, there must be only 1 ID per
                   15653: username, and only 1 username per ID in a specific domain) (returns
                   15654: hash: id=>name,id=>name)
1.191     harris41 15655: 
                   15656: =item *
1.394     bowersj2 15657: X<idrget()>
                   15658: B<idrget($udom,@unames)>: find the IDs behind a list of
                   15659: usernames (returns hash: name=>id,name=>id)
1.191     harris41 15660: 
                   15661: =item *
1.394     bowersj2 15662: X<idput()>
                   15663: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 15664: 
                   15665: =item *
1.394     bowersj2 15666: X<rolesinit()>
1.1169    droeschl 15667: B<rolesinit($udom,$username)>: get user privileges.
                   15668: returns user role, first access and timer interval hashes
1.243     albertel 15669: 
                   15670: =item *
1.1171    droeschl 15671: X<privileged()>
                   15672: B<privileged($username,$domain)>: returns a true if user has a
                   15673: privileged and active role (i.e. su or dc), false otherwise.
                   15674: 
                   15675: =item *
1.551     albertel 15676: X<getsection()>
                   15677: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 15678: course $cname, return section name/number or '' for "not in course"
                   15679: and '-1' for "no section"
                   15680: 
                   15681: =item *
1.394     bowersj2 15682: X<userenvironment()>
                   15683: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 15684: passed in @what from the requested user's environment, returns a hash
                   15685: 
1.858     raeburn  15686: =item * 
                   15687: X<userlog_query()>
1.859     albertel 15688: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   15689: activity.log file. %filters defines filters applied when parsing the
                   15690: log file. These can be start or end timestamps, or the type of action
                   15691: - log to look for Login or Logout events, check for Checkin or
                   15692: Checkout, role for role selection. The response is in the form
                   15693: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   15694: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  15695: 
1.243     albertel 15696: =back
                   15697: 
                   15698: =head2 User Roles
                   15699: 
                   15700: =over 4
                   15701: 
                   15702: =item *
                   15703: 
1.1172.2.65  raeburn  15704: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   15705: returns codes for allowed actions.
                   15706: 
                   15707: The first argument is required, all others are optional.
                   15708: 
                   15709: $priv is the privilege being checked.
                   15710: $uri contains additional information about what is being checked for access (e.g.,
                   15711: URL, course ID etc.).
                   15712: $symb is the unique resource instance identifier in a course; if needed,
                   15713: but not provided, it will be retrieved via a call to &symbread().
                   15714: $role is the role for which a priv is being checked (only used if priv is evb).
                   15715: $clientip is the user's IP address (only used when checking for access to portfolio
                   15716: files).
                   15717: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
                   15718: prevents recursive calls to &allowed.
                   15719: 
1.243     albertel 15720:  F: full access
                   15721:  U,I,K: authentication modes (cxx only)
                   15722:  '': forbidden
                   15723:  1: user needs to choose course
                   15724:  2: browse allowed
1.766     albertel 15725:  A: passphrase authentication needed
1.1172.2.65  raeburn  15726:  B: access temporarily blocked because of a blocking event in a course.
1.1172.2.146.  .1(raebu 15727:22):  D: access blocked because access is required via session initiated via deep-link
1.243     albertel 15728: 
                   15729: =item *
                   15730: 
1.1172.2.13  raeburn  15731: constructaccess($url,$setpriv) : check for access to construction space URL
                   15732: 
                   15733: See if the owner domain and name in the URL match those in the
                   15734: expected environment.  If so, return three element list
                   15735: ($ownername,$ownerdomain,$ownerhome).
                   15736: 
                   15737: Otherwise return the null string.
                   15738: 
                   15739: If second argument 'setpriv' is true, it assigns the privileges,
                   15740: and returns the same three element list, unless the owner has
                   15741: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   15742: in which case the null string is returned.
                   15743: 
                   15744: =item *
                   15745: 
1.1172.2.84  raeburn  15746: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   15747: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   15748: for system, domain, and course level. $uname and $udom are optional (current
                   15749: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 15750: 
                   15751: =item *
                   15752: 
1.988     raeburn  15753: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   15754: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  15755: $type is Course (default) or Community.
1.988     raeburn  15756: If $forcedefault evaluates to true, text returned will be default 
                   15757: text for $type. Otherwise, if this is a course, the text returned 
                   15758: will be a custom name for the role (if defined in the course's 
                   15759: environment).  If no custom name is defined the default is returned.
                   15760:    
1.832     raeburn  15761: =item *
                   15762: 
1.1172.2.23  raeburn  15763: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  15764: All arguments are optional. Returns a hash of a roles, either for
                   15765: co-author/assistant author roles for a user's Construction Space
1.906     albertel 15766: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  15767: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   15768: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   15769: For each key, value is set to colon-separated start and end times for
                   15770: the role.  If no username and domain are specified, will default to
1.934     raeburn  15771: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  15772: of role statuses (active, future or previous), roles 
                   15773: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   15774: to restrict the list of roles reported. If no array ref is 
                   15775: provided for types, will default to return only active roles.
1.834     albertel 15776: 
1.1172.2.13  raeburn  15777: =item *
                   15778: 
                   15779: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
                   15780: user: $uname:$udom has a role in the course: $cdom_$cnum.
                   15781: 
                   15782: Additional optional arguments are: $type (if role checking is to be restricted
                   15783: to certain user status types -- previous (expired roles), active (currently
                   15784: available roles) or future (roles available in the future), and
                   15785: $hideprivileged -- if true will not report course roles for users who
1.1172.2.23  raeburn  15786: have active Domain Coordinator role in course's domain or in additional
                   15787: domains (specified in 'Domains to check for privileged users' in course
                   15788: environment -- set via:  Course Settings -> Classlists and staff listing).
                   15789: 
                   15790: =item *
                   15791: 
                   15792: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   15793: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   15794: $possdomains and $possroles are optional array refs -- to domains to check and
                   15795: roles to check.  If $possdomains is not specified, a dump will be done of the
                   15796: users' roles.db to check for a dc or su role in any domain. This can be
                   15797: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   15798: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   15799: this then allows &privileged_by_domain() to be used, which caches the identity
                   15800: of privileged users, eliminating the need for repeated calls to &dump().
                   15801: 
                   15802: =item *
                   15803: 
                   15804: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   15805: where the outer hash keys are domains specified in the $possdomains array ref,
                   15806: next inner hash keys are privileged roles specified in the $roles array ref,
                   15807: and the innermost hash contains key = value pairs for username:domain = end:start
                   15808: for active or future "privileged" users with that role in that domain. To avoid
                   15809: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   15810: innerhash are cached using priv_$role and $dom as the identifiers.
1.1172.2.13  raeburn  15811: 
1.243     albertel 15812: =back
                   15813: 
                   15814: =head2 User Modification
                   15815: 
                   15816: =over 4
                   15817: 
                   15818: =item *
                   15819: 
1.957     raeburn  15820: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 15821: user for the level given by URL.  Optional start and end dates (leave empty
                   15822: string or zero for "no date")
1.191     harris41 15823: 
                   15824: =item *
                   15825: 
1.243     albertel 15826: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   15827: change a users, password, possible return values are: ok,
                   15828: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   15829: refused
1.191     harris41 15830: 
                   15831: =item *
                   15832: 
1.243     albertel 15833: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 15834: 
                   15835: =item *
                   15836: 
1.1058    raeburn  15837: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   15838:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   15839: 
                   15840: will update user information (firstname,middlename,lastname,generation,
                   15841: permanentemail), and if forceid is true, student/employee ID also.
                   15842: A user's institutional affiliation(s) can also be updated.
                   15843: User information fields will not be overwritten with empty entries 
                   15844: unless the field is included in the $candelete array reference.
                   15845: This array is included when a single user is modified via "Manage Users",
                   15846: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 15847: 
                   15848: =item *
                   15849: 
1.286     matthew  15850: modifystudent
                   15851: 
1.957     raeburn  15852: modify a student's enrollment and identification information.
1.1172.2.31  raeburn  15853: The course id is resolved based on the current user's environment.  
                   15854: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  15855: associated with a course.
                   15856: 
1.297     matthew  15857: This call is essentially a wrapper for lonnet::modifyuser and
                   15858: lonnet::modify_student_enrollment
1.286     matthew  15859: 
                   15860: Inputs: 
                   15861: 
                   15862: =over 4
                   15863: 
1.957     raeburn  15864: =item B<$udom> Student's loncapa domain
1.286     matthew  15865: 
1.957     raeburn  15866: =item B<$uname> Student's loncapa login name
1.286     matthew  15867: 
1.964     bisitz   15868: =item B<$uid> Student/Employee ID
1.286     matthew  15869: 
1.957     raeburn  15870: =item B<$umode> Student's authentication mode
1.286     matthew  15871: 
1.957     raeburn  15872: =item B<$upass> Student's password
1.286     matthew  15873: 
1.957     raeburn  15874: =item B<$first> Student's first name
1.286     matthew  15875: 
1.957     raeburn  15876: =item B<$middle> Student's middle name
1.286     matthew  15877: 
1.957     raeburn  15878: =item B<$last> Student's last name
1.286     matthew  15879: 
1.957     raeburn  15880: =item B<$gene> Student's generation
1.286     matthew  15881: 
1.957     raeburn  15882: =item B<$usec> Student's section in course
1.286     matthew  15883: 
                   15884: =item B<$end> Unix time of the roles expiration
                   15885: 
                   15886: =item B<$start> Unix time of the roles start date
                   15887: 
                   15888: =item B<$forceid> If defined, allow $uid to be changed
                   15889: 
                   15890: =item B<$desiredhome> server to use as home server for student
                   15891: 
1.957     raeburn  15892: =item B<$email> Student's permanent e-mail address
                   15893: 
                   15894: =item B<$type> Type of enrollment (auto or manual)
                   15895: 
1.963     raeburn  15896: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   15897: 
                   15898: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  15899: 
1.963     raeburn  15900: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  15901: 
1.963     raeburn  15902: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  15903: 
1.1172.2.19  raeburn  15904: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   15905: 
                   15906: =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  15907: 
1.286     matthew  15908: =back
1.297     matthew  15909: 
                   15910: =item *
                   15911: 
                   15912: modify_student_enrollment
                   15913: 
1.1172.2.31  raeburn  15914: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  15915: 'role.request.course' must be defined for this function to proceed.
                   15916: 
                   15917: Inputs:
                   15918: 
                   15919: =over 4
                   15920: 
1.1172.2.31  raeburn  15921: =item $udom, student's domain
1.297     matthew  15922: 
1.1172.2.31  raeburn  15923: =item $uname, student's name
1.297     matthew  15924: 
1.1172.2.31  raeburn  15925: =item $uid, student's user id
1.297     matthew  15926: 
1.1172.2.31  raeburn  15927: =item $first, student's first name
1.297     matthew  15928: 
                   15929: =item $middle
                   15930: 
                   15931: =item $last
                   15932: 
                   15933: =item $gene
                   15934: 
                   15935: =item $usec
                   15936: 
                   15937: =item $end
                   15938: 
                   15939: =item $start
                   15940: 
1.957     raeburn  15941: =item $type
                   15942: 
                   15943: =item $locktype
                   15944: 
                   15945: =item $cid
                   15946: 
                   15947: =item $selfenroll
                   15948: 
                   15949: =item $context
                   15950: 
1.1172.2.19  raeburn  15951: =item $credits, number of credits student will earn from this class
                   15952: 
1.1172.2.76  raeburn  15953: =item $instsec, institutional course section code for student
                   15954: 
1.297     matthew  15955: =back
                   15956: 
1.191     harris41 15957: 
                   15958: =item *
                   15959: 
1.243     albertel 15960: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   15961: custom role; give a custom role to a user for the level given by URL.  Specify
                   15962: name and domain of role author, and role name
1.191     harris41 15963: 
                   15964: =item *
                   15965: 
1.243     albertel 15966: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 15967: 
                   15968: =item *
                   15969: 
1.243     albertel 15970: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   15971: 
                   15972: =back
                   15973: 
                   15974: =head2 Course Infomation
                   15975: 
                   15976: =over 4
1.191     harris41 15977: 
                   15978: =item *
                   15979: 
1.1118    foxr     15980: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 15981: specified course id, including all environment settings for the
                   15982: course, the description of the course will be in the hash under the
                   15983: key 'description'
1.191     harris41 15984: 
1.1118    foxr     15985: $options is an optional parameter that if supplied is a hash reference that controls
                   15986: what how this function works.  It has the following key/values:
                   15987: 
                   15988: =over 4
                   15989: 
                   15990: =item freshen_cache
                   15991: 
                   15992: If defined, and the environment cache for the course is valid, it is 
                   15993: returned in the returned hash.
                   15994: 
                   15995: =item one_time
                   15996: 
                   15997: If defined, the last cache time is set to _now_
                   15998: 
                   15999: =item user
                   16000: 
                   16001: If defined, the supplied username is used instead of the current user.
                   16002: 
                   16003: 
                   16004: =back
                   16005: 
1.191     harris41 16006: =item *
                   16007: 
1.624     albertel 16008: resdata($name,$domain,$type,@which) : request for current parameter
                   16009: setting for a specific $type, where $type is either 'course' or 'user',
                   16010: @what should be a list of parameters to ask about. This routine caches
1.1172.2.31  raeburn  16011: answers for 10 minutes.
1.243     albertel 16012: 
1.877     foxr     16013: =item *
                   16014: 
                   16015: get_courseresdata($courseid, $domain) : dump the entire course resource
                   16016: data base, returning a hash that is keyed by the resource name and has
                   16017: values that are the resource value.  I believe that the timestamps and
                   16018: versions are also returned.
                   16019: 
1.243     albertel 16020: =back
                   16021: 
                   16022: =head2 Course Modification
                   16023: 
                   16024: =over 4
1.191     harris41 16025: 
                   16026: =item *
                   16027: 
1.243     albertel 16028: writecoursepref($courseid,%prefs) : write preferences (environment
                   16029: database) for a course
1.191     harris41 16030: 
                   16031: =item *
                   16032: 
1.1011    raeburn  16033: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   16034: 
                   16035: =item *
                   16036: 
1.1038    raeburn  16037: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 16038: 
1.1167    droeschl 16039: =item *
                   16040: 
                   16041: is_course($courseid), is_course($cdom, $cnum)
                   16042: 
                   16043: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   16044: two component version $cdom, $cnum. It checks if the specified course exists.
                   16045: 
                   16046: Returns:
                   16047:     undef if the course doesn't exist, otherwise
                   16048:     in scalar context the combined courseid.
                   16049:     in list context the two components of the course identifier, domain and 
                   16050:     courseid.    
                   16051: 
1.243     albertel 16052: =back
                   16053: 
1.1172.2.109  raeburn  16054: =head2 Bubblesheet Configuration
                   16055: 
                   16056: =over 4
                   16057: 
                   16058: =item *
                   16059: 
                   16060: get_scantron_config($which)
                   16061: 
                   16062: $which - the name of the configuration to parse from the file.
                   16063: 
                   16064: Parses and returns the bubblesheet configuration line selected as a
                   16065: hash of configuration file fields.
                   16066: 
                   16067: 
                   16068: Returns:
                   16069:     If the named configuration is not in the file, an empty
                   16070:     hash is returned.
                   16071: 
                   16072:     a hash with the fields
                   16073:       name         - internal name for the this configuration setup
                   16074:       description  - text to display to operator that describes this config
                   16075:       CODElocation - if 0 or the string 'none'
                   16076:                           - no CODE exists for this config
                   16077:                      if -1 || the string 'letter'
                   16078:                           - a CODE exists for this config and is
                   16079:                             a string of letters
                   16080:                      Unsupported value (but planned for future support)
                   16081:                           if a positive integer
                   16082:                                - The CODE exists as the first n items from
                   16083:                                  the question section of the form
                   16084:                           if the string 'number'
                   16085:                                - The CODE exists for this config and is
                   16086:                                  a string of numbers
                   16087:       CODEstart   - (only matter if a CODE exists) column in the line where
                   16088:                      the CODE starts
                   16089:       CODElength  - length of the CODE
                   16090:       IDstart     - column where the student/employee ID starts
                   16091:       IDlength    - length of the student/employee ID info
                   16092:       Qstart      - column where the information from the bubbled
                   16093:                     'questions' start
                   16094:       Qlength     - number of columns comprising a single bubble line from
                   16095:                     the sheet. (usually either 1 or 10)
                   16096:       Qon         - either a single character representing the character used
                   16097:                     to signal a bubble was chosen in the positional setup, or
                   16098:                     the string 'letter' if the letter of the chosen bubble is
                   16099:                     in the final, or 'number' if a number representing the
                   16100:                     chosen bubble is in the file (1->A 0->J)
                   16101:       Qoff        - the character used to represent that a bubble was
                   16102:                     left blank
                   16103:       PaperID     - if the scanning process generates a unique number for each
                   16104:                     sheet scanned the column that this ID number starts in
                   16105:       PaperIDlength - number of columns that comprise the unique ID number
                   16106:                       for the sheet of paper
                   16107:       FirstName   - column that the first name starts in
                   16108:       FirstNameLength - number of columns that the first name spans
                   16109:       LastName    - column that the last name starts in
                   16110:       LastNameLength - number of columns that the last name spans
                   16111:       BubblesPerRow - number of bubbles available in each row used to
                   16112:                       bubble an answer. (If not specified, 10 assumed).
                   16113: 
                   16114: 
                   16115: =item *
                   16116: 
                   16117: get_scantronformat_file($cdom)
                   16118: 
                   16119: $cdom - the course's domain (optional); if not supplied, uses
                   16120: domain for current $env{'request.course.id'}.
                   16121: 
                   16122: Returns an array containing lines from the scantron format file for
                   16123: the domain of the course.
                   16124: 
                   16125: If a url for a custom.tab file is listed in domain's configuration.db,
                   16126: lines are from this file.
                   16127: 
                   16128: Otherwise, if a default.tab has been published in RES space by the
                   16129: domainconfig user, lines are from this file.
                   16130: 
                   16131: Otherwise, fall back to getting lines from the legacy file on the
                   16132: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   16133: 
                   16134: =back
                   16135: 
1.243     albertel 16136: =head2 Resource Subroutines
                   16137: 
                   16138: =over 4
1.191     harris41 16139: 
                   16140: =item *
                   16141: 
1.243     albertel 16142: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 16143: 
                   16144: =item *
                   16145: 
1.243     albertel 16146: repcopy($filename) : subscribes to the requested file, and attempts to
                   16147: replicate from the owning library server, Might return
1.607     raeburn  16148: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   16149: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 16150: resource. Expects the local filesystem pathname
                   16151: (/home/httpd/html/res/....)
                   16152: 
                   16153: =back
                   16154: 
                   16155: =head2 Resource Information
                   16156: 
                   16157: =over 4
1.191     harris41 16158: 
                   16159: =item *
                   16160: 
1.1172.2.28  raeburn  16161: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   16162: and returns the value of a variety of different possible values,
                   16163: $varname should be a request string, and the other parameters can be
                   16164: used to specify who and what one is asking about. Ordinarily, $cid 
                   16165: does not need to be specified, as it is retrived from 
                   16166: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   16167: within lonuserstate::loadmap() when initializing a course, before
                   16168: $env{'request.course.id'} has been set, so it needs to be provided
                   16169: in that one case.
1.243     albertel 16170: 
                   16171: Possible values for $varname are environment.lastname (or other item
                   16172: from the envirnment hash), user.name (or someother aspect about the
                   16173: user), resource.0.maxtries (or some other part and parameter of a
                   16174: resource)
1.204     albertel 16175: 
                   16176: =item *
                   16177: 
1.243     albertel 16178: directcondval($number) : get current value of a condition; reads from a state
                   16179: string
1.204     albertel 16180: 
                   16181: =item *
                   16182: 
1.243     albertel 16183: condval($condidx) : value of condition index based on state
1.204     albertel 16184: 
                   16185: =item *
                   16186: 
1.1172.2.146.  .13(raeb 16187:-23): metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 16188: resource's metadata, $what should be either a specific key, or either
                   16189: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1172.2.146.  .13(raeb 16190:-23): packages that this resource currently uses, the last 3 arguments are
                   16191:-23): only used internally for recursive metadata.
                   16192:-23): 
                   16193:-23): the toolsymb is only used where the uri is for an external tool (for which
                   16194:-23): the uri as well as the symb are guaranteed to be unique).
1.243     albertel 16195: 
                   16196: this function automatically caches all requests
1.191     harris41 16197: 
                   16198: =item *
                   16199: 
1.243     albertel 16200: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   16201: network of library servers; returns file handle of where SQL and regex results
                   16202: will be stored for query
1.191     harris41 16203: 
                   16204: =item *
                   16205: 
1.1172.2.66  raeburn  16206: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
                   16207: return symbolic list entry (all arguments optional).
                   16208: 
                   16209: Args: filename is the filename (including path) for the file for which a symb
                   16210: is required; donotrecurse, if true will prevent calls to allowed() being made
                   16211: to check access status if more than one resource was found in the bighash
                   16212: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
                   16213: a randompick); ignorecachednull, if true will prevent a symb of '' being
                   16214: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   16215: cause possible symbs to be checked to determine if they are subject to content
                   16216: blocking, if so they will not be included as possible symbs; possibles is a
                   16217: ref to a hash, which, as a side effect, will be populated with all possible
                   16218: symbs (content blocking not tested).
                   16219: 
1.243     albertel 16220: returns the data handle
1.191     harris41 16221: 
                   16222: =item *
                   16223: 
1.1172.2.17  raeburn  16224: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
1.1172.2.11  raeburn  16225: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 16226: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1172.2.11  raeburn  16227: on failure, user must be in a course, as it assumes the existence of
                   16228: the course initial hash, and uses $env('request.course.id'}.  The third
                   16229: arg is an optional reference to a scalar.  If this arg is passed in the
                   16230: call to symbverify, it will be set to 1 if the symb has been set to be 
                   16231: encrypted; otherwise it will be null.
1.243     albertel 16232: 
1.191     harris41 16233: =item *
                   16234: 
1.243     albertel 16235: symbclean($symb) : removes versions numbers from a symb, returns the
                   16236: cleaned symb
1.191     harris41 16237: 
                   16238: =item *
                   16239: 
1.243     albertel 16240: is_on_map($uri) : checks if the $uri is somewhere on the current
                   16241: course map, user must be in a course for it to work.
1.191     harris41 16242: 
                   16243: =item *
                   16244: 
1.243     albertel 16245: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 16246: 
                   16247: =item *
                   16248: 
1.243     albertel 16249: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   16250: a random seed, all arguments are optional, if they aren't sent it uses the
                   16251: environment to derive them. Note: if symb isn't sent and it can't get one
                   16252: from &symbread it will use the current time as its return value
1.191     harris41 16253: 
                   16254: =item *
                   16255: 
1.243     albertel 16256: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   16257: unfakeable, receipt
1.191     harris41 16258: 
                   16259: =item *
                   16260: 
1.620     albertel 16261: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 16262: 
                   16263: =item *
                   16264: 
1.243     albertel 16265: countacc($url) : count the number of accesses to a given URL
1.191     harris41 16266: 
                   16267: =item *
                   16268: 
1.243     albertel 16269: 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 16270: 
                   16271: =item *
                   16272: 
1.243     albertel 16273: 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 16274: 
                   16275: =item *
                   16276: 
1.243     albertel 16277: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 16278: 
                   16279: =item *
                   16280: 
1.243     albertel 16281: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   16282: forcing spreadsheet to reevaluate the resource scores next time.
                   16283: 
1.1172.2.13  raeburn  16284: =item *
                   16285: 
                   16286: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   16287: when viewing in course context.
                   16288: 
                   16289:  input: six args -- filename (decluttered), course number, course domain,
                   16290:                     url, symb (if registered) and group (if this is a
                   16291:                     group item -- e.g., bulletin board, group page etc.).
                   16292: 
                   16293:  output: array of five scalars --
                   16294:          $cfile -- url for file editing if editable on current server
                   16295:          $home -- homeserver of resource (i.e., for author if published,
                   16296:                                           or course if uploaded.).
                   16297:          $switchserver --  1 if server switch will be needed.
                   16298:          $forceedit -- 1 if icon/link should be to go to edit mode
                   16299:          $forceview -- 1 if icon/link should be to go to view mode
                   16300: 
                   16301: =item *
                   16302: 
                   16303: is_course_upload($file,$cnum,$cdom)
                   16304: 
                   16305: Used in course context to determine if current file was uploaded to
                   16306: the course (i.e., would be found in /userfiles/docs on the course's
                   16307: homeserver.
                   16308: 
                   16309:   input: 3 args -- filename (decluttered), course number and course domain.
                   16310:   output: boolean -- 1 if file was uploaded.
                   16311: 
1.243     albertel 16312: =back
                   16313: 
                   16314: =head2 Storing/Retreiving Data
                   16315: 
                   16316: =over 4
1.191     harris41 16317: 
                   16318: =item *
                   16319: 
1.1172.2.64  raeburn  16320: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
                   16321: permanently for this url; hashref needs to be given and should be a \%hashname;
                   16322: the remaining args aren't required and if they aren't passed or are '' they will
                   16323: be derived from the env (with the exception of $laststore, which is an
                   16324: optional arg used when a user's submission is stored in grading).
                   16325: $laststore is $version=$timestamp, where $version is the most recent version
                   16326: number retrieved for the corresponding $symb in the $namespace db file, and
                   16327: $timestamp is the timestamp for that transaction (UNIX time).
                   16328: $laststore is currently only passed when cstore() is called by
                   16329: structuretags::finalize_storage().
1.191     harris41 16330: 
                   16331: =item *
                   16332: 
1.1172.2.64  raeburn  16333: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
                   16334: but uses critical subroutine
1.191     harris41 16335: 
                   16336: =item *
                   16337: 
1.243     albertel 16338: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   16339: all args are optional
1.191     harris41 16340: 
                   16341: =item *
                   16342: 
1.717     albertel 16343: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   16344: dumps the complete (or key matching regexp) namespace into a hash
                   16345: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   16346: normally &store()ed into
                   16347: 
                   16348: $range should be either an integer '100' (give me the first 100
                   16349:                                            matching records)
                   16350:               or be  two integers sperated by a - with no spaces
                   16351:                  '30-50' (give me the 30th through the 50th matching
                   16352:                           records)
                   16353: 
                   16354: 
                   16355: =item *
                   16356: 
1.1172.2.59  raeburn  16357: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 16358: replaces a &store() version of data with a replacement set of data
                   16359: for a particular resource in a namespace passed in the $storehash hash 
1.1172.2.59  raeburn  16360: reference. If $tolog is true, the transaction is logged in the courselog
                   16361: with an action=PUTSTORE.
1.717     albertel 16362: 
                   16363: =item *
                   16364: 
1.243     albertel 16365: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   16366: works very similar to store/cstore, but all data is stored in a
                   16367: temporary location and can be reset using tmpreset, $storehash should
                   16368: be a hash reference, returns nothing on success
1.191     harris41 16369: 
                   16370: =item *
                   16371: 
1.243     albertel 16372: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   16373: similar to restore, but all data is stored in a temporary location and
                   16374: can be reset using tmpreset. Returns a hash of values on success,
                   16375: error string otherwise.
1.191     harris41 16376: 
                   16377: =item *
                   16378: 
1.243     albertel 16379: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   16380: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 16381: 
                   16382: =item *
                   16383: 
1.243     albertel 16384: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16385: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 16386: 
                   16387: =item *
                   16388: 
1.243     albertel 16389: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   16390: namesp ($udom and $uname are optional)
1.191     harris41 16391: 
                   16392: =item *
                   16393: 
1.702     albertel 16394: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 16395: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 16396: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  16397: 
1.702     albertel 16398: $range should be either an integer '100' (give me the first 100
                   16399:                                            matching records)
                   16400:               or be  two integers sperated by a - with no spaces
                   16401:                  '30-50' (give me the 30th through the 50th matching
                   16402:                           records)
1.449     matthew  16403: =item *
                   16404: 
                   16405: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   16406: $store can be a scalar, an array reference, or if the amount to be 
                   16407: incremented is > 1, a hash reference.
                   16408: 
                   16409: ($udom and $uname are optional)
1.191     harris41 16410: 
                   16411: =item *
                   16412: 
1.243     albertel 16413: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   16414: ($udom and $uname are optional)
1.191     harris41 16415: 
                   16416: =item *
                   16417: 
1.243     albertel 16418: cput($namespace,$storehash,$udom,$uname) : critical put
                   16419: ($udom and $uname are optional)
1.191     harris41 16420: 
                   16421: =item *
                   16422: 
1.748     albertel 16423: newput($namespace,$storehash,$udom,$uname) :
                   16424: 
                   16425: Attempts to store the items in the $storehash, but only if they don't
                   16426: currently exist, if this succeeds you can be certain that you have 
                   16427: successfully created a new key value pair in the $namespace db.
                   16428: 
                   16429: 
                   16430: Args:
                   16431:  $namespace: name of database to store values to
                   16432:  $storehash: hashref to store to the db
                   16433:  $udom: (optional) domain of user containing the db
                   16434:  $uname: (optional) name of user caontaining the db
                   16435: 
                   16436: Returns:
                   16437:  'ok' -> succeeded in storing all keys of $storehash
                   16438:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   16439:                         least <key> already existed in the db (other
                   16440:                         requested keys may also already exist)
1.967     bisitz   16441:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 16442:  'con_lost' -> unable to contact request server
                   16443:  'refused' -> action was not allowed by remote machine
                   16444: 
                   16445: 
                   16446: =item *
                   16447: 
1.243     albertel 16448: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16449: reference filled in from namesp (encrypts the return communication)
                   16450: ($udom and $uname are optional)
1.191     harris41 16451: 
                   16452: =item *
                   16453: 
1.243     albertel 16454: log($udom,$name,$home,$message) : write to permanent log for user; use
                   16455: critical subroutine
                   16456: 
1.806     raeburn  16457: =item *
                   16458: 
1.860     raeburn  16459: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   16460: array reference filled in from namespace found in domain level on either
                   16461: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  16462: 
                   16463: =item *
                   16464: 
1.860     raeburn  16465: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   16466: domain level either on specified domain server ($uhome) or primary domain 
                   16467: server ($udom and $uhome are optional)
1.806     raeburn  16468: 
1.943     raeburn  16469: =item * 
                   16470: 
1.1172.2.35  raeburn  16471: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
                   16472: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   16473: the target domain.
                   16474: 
                   16475: May also include additional key => value pairs for the following groups:
                   16476: 
                   16477: =over
                   16478: 
                   16479: =item
                   16480: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   16481: 
                   16482: =over
                   16483: 
                   16484: =item defaultquota, authorquota
                   16485: 
                   16486: =back
                   16487: 
                   16488: =item
                   16489: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   16490: portfolio for users).
                   16491: 
                   16492: =over
                   16493: 
                   16494: =item
                   16495: aboutme, blog, webdav, portfolio
                   16496: 
                   16497: =back
                   16498: 
                   16499: =item
                   16500: requestcourses: ability to request courses, and how requests are processed.
                   16501: 
                   16502: =over
                   16503: 
                   16504: =item
1.1172.2.37  raeburn  16505: official, unofficial, community, textbook
1.1172.2.35  raeburn  16506: 
                   16507: =back
                   16508: 
                   16509: =item
                   16510: inststatus: types of institutional affiliation, and order in which they are displayed.
                   16511: 
                   16512: =over
                   16513: 
                   16514: =item
1.1172.2.44  raeburn  16515: inststatustypes, inststatusorder, inststatusguest
1.1172.2.35  raeburn  16516: 
                   16517: =back
                   16518: 
                   16519: =item
                   16520: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   16521: for course's uploaded content.
                   16522: 
                   16523: =over
                   16524: 
                   16525: =item
1.1172.2.68  raeburn  16526: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
                   16527: communityquota, textbookquota
1.1172.2.35  raeburn  16528: 
                   16529: =back
                   16530: 
                   16531: =item
                   16532: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   16533: on your servers.
                   16534: 
                   16535: =over
                   16536: 
                   16537: =item
                   16538: remotesessions, hostedsessions
                   16539: 
                   16540: =back
                   16541: 
                   16542: =back
                   16543: 
                   16544: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   16545: utility to create a configuration.db file on a domain's primary library server
                   16546: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   16547: -- corresponding values are authentication type (internal, krb4, krb5,
                   16548: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
                   16549: will be available. Values are retrieved from cache (if current), unless the
                   16550: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   16551: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   16552: 
                   16553: Typical usage:
1.943     raeburn  16554: 
1.1172.2.35  raeburn  16555: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  16556: 
1.243     albertel 16557: =back
                   16558: 
                   16559: =head2 Network Status Functions
                   16560: 
                   16561: =over 4
1.191     harris41 16562: 
                   16563: =item *
                   16564: 
1.1137    raeburn  16565: dirlist() : return directory list based on URI (first arg).
                   16566: 
                   16567: Inputs: 1 required, 5 optional.
                   16568: 
                   16569: =over
                   16570: 
                   16571: =item 
                   16572: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   16573: 
                   16574: =item
                   16575: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   16576: 
                   16577: =item
                   16578: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   16579: 
                   16580: =item
                   16581: $getpropath - boolean: 1 if prepend path using &propath(). 
                   16582: 
                   16583: =item
                   16584: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   16585: 
                   16586: =item 
                   16587: $alternateRoot - path to prepend in place of path from $uri.
                   16588: 
                   16589: =back
                   16590: 
                   16591: Returns: Array of up to two items.
                   16592: 
                   16593: =over
                   16594: 
                   16595: a reference to an array of files/subdirectories
                   16596: 
                   16597: =over
                   16598: 
                   16599: Each element in the array of files/subdirectories is a & separated list of
                   16600: item name and the result of running stat on the item.  If dirlist was requested
                   16601: for a file instead of a directory, the item name will be ''. For a directory 
                   16602: listing, if the item is a metadata file, the element will end &N&M 
                   16603: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   16604: default copyright set (1).  
                   16605: 
                   16606: =back
                   16607: 
                   16608: a scalar containing error condition (if encountered).
                   16609: 
                   16610: =over
                   16611: 
                   16612: =item 
                   16613: no_host (no homeserver identified for $username:$domain).
                   16614: 
                   16615: =item 
                   16616: no_such_host (server contacted for listing not identified as valid host).
                   16617: 
                   16618: =item 
                   16619: con_lost (connection to remote server failed).
                   16620: 
                   16621: =item 
                   16622: refused (invalid $username:$domain received on lond side).
                   16623: 
                   16624: =item 
                   16625: no_such_dir (directory at specified path on lond side does not exist). 
                   16626: 
                   16627: =item 
                   16628: empty (directory at specified path on lond side is empty).
                   16629: 
                   16630: =over
                   16631: 
                   16632: This is currently not encountered because the &ls3, &ls2, 
                   16633: &ls (_handler) routines on the lond side do not filter out
                   16634: . and .. from a directory listing. 
                   16635: 
                   16636: =back
                   16637: 
                   16638: =back
                   16639: 
                   16640: =back
1.191     harris41 16641: 
                   16642: =item *
                   16643: 
1.243     albertel 16644: spareserver() : find server with least workload from spare.tab
                   16645: 
1.986     foxr     16646: 
                   16647: =item *
                   16648: 
                   16649: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   16650: if there is no corresponding loncapa host.
                   16651: 
1.243     albertel 16652: =back
                   16653: 
1.986     foxr     16654: 
1.243     albertel 16655: =head2 Apache Request
                   16656: 
                   16657: =over 4
1.191     harris41 16658: 
                   16659: =item *
                   16660: 
1.243     albertel 16661: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   16662: localhost, posts hash
                   16663: 
                   16664: =back
                   16665: 
                   16666: =head2 Data to String to Data
                   16667: 
                   16668: =over 4
1.191     harris41 16669: 
                   16670: =item *
                   16671: 
1.243     albertel 16672: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   16673: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 16674: 
                   16675: =item *
                   16676: 
1.243     albertel 16677: hashref2str($hashref) : convert a hashref into a string complete with
                   16678: escaping and '=' and '&' separators, supports elements that are
                   16679: arrayrefs and hashrefs
1.191     harris41 16680: 
                   16681: =item *
                   16682: 
1.243     albertel 16683: arrayref2str($arrayref) : convert an arrayref into a string complete
                   16684: with escaping and '&' separators, supports elements that are arrayrefs
                   16685: and hashrefs
1.191     harris41 16686: 
                   16687: =item *
                   16688: 
1.243     albertel 16689: str2hash($string) : convert string to hash using unescaping and
                   16690: splitting on '=' and '&', supports elements that are arrayrefs and
                   16691: hashrefs
1.191     harris41 16692: 
                   16693: =item *
                   16694: 
1.243     albertel 16695: str2array($string) : convert string to hash using unescaping and
                   16696: splitting on '&', supports elements that are arrayrefs and hashrefs
                   16697: 
                   16698: =back
                   16699: 
                   16700: =head2 Logging Routines
                   16701: 
                   16702: 
                   16703: These routines allow one to make log messages in the lonnet.log and
                   16704: lonnet.perm logfiles.
1.191     harris41 16705: 
1.1119    foxr     16706: =over 4
                   16707: 
1.191     harris41 16708: =item *
                   16709: 
1.243     albertel 16710: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 16711: 
                   16712: =item *
                   16713: 
1.243     albertel 16714: logthis() : append message to the normal lonnet.log file, it gets
                   16715: preiodically rolled over and deleted.
1.191     harris41 16716: 
                   16717: =item *
                   16718: 
1.243     albertel 16719: logperm() : append a permanent message to lonnet.perm.log, this log
                   16720: file never gets deleted by any automated portion of the system, only
                   16721: messages of critical importance should go in here.
                   16722: 
1.1119    foxr     16723: 
1.243     albertel 16724: =back
                   16725: 
                   16726: =head2 General File Helper Routines
                   16727: 
                   16728: =over 4
1.191     harris41 16729: 
                   16730: =item *
                   16731: 
1.481     raeburn  16732: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   16733: (a) files in /uploaded
                   16734:   (i) If a local copy of the file exists - 
                   16735:       compares modification date of local copy with last-modified date for 
                   16736:       definitive version stored on home server for course. If local copy is 
                   16737:       stale, requests a new version from the home server and stores it. 
                   16738:       If the original has been removed from the home server, then local copy 
                   16739:       is unlinked.
                   16740:   (ii) If local copy does not exist -
                   16741:       requests the file from the home server and stores it. 
                   16742:   
                   16743:   If $caller is 'uploadrep':  
                   16744:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   16745:     for request for files originally uploaded via DOCS. 
                   16746:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   16747:   
                   16748:   Otherwise:
                   16749:      This indicates a call from the content generation phase of the request.
                   16750:      -  returns the entire contents of the file or -1.
                   16751:      
                   16752: (b) files in /res
                   16753:    - returns the entire contents of a file or -1; 
                   16754:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 16755: 
1.712     albertel 16756: 
                   16757: =item *
                   16758: 
                   16759: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   16760:                   reference
                   16761: 
                   16762: returns either a stat() list of data about the file or an empty list
                   16763: if the file doesn't exist or couldn't find out about it (connection
                   16764: problems or user unknown)
                   16765: 
1.191     harris41 16766: =item *
                   16767: 
1.243     albertel 16768: filelocation($dir,$file) : returns file system location of a file
                   16769: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   16770: directory that relative $file lookups are to looked in ($dir of /a/dir
                   16771: and a file of ../bob will become /a/bob)
1.191     harris41 16772: 
                   16773: =item *
                   16774: 
                   16775: hreflocation($dir,$file) : returns file system location or a URL; same as
                   16776: filelocation except for hrefs
                   16777: 
                   16778: =item *
                   16779: 
1.1172.2.49  raeburn  16780: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   16781: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 16782: 
1.243     albertel 16783: =back
                   16784: 
1.608     albertel 16785: =head2 Usererfile file routines (/uploaded*)
                   16786: 
                   16787: =over 4
                   16788: 
                   16789: =item *
                   16790: 
                   16791: userfileupload(): main rotine for putting a file in a user or course's
                   16792:                   filespace, arguments are,
                   16793: 
1.620     albertel 16794:  formname - required - this is the name of the element in $env where the
1.608     albertel 16795:            filename, and the contents of the file to create/modifed exist
1.620     albertel 16796:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   16797:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  16798:  context - if coursedoc, store the file in the course of the active role
                   16799:              of the current user; 
                   16800:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   16801:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 16802:  subdir - required - subdirectory to put the file in under ../userfiles/
                   16803:          if undefined, it will be placed in "unknown"
                   16804: 
                   16805:  (This routine calls clean_filename() to remove any dangerous
                   16806:  characters from the filename, and then calls finuserfileupload() to
                   16807:  complete the transaction)
                   16808: 
                   16809:  returns either the url of the uploaded file (/uploaded/....) if successful
                   16810:  and /adm/notfound.html if unsuccessful
                   16811: 
                   16812: =item *
                   16813: 
                   16814: clean_filename(): routine for cleaing a filename up for storage in
                   16815:                  userfile space, argument is:
                   16816: 
                   16817:  filename - proposed filename
                   16818: 
                   16819: returns: the new clean filename
                   16820: 
                   16821: =item *
                   16822: 
1.1090    raeburn  16823: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 16824: userspace, probably shouldn't be called directly
                   16825: 
                   16826:   docuname: username or courseid of destination for the file
                   16827:   docudom: domain of user/course of destination for the file
                   16828:   formname: same as for userfileupload()
1.1090    raeburn  16829:   fname: filename (including subdirectories) for the file
                   16830:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1172.2.109  raeburn  16831:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  16832:   allfiles: reference to hash used to store objects found by parser
                   16833:   codebase: reference to hash used for codebases of java objects found by parser
                   16834:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   16835:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   16836:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   16837:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   16838:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   16839:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  16840:   mimetype: reference to scalar to accommodate mime type determined
                   16841:             from File::MMagic if $parser = parse.
1.608     albertel 16842: 
                   16843:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  16844:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   16845:  was 'overwrite').
                   16846:  
1.608     albertel 16847: 
                   16848: =item *
                   16849: 
                   16850: renameuserfile(): renames an existing userfile to a new name
                   16851: 
                   16852:   Args:
                   16853:    docuname: username or courseid of destination for the file
                   16854:    docudom: domain of user/course of destination for the file
                   16855:    old: current file name (including any subdirs under userfiles)
                   16856:    new: desired file name (including any subdirs under userfiles)
                   16857: 
                   16858: =item *
                   16859: 
                   16860: mkdiruserfile(): creates a directory is a userfiles dir
                   16861: 
                   16862:   Args:
                   16863:    docuname: username or courseid of destination for the file
                   16864:    docudom: domain of user/course of destination for the file
                   16865:    dir: dir to create (including any subdirs under userfiles)
                   16866: 
                   16867: =item *
                   16868: 
                   16869: removeuserfile(): removes a file that exists in userfiles
                   16870: 
                   16871:   Args:
                   16872:    docuname: username or courseid of destination for the file
                   16873:    docudom: domain of user/course of destination for the file
                   16874:    fname: filname to delete (including any subdirs under userfiles)
                   16875: 
                   16876: =item *
                   16877: 
                   16878: removeuploadedurl(): convience function for removeuserfile()
                   16879: 
                   16880:   Args:
                   16881:    url:  a full /uploaded/... url to delete
                   16882: 
1.747     albertel 16883: =item * 
                   16884: 
                   16885: get_portfile_permissions():
                   16886:   Args:
                   16887:     domain: domain of user or course contain the portfolio files
                   16888:     user: name of user or num of course contain the portfolio files
                   16889:   Returns:
                   16890:     hashref of a dump of the proper file_permissions.db
                   16891:    
                   16892: 
                   16893: =item * 
                   16894: 
                   16895: get_access_controls():
                   16896: 
                   16897: Args:
                   16898:   current_permissions: the hash ref returned from get_portfile_permissions()
                   16899:   group: (optional) the group you want the files associated with
                   16900:   file: (optional) the file you want access info on
                   16901: 
                   16902: Returns:
1.749     raeburn  16903:     a hash (keys are file names) of hashes containing
                   16904:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   16905:         values are XML containing access control settings (see below) 
1.747     albertel 16906: 
                   16907: Internal notes:
                   16908: 
1.749     raeburn  16909:  access controls are stored in file_permissions.db as key=value pairs.
                   16910:     key -> path to file/file_name\0uniqueID:scope_end_start
                   16911:         where scope -> public,guest,course,group,domains or users.
                   16912:               end -> UNIX time for end of access (0 -> no end date)
                   16913:               start -> UNIX time for start of access
                   16914: 
                   16915:     value -> XML description of access control
                   16916:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   16917:             <start></start>
                   16918:             <end></end>
                   16919: 
                   16920:             <password></password>  for scope type = guest
                   16921: 
                   16922:             <domain></domain>     for scope type = course or group
                   16923:             <number></number>
                   16924:             <roles id="">
                   16925:              <role></role>
                   16926:              <access></access>
                   16927:              <section></section>
                   16928:              <group></group>
                   16929:             </roles>
                   16930: 
                   16931:             <dom></dom>         for scope type = domains
                   16932: 
                   16933:             <users>             for scope type = users
                   16934:              <user>
                   16935:               <uname></uname>
                   16936:               <udom></udom>
                   16937:              </user>
                   16938:             </users>
                   16939:            </scope> 
                   16940:               
                   16941:  Access data is also aggregated for each file in an additional key=value pair:
                   16942:  key -> path to file/file_name\0accesscontrol 
                   16943:  value -> reference to hash
                   16944:           hash contains key = value pairs
                   16945:           where key = uniqueID:scope_end_start
                   16946:                 value = UNIX time record was last updated
                   16947: 
                   16948:           Used to improve speed of look-ups of access controls for each file.  
                   16949:  
                   16950:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   16951: 
1.1172.2.13  raeburn  16952: =item *
                   16953: 
1.749     raeburn  16954: modify_access_controls():
                   16955: 
                   16956: Modifies access controls for a portfolio file
                   16957: Args
                   16958: 1. file name
                   16959: 2. reference to hash of required changes,
                   16960: 3. domain
                   16961: 4. username
                   16962:   where domain,username are the domain of the portfolio owner 
                   16963:   (either a user or a course) 
                   16964: 
                   16965: Returns:
                   16966: 1. result of additions or updates ('ok' or 'error', with error message). 
                   16967: 2. result of deletions ('ok' or 'error', with error message).
                   16968: 3. reference to hash of any new or updated access controls.
                   16969: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   16970:    key = integer (inbound ID)
1.1172.2.13  raeburn  16971:    value = uniqueID
                   16972: 
                   16973: =item *
                   16974: 
                   16975: get_timebased_id():
                   16976: 
                   16977: Attempts to get a unique timestamp-based suffix for use with items added to a
                   16978: course via the Course Editor (e.g., folders, composite pages,
                   16979: group bulletin boards).
                   16980: 
                   16981: Args: (first three required; six others optional)
                   16982: 
                   16983: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   16984:    docssequence, or name of group
                   16985: 
                   16986: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   16987:    e.g., num, boardids
                   16988: 
                   16989: 3. namespace: name of gdbm file used to store suffixes already assigned;
                   16990:    file will be named nohist_namespace.db
                   16991: 
                   16992: 4. cdom: domain of course; default is current course domain from %env
                   16993: 
                   16994: 5. cnum: course number; default is current course number from %env
                   16995: 
                   16996: 6. idtype: set to concat if an additional digit is to be appended to the
                   16997:    unix timestamp to form the suffix, if the plain timestamp is already
                   16998:    in use.  Default is to not do this, but simply increment the unix
                   16999:    timestamp by 1 until a unique key is obtained.
                   17000: 
                   17001: 7. who: holder of locking key; defaults to user:domain for user.
                   17002: 
                   17003: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
                   17004:    retrying); default is 3.
                   17005: 
                   17006: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
                   17007: 
                   17008: Returns:
                   17009: 
                   17010: 1. suffix obtained (numeric)
                   17011: 
                   17012: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   17013: 
                   17014: 3. error: contains (localized) error message if an error occurred.
                   17015: 
1.747     albertel 17016: 
1.608     albertel 17017: =back
                   17018: 
1.243     albertel 17019: =head2 HTTP Helper Routines
                   17020: 
                   17021: =over 4
                   17022: 
1.191     harris41 17023: =item *
                   17024: 
                   17025: escape() : unpack non-word characters into CGI-compatible hex codes
                   17026: 
                   17027: =item *
                   17028: 
                   17029: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   17030: 
1.243     albertel 17031: =back
                   17032: 
                   17033: =head1 PRIVATE SUBROUTINES
                   17034: 
                   17035: =head2 Underlying communication routines (Shouldn't call)
                   17036: 
                   17037: =over 4
                   17038: 
                   17039: =item *
                   17040: 
                   17041: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   17042: 
                   17043: =item *
                   17044: 
                   17045: reply() : uses subreply to send a message to remote machine, logs all failures
                   17046: 
                   17047: =item *
                   17048: 
                   17049: critical() : passes a critical message to another server; if cannot
                   17050: get through then place message in connection buffer directory and
                   17051: returns con_delayed, if incapable of saving message, returns
                   17052: con_failed
                   17053: 
                   17054: =item *
                   17055: 
                   17056: reconlonc() : tries to reconnect lonc client processes.
                   17057: 
                   17058: =back
                   17059: 
                   17060: =head2 Resource Access Logging
                   17061: 
                   17062: =over 4
                   17063: 
                   17064: =item *
                   17065: 
                   17066: flushcourselogs() : flush (save) buffer logs and access logs
                   17067: 
                   17068: =item *
                   17069: 
                   17070: courselog($what) : save message for course in hash
                   17071: 
                   17072: =item *
                   17073: 
                   17074: courseacclog($what) : save message for course using &courselog().  Perform
                   17075: special processing for specific resource types (problems, exams, quizzes, etc).
                   17076: 
1.191     harris41 17077: =item *
                   17078: 
                   17079: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   17080: as a PerlChildExitHandler
1.243     albertel 17081: 
                   17082: =back
                   17083: 
                   17084: =head2 Other
                   17085: 
                   17086: =over 4
                   17087: 
                   17088: =item *
                   17089: 
                   17090: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 17091: 
                   17092: =back
                   17093: 
                   17094: =cut
1.877     foxr     17095: 

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