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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1482  ! raeburn     4: # $Id: lonnet.pm,v 1.1481 2022/02/14 02:48:53 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.486     www        74: use HTTP::Date;
1.977     amueller   75: use Image::Magick;
1.1389    raeburn    76: use CGI::Cookie;
1.1182    foxr       77: 
1.1173    foxr       78: use Encode;
                     79: 
1.1405    raeburn    80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
1.1138    raeburn    81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
1.1416    raeburn    82:             %managerstab $passwdmin);
1.871     albertel   83: 
                     84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        87:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        88: 
1.1       albertel   89: use IO::Socket;
1.31      www        90: use GDBM_File;
1.208     albertel   91: use HTML::LCParser;
1.88      www        92: use Fcntl qw(:flock);
1.870     albertel   93: use Storable qw(thaw nfreeze);
1.1289    damieng    94: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   95: use Cache::Memcached;
1.676     albertel   96: use Digest::MD5;
1.790     albertel   97: use Math::Random;
1.1024    raeburn    98: use File::MMagic;
1.1434    raeburn    99: use Net::CIDR;
1.1456    raeburn   100: use Sys::Hostname::FQDN();
1.807     albertel  101: use LONCAPA qw(:DEFAULT :match);
1.740     www       102: use LONCAPA::Configuration;
1.1160    www       103: use LONCAPA::lonmetadata;
1.1167    droeschl  104: use LONCAPA::Lond;
1.1345    raeburn   105: use LONCAPA::LWPReq;
1.1406    raeburn   106: use LONCAPA::transliterate;
1.1117    foxr      107: 
1.1090    raeburn   108: use File::Copy;
1.676     albertel  109: 
1.195     www       110: my $readit;
1.1288    damieng   111: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  112: 
1.619     albertel  113: require Exporter;
                    114: 
                    115: our @ISA = qw (Exporter);
                    116: our @EXPORT = qw(%env);
                    117: 
1.449     matthew   118: 
1.1187    raeburn   119: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       120: {
                    121:     my $logid;
1.1187    raeburn   122:     sub write_log {
1.1188    raeburn   123: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184    raeburn   124:         if ($context eq 'course') {
                    125:             if (($cnum eq '') || ($cdom eq '')) {
                    126:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    127:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    128:             }
1.957     raeburn   129:         }
1.1184    raeburn   130: 	$logid ++;
1.957     raeburn   131:         my $now = time();
                    132: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1434    raeburn   133:         my $ip = &get_requestor_ip();
1.1184    raeburn   134:         my $logentry = { 
                    135:                           $id => {
                    136:                                    'exe_uname' => $env{'user.name'},
                    137:                                    'exe_udom'  => $env{'user.domain'},
                    138:                                    'exe_time'  => $now,
1.1434    raeburn   139:                                    'exe_ip'    => $ip,
1.1184    raeburn   140:                                    'delflag'   => $delflag,
                    141:                                    'logentry'  => $storehash,
                    142:                                    'uname'     => $uname,
                    143:                                    'udom'      => $udom,
                    144:                                   }
                    145:                        };
                    146: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       147:     }
                    148: }
1.1       albertel  149: 
1.163     harris41  150: sub logtouch {
                    151:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  152:     unless (-e "$execdir/logs/lonnet.log") {	
1.1359    raeburn   153: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  154: 	close $fh;
                    155:     }
                    156:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    157:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    158: }
                    159: 
1.1       albertel  160: sub logthis {
                    161:     my $message=shift;
                    162:     my $execdir=$perlvar{'lonDaemons'};
                    163:     my $now=time;
                    164:     my $local=localtime($now);
1.1359    raeburn   165:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      166: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    167: 	print $fh $logstring;
1.448     albertel  168: 	close($fh);
                    169:     }
1.1       albertel  170:     return 1;
                    171: }
                    172: 
                    173: sub logperm {
                    174:     my $message=shift;
                    175:     my $execdir=$perlvar{'lonDaemons'};
                    176:     my $now=time;
                    177:     my $local=localtime($now);
1.1359    raeburn   178:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  179: 	print $fh "$now:$message:$local\n";
                    180: 	close($fh);
                    181:     }
1.1       albertel  182:     return 1;
                    183: }
                    184: 
1.850     albertel  185: sub create_connection {
1.853     albertel  186:     my ($hostname,$lonid) = @_;
1.851     albertel  187:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  188: 				     Type    => SOCK_STREAM,
                    189: 				     Timeout => 10);
                    190:     return 0 if (!$client);
1.1399    raeburn   191:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname),$loncaparevs{$lonid})."\n");
1.850     albertel  192:     my $result = <$client>;
                    193:     chomp($result);
                    194:     return 1 if ($result eq 'done');
                    195:     return 0;
                    196: }
                    197: 
1.983     raeburn   198: sub get_server_timezone {
                    199:     my ($cnum,$cdom) = @_;
                    200:     my $home=&homeserver($cnum,$cdom);
                    201:     if ($home ne 'no_host') {
                    202:         my $cachetime = 24*3600;
                    203:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    204:         if (defined($cached)) {
                    205:             return $timezone;
                    206:         } else {
                    207:             my $timezone = &reply('servertimezone',$home);
                    208:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    209:         }
                    210:     }
                    211: }
1.850     albertel  212: 
1.1106    raeburn   213: sub get_server_distarch {
                    214:     my ($lonhost,$ignore_cache) = @_;
                    215:     if (defined($lonhost)) {
                    216:         if (!defined(&hostname($lonhost))) {
                    217:             return;
                    218:         }
                    219:         my $cachetime = 12*3600;
                    220:         if (!$ignore_cache) {
                    221:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    222:             if (defined($cached)) {
                    223:                 return $distarch;
                    224:             }
                    225:         }
                    226:         my $rep = &reply('serverdistarch',$lonhost);
                    227:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    228:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    229:                 $rep eq '') {
                    230:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    231:         }
                    232:     }
                    233:     return;
                    234: }
                    235: 
1.1315    raeburn   236: sub get_servercerts_info {
1.1383    raeburn   237:     my ($lonhost,$hostname,$context) = @_;
                    238:     return if ($lonhost eq '');
                    239:     if ($hostname eq '') {
                    240:         $hostname = &hostname($lonhost);
                    241:     }
                    242:     return if ($hostname eq '');
1.1315    raeburn   243:     my ($rep,$uselocal);
1.1388    raeburn   244:     if ($context eq 'install') {
1.1387    raeburn   245:         $uselocal = 1;
                    246:     } elsif (grep { $_ eq $lonhost } &current_machine_ids()) {
1.1315    raeburn   247:         $uselocal = 1;
                    248:     }
1.1387    raeburn   249:     if (($context ne 'cgi') && ($context ne 'install') && ($uselocal)) {
1.1315    raeburn   250:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
1.1323    raeburn   251:         if ($distro eq '') {
                    252:             $uselocal = 0;
                    253:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
1.1315    raeburn   254:             if ($1 < 6) {
                    255:                 $uselocal = 0;
                    256:             }
1.1346    raeburn   257:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
                    258:             if ($1 < 12) {
                    259:                 $uselocal = 0;
                    260:             }
1.1315    raeburn   261:         }
                    262:     }
                    263:     if ($uselocal) {
1.1383    raeburn   264:         $rep = LONCAPA::Lond::server_certs(\%perlvar,$lonhost,$hostname);
1.1315    raeburn   265:     } else {
                    266:         $rep=&reply('servercerts',$lonhost);
                    267:     }
                    268:     my ($result,%returnhash);
                    269:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    270:         ($rep eq 'unknown_cmd')) {
                    271:         $result = $rep;
                    272:     } else {
                    273:         $result = 'ok';
                    274:         my @pairs=split(/\&/,$rep);
                    275:         foreach my $item (@pairs) {
                    276:             my ($key,$value)=split(/=/,$item,2);
                    277:             my $what = &unescape($key);
                    278:             $returnhash{$what}=&thaw_unescape($value);
                    279:         }
                    280:     }
                    281:     return ($result,\%returnhash);
                    282: }
                    283: 
1.993     raeburn   284: sub get_server_loncaparev {
1.1073    raeburn   285:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   286:     if (defined($lonhost)) {
                    287:         if (!defined(&hostname($lonhost))) {
                    288:             undef($lonhost);
                    289:         }
                    290:     }
                    291:     if (!defined($lonhost)) {
                    292:         if (defined(&domain($dom,'primary'))) {
                    293:             $lonhost=&domain($dom,'primary');
                    294:             if ($lonhost eq 'no_host') {
                    295:                 undef($lonhost);
                    296:             }
                    297:         }
                    298:     }
                    299:     if (defined($lonhost)) {
1.1073    raeburn   300:         my $cachetime = 12*3600;
                    301:         if (!$ignore_cache) {
                    302:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    303:             if (defined($cached)) {
                    304:                 return $loncaparev;
                    305:             }
                    306:         }
                    307:         my ($answer,$loncaparev);
                    308:         my @ids=&current_machine_ids();
                    309:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    310:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   311:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   312:                 $loncaparev = $1;
                    313:             }
                    314:         } else {
                    315:             $answer = &reply('serverloncaparev',$lonhost);
                    316:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    317:                 if ($caller eq 'loncron') {
1.1397    raeburn   318:                     my $hostname = &hostname($lonhost);
1.1073    raeburn   319:                     my $protocol = $protocol{$lonhost};
                    320:                     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn   321:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
1.1073    raeburn   322:                     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn   323:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
1.1073    raeburn   324:                     unless ($response->is_error()) {
                    325:                         my $content = $response->content;
1.1081    raeburn   326:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   327:                             $loncaparev = $1;
                    328:                         }
                    329:                     }
                    330:                 } else {
                    331:                     $loncaparev = $loncaparevs{$lonhost};
                    332:                 }
1.1081    raeburn   333:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   334:                 $loncaparev = $1;
                    335:             }
1.993     raeburn   336:         }
1.1073    raeburn   337:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   338:     }
                    339: }
                    340: 
1.1074    raeburn   341: sub get_server_homeID {
                    342:     my ($hostname,$ignore_cache,$caller) = @_;
                    343:     unless ($ignore_cache) {
                    344:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    345:         if (defined($cached)) {
                    346:             return $serverhomeID;
                    347:         }
                    348:     }
                    349:     my $cachetime = 12*3600;
                    350:     my $serverhomeID;
                    351:     if ($caller eq 'loncron') { 
                    352:         my @machine_ids = &machine_ids($hostname);
                    353:         foreach my $id (@machine_ids) {
                    354:             my $response = &reply('serverhomeID',$id);
                    355:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    356:                 $serverhomeID = $response;
                    357:                 last;
                    358:             }
                    359:         }
                    360:         if ($serverhomeID eq '') {
                    361:             $serverhomeID = $machine_ids[-1];
                    362:         }
                    363:     } else {
                    364:         $serverhomeID = $serverhomeIDs{$hostname};
                    365:     }
                    366:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    367: }
                    368: 
1.1121    raeburn   369: sub get_remote_globals {
                    370:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   371:     my ($result,%returnhash,%whatneeded);
                    372:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   373:         foreach my $what (sort(keys(%{$whathash}))) {
                    374:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   375:             my ($response,$cached);
1.1121    raeburn   376:             unless ($ignore_cache) {
1.1125    raeburn   377:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   378:             }
                    379:             if (defined($cached)) {
1.1125    raeburn   380:                 $returnhash{$what} = $response;
1.1121    raeburn   381:             } else {
1.1125    raeburn   382:                 $whatneeded{$what} = 1;
1.1121    raeburn   383:             }
                    384:         }
1.1125    raeburn   385:         if (keys(%whatneeded) == 0) {
                    386:             $result = 'ok';
                    387:         } else {
1.1121    raeburn   388:             my $requested = &freeze_escape(\%whatneeded);
                    389:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   390:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    391:                 ($rep eq 'unknown_cmd')) {
                    392:                 $result = $rep;
                    393:             } else {
                    394:                 $result = 'ok';
1.1121    raeburn   395:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   396:                 foreach my $item (@pairs) {
                    397:                     my ($key,$value)=split(/=/,$item,2);
                    398:                     my $what = &unescape($key);
                    399:                     my $hashid = $lonhost.'-'.$what;
                    400:                     $returnhash{$what}=&thaw_unescape($value);
                    401:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   402:                 }
                    403:             }
                    404:         }
                    405:     }
1.1125    raeburn   406:     return ($result,\%returnhash);
1.1121    raeburn   407: }
                    408: 
1.1124    raeburn   409: sub remote_devalidate_cache {
1.1241    raeburn   410:     my ($lonhost,$cachekeys) = @_;
                    411:     my $items;
                    412:     return unless (ref($cachekeys) eq 'ARRAY');
                    413:     my $cachestr = join('&',@{$cachekeys});
                    414:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   415:     return $response;
                    416: }
                    417: 
1.1       albertel  418: # -------------------------------------------------- Non-critical communication
                    419: sub subreply {
                    420:     my ($cmd,$server)=@_;
1.838     albertel  421:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      422:     #
                    423:     #  With loncnew process trimming, there's a timing hole between lonc server
                    424:     #  process exit and the master server picking up the listen on the AF_UNIX
                    425:     #  socket.  In that time interval, a lock file will exist:
                    426: 
                    427:     my $lockfile=$peerfile.".lock";
                    428:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1289    damieng   429: 	sleep(0.1);
1.549     foxr      430:     }
                    431:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      432:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      433:     #
1.550     foxr      434:     #   We'll give the connection a few tries before abandoning it.  If
                    435:     #   connection is not possible, we'll con_lost back to the client.
                    436:     #   
                    437:     my $client;
                    438:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    439: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    440: 				      Type    => SOCK_STREAM,
                    441: 				      Timeout => 10);
1.869     albertel  442: 	if ($client) {
1.550     foxr      443: 	    last;		# Connected!
1.850     albertel  444: 	} else {
1.853     albertel  445: 	    &create_connection(&hostname($server),$server);
1.550     foxr      446: 	}
1.1289    damieng   447:         sleep(0.1);	# Try again later if failed connection.
1.550     foxr      448:     }
                    449:     my $answer;
                    450:     if ($client) {
1.704     albertel  451: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      452: 	$answer=<$client>;
                    453: 	if (!$answer) { $answer="con_lost"; }
                    454: 	chomp($answer);
                    455:     } else {
                    456: 	$answer = 'con_lost';	# Failed connection.
                    457:     }
1.1       albertel  458:     return $answer;
                    459: }
                    460: 
                    461: sub reply {
                    462:     my ($cmd,$server)=@_;
1.838     albertel  463:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  464:     my $answer=subreply($cmd,$server);
1.65      www       465:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.1396    raeburn   466:         my $logged = $cmd;
                    467:         if ($cmd =~ /^encrypt:([^:]+):/) {
                    468:             my $subcmd = $1;
                    469:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
                    470:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
1.1462    raeburn   471:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades') ||
                    472:                 ($subcmd eq 'put')) {
1.1396    raeburn   473:                 (undef,undef,my @rest) = split(/:/,$cmd);
                    474:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
                    475:                     splice(@rest,2,1,'Hidden');
                    476:                 } elsif ($subcmd eq 'passwd') {
                    477:                     splice(@rest,2,2,('Hidden','Hidden'));
                    478:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
1.1462    raeburn   479:                          ($subcmd eq 'autoexportgrades') || ($subcmd eq 'put')) {
1.1396    raeburn   480:                     splice(@rest,3,1,'Hidden');
                    481:                 }
                    482:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
                    483:             }
                    484:         }
                    485:         &logthis("<font color=\"blue\">WARNING:".
                    486:                  " $logged to $server returned $answer</font>");
1.12      www       487:     }
1.1       albertel  488:     return $answer;
                    489: }
                    490: 
                    491: # ----------------------------------------------------------- Send USR1 to lonc
                    492: 
                    493: sub reconlonc {
1.891     albertel  494:     my ($lonid) = @_;
                    495:     if ($lonid) {
1.1295    raeburn   496:         my $hostname = &hostname($lonid);
1.891     albertel  497: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    498: 	if ($hostname && -e $peerfile) {
                    499: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    500: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    501: 					     Type    => SOCK_STREAM,
                    502: 					     Timeout => 10);
                    503: 	    if ($client) {
                    504: 		print $client ("reset_retries\n");
                    505: 		my $answer=<$client>;
                    506: 		#reset just this one.
                    507: 	    }
                    508: 	}
                    509: 	return;
                    510:     }
                    511: 
1.836     www       512:     &logthis("Trying to reconnect lonc");
1.1       albertel  513:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1359    raeburn   514:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  515: 	my $loncpid=<$fh>;
                    516:         chomp($loncpid);
                    517:         if (kill 0 => $loncpid) {
                    518: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    519:             kill USR1 => $loncpid;
                    520:             sleep 1;
1.1295    raeburn   521:         } else {
1.12      www       522: 	    &logthis(
1.672     albertel  523:                "<font color=\"blue\">WARNING:".
1.12      www       524:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  525:         }
                    526:     } else {
1.836     www       527: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  528:     }
                    529: }
                    530: 
                    531: # ------------------------------------------------------ Critical communication
1.12      www       532: 
1.1       albertel  533: sub critical {
                    534:     my ($cmd,$server)=@_;
1.838     albertel  535:     unless (&hostname($server)) {
1.672     albertel  536:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       537:                " Critical message to unknown server ($server)</font>");
                    538:         return 'no_such_host';
                    539:     }
1.1       albertel  540:     my $answer=reply($cmd,$server);
                    541:     if ($answer eq 'con_lost') {
1.1295    raeburn   542: 	&reconlonc($server);
1.589     albertel  543: 	my $answer=reply($cmd,$server);
1.1       albertel  544:         if ($answer eq 'con_lost') {
                    545:             my $now=time;
                    546:             my $middlename=$cmd;
1.5       www       547:             $middlename=substr($middlename,0,16);
1.1       albertel  548:             $middlename=~s/\W//g;
                    549:             my $dfilename=
1.305     www       550:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    551:             $dumpcount++;
1.1       albertel  552:             {
1.448     albertel  553: 		my $dfh;
1.1359    raeburn   554: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  555: 		    print $dfh "$cmd\n"; 
                    556: 		    close($dfh);
                    557: 		}
1.1       albertel  558:             }
1.1288    damieng   559:             sleep 1;
1.1       albertel  560:             my $wcmd='';
                    561:             {
1.448     albertel  562: 		my $dfh;
1.1359    raeburn   563: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  564: 		    $wcmd=<$dfh>; 
                    565: 		    close($dfh);
                    566: 		}
1.1       albertel  567:             }
                    568:             chomp($wcmd);
1.7       www       569:             if ($wcmd eq $cmd) {
1.672     albertel  570: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       571:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  572:                 &logperm("D:$server:$cmd");
                    573: 	        return 'con_delayed';
                    574:             } else {
1.672     albertel  575:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       576:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  577:                 &logperm("F:$server:$cmd");
                    578:                 return 'con_failed';
                    579:             }
                    580:         }
                    581:     }
                    582:     return $answer;
1.405     albertel  583: }
                    584: 
1.755     albertel  585: # ------------------------------------------- check if return value is an error
                    586: 
                    587: sub error {
                    588:     my ($result) = @_;
1.756     albertel  589:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  590: 	if ($2 == 2) { return undef; }
                    591: 	return $1;
                    592:     }
                    593:     return undef;
                    594: }
                    595: 
1.783     albertel  596: sub convert_and_load_session_env {
                    597:     my ($lonidsdir,$handle)=@_;
                    598:     my @profile;
                    599:     {
1.917     albertel  600: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    601: 	if (!$opened) {
1.915     albertel  602: 	    return 0;
                    603: 	}
1.783     albertel  604: 	flock($idf,LOCK_SH);
                    605: 	@profile=<$idf>;
                    606: 	close($idf);
                    607:     }
                    608:     my %temp_env;
                    609:     foreach my $line (@profile) {
1.786     albertel  610: 	if ($line !~ m/=/) {
                    611: 	    return 0;
                    612: 	}
1.783     albertel  613: 	chomp($line);
                    614: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    615: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    616:     }
                    617:     unlink("$lonidsdir/$handle.id");
                    618:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    619: 	    0640)) {
                    620: 	%disk_env = %temp_env;
                    621: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    622: 	untie(%disk_env);
                    623:     }
1.786     albertel  624:     return 1;
1.783     albertel  625: }
                    626: 
1.374     www       627: # ------------------------------------------- Transfer profile into environment
1.780     albertel  628: my $env_loaded;
                    629: sub transfer_profile_to_env {
1.788     albertel  630:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    631:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       632: 
1.720     albertel  633:     if (!defined($lonidsdir)) {
                    634: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    635:     }
                    636:     if (!defined($handle)) {
                    637:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    638:     }
                    639: 
1.786     albertel  640:     my $convert;
                    641:     {
1.917     albertel  642:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    643: 	if (!$opened) {
1.915     albertel  644: 	    return;
                    645: 	}
1.786     albertel  646: 	flock($idf,LOCK_SH);
                    647: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    648: 		&GDBM_READER(),0640)) {
                    649: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    650: 	    untie(%disk_env);
                    651: 	} else {
                    652: 	    $convert = 1;
                    653: 	}
                    654:     }
                    655:     if ($convert) {
                    656: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    657: 	    &logthis("Failed to load session, or convert session.");
                    658: 	}
1.374     www       659:     }
1.783     albertel  660: 
1.786     albertel  661:     my %remove;
1.783     albertel  662:     while ( my $envname = each(%env) ) {
1.433     matthew   663:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    664:             if ($time < time-300) {
1.783     albertel  665:                 $remove{$key}++;
1.433     matthew   666:             }
                    667:         }
                    668:     }
1.783     albertel  669: 
1.619     albertel  670:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  671:     $env_loaded=1;
1.783     albertel  672:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   673:         &delenv($expired_key);
1.374     www       674:     }
1.1       albertel  675: }
                    676: 
1.916     albertel  677: # ---------------------------------------------------- Check for valid session 
                    678: sub check_for_valid_session {
1.1355    raeburn   679:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  680:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1378    raeburn   681:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
                    682:     if ($name eq 'lonDAV') {
                    683:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    684:     } else {
                    685:         $lonidsdir=$r->dir_config('lonIDsDir');
                    686:         if ($name eq '') {
                    687:             $name = 'lonID';
                    688:         }
                    689:     }
                    690:     if ($name eq 'lonID') {
                    691:         $secure = 'lonSID';
1.1337    raeburn   692:         $linkname = 'lonLinkID';
                    693:         $pubname = 'lonPubID';
1.1378    raeburn   694:         if (exists($cookies{$secure})) {
                    695:             $lonid=$cookies{$secure};
                    696:         } elsif (exists($cookies{$name})) {
                    697:             $lonid=$cookies{$name};
1.1400    raeburn   698:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
1.1337    raeburn   699:             $lonid=$cookies{$linkname};
1.1378    raeburn   700:         } elsif (exists($cookies{$pubname})) {
                    701:             $lonid=$cookies{$pubname};
1.1337    raeburn   702:         }
1.1378    raeburn   703:     } else {
                    704:         $lonid=$cookies{$name};
1.1337    raeburn   705:     }
1.916     albertel  706:     return undef if (!$lonid);
                    707: 
                    708:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1378    raeburn   709:     if (-l "$lonidsdir/$handle.id") {
                    710:         my $link = readlink("$lonidsdir/$handle.id");
                    711:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    712:             $handle = $1;
                    713:         }
1.1155    raeburn   714:     }
1.1355    raeburn   715:     if (!-e "$lonidsdir/$handle.id") {
                    716:         if ((ref($domref)) && ($name eq 'lonID') && 
                    717:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    718:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    719:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    720:                 $$domref = $possudom;
                    721:             }
                    722:         }
                    723:         return undef;
                    724:     }
1.916     albertel  725: 
1.917     albertel  726:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    727:     return undef if (!$opened);
1.916     albertel  728: 
                    729:     flock($idf,LOCK_SH);
                    730:     my %disk_env;
                    731:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    732: 	    &GDBM_READER(),0640)) {
                    733: 	return undef;	
                    734:     }
                    735: 
                    736:     if (!defined($disk_env{'user.name'})
                    737: 	|| !defined($disk_env{'user.domain'})) {
1.1394    raeburn   738:         untie(%disk_env);
1.916     albertel  739: 	return undef;
                    740:     }
1.1245    raeburn   741: 
                    742:     if (ref($userhashref) eq 'HASH') {
                    743:         $userhashref->{'name'} = $disk_env{'user.name'};
                    744:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1448    raeburn   745:         if ($disk_env{'request.role'}) {
                    746:             $userhashref->{'role'} = $disk_env{'request.role'};
                    747:         }
1.1361    raeburn   748:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
1.1375    raeburn   749:         if ($userhashref->{'lti'}) {
                    750:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
                    751:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
                    752:         }
1.1212    raeburn   753:     }
1.1394    raeburn   754:     untie(%disk_env);
1.1245    raeburn   755: 
1.916     albertel  756:     return $handle;
                    757: }
                    758: 
1.830     albertel  759: sub timed_flock {
                    760:     my ($file,$lock_type) = @_;
                    761:     my $failed=0;
                    762:     eval {
                    763: 	local $SIG{__DIE__}='DEFAULT';
                    764: 	local $SIG{ALRM}=sub {
                    765: 	    $failed=1;
                    766: 	    die("failed lock");
                    767: 	};
                    768: 	alarm(13);
                    769: 	flock($file,$lock_type);
                    770: 	alarm(0);
                    771:     };
                    772:     if ($failed) {
                    773: 	return undef;
                    774:     } else {
                    775: 	return 1;
                    776:     }
                    777: }
                    778: 
1.1392    raeburn   779: sub get_sessionfile_vars {
                    780:     my ($handle,$lonidsdir,$storearr) = @_;
                    781:     my %returnhash;
                    782:     unless (ref($storearr) eq 'ARRAY') {
                    783:         return %returnhash;
                    784:     }
                    785:     if (-l "$lonidsdir/$handle.id") {
                    786:         my $link = readlink("$lonidsdir/$handle.id");
                    787:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
                    788:             $handle = $1;
                    789:         }
                    790:     }
                    791:     if ((-e "$lonidsdir/$handle.id") &&
                    792:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    793:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    794:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    795:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
                    796:                 flock($idf,LOCK_SH);
                    797:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    798:                         &GDBM_READER(),0640)) {
                    799:                     foreach my $item (@{$storearr}) {
                    800:                         $returnhash{$item} = $disk_env{$item};
                    801:                     }
                    802:                     untie(%disk_env);
                    803:                 }
                    804:             }
                    805:         }
                    806:     }
                    807:     return %returnhash;
                    808: }
                    809: 
1.5       www       810: # ---------------------------------------------------------- Append Environment
                    811: 
                    812: sub appenv {
1.949     raeburn   813:     my ($newenv,$roles) = @_;
                    814:     if (ref($newenv) eq 'HASH') {
                    815:         foreach my $key (keys(%{$newenv})) {
                    816:             my $refused = 0;
                    817: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    818:                 $refused = 1;
                    819:                 if (ref($roles) eq 'ARRAY') {
1.1250    raeburn   820:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   821:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    822:                         $refused = 0;
                    823:                     }
                    824:                 }
                    825:             }
                    826:             if ($refused) {
                    827:                 &logthis("<font color=\"blue\">WARNING: ".
                    828:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    829:                          .'</font>');
                    830: 	        delete($newenv->{$key});
                    831:             } else {
                    832:                 $env{$key}=$newenv->{$key};
                    833:             }
                    834:         }
1.1376    raeburn   835:         my $lonids = $perlvar{'lonIDsDir'};
                    836:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
                    837:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    838:             if ($opened
                    839: 	        && &timed_flock($env_file,LOCK_EX)
                    840: 	        &&
                    841: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    842: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    843: 	        while (my ($key,$value) = each(%{$newenv})) {
                    844: 	            $disk_env{$key} = $value;
                    845: 	        }
                    846: 	        untie(%disk_env);
                    847:             }
1.35      www       848:         }
1.191     harris41  849:     }
1.56      www       850:     return 'ok';
                    851: }
                    852: # ----------------------------------------------------- Delete from Environment
                    853: 
                    854: sub delenv {
1.1104    raeburn   855:     my ($delthis,$regexp,$roles) = @_;
                    856:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    857:         my $refused = 1;
                    858:         if (ref($roles) eq 'ARRAY') {
                    859:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    860:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    861:                 $refused = 0;
                    862:             }
                    863:         }
                    864:         if ($refused) {
                    865:             &logthis("<font color=\"blue\">WARNING: ".
                    866:                      "Attempt to delete from environment ".$delthis);
                    867:             return 'error';
                    868:         }
1.56      www       869:     }
1.917     albertel  870:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    871:     if ($opened
1.915     albertel  872: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  873: 	&&
                    874: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    875: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  876: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   877: 	    if ($regexp) {
                    878:                 if ($key=~/^$delthis/) {
                    879:                     delete($env{$key});
                    880:                     delete($disk_env{$key});
                    881:                 } 
                    882:             } else {
                    883:                 if ($key=~/^\Q$delthis\E/) {
                    884: 		    delete($env{$key});
                    885: 		    delete($disk_env{$key});
                    886: 	        }
                    887:             }
1.448     albertel  888: 	}
1.783     albertel  889: 	untie(%disk_env);
1.5       www       890:     }
                    891:     return 'ok';
1.369     albertel  892: }
                    893: 
1.790     albertel  894: sub get_env_multiple {
                    895:     my ($name) = @_;
                    896:     my @values;
                    897:     if (defined($env{$name})) {
                    898:         # exists is it an array
                    899:         if (ref($env{$name})) {
                    900:             @values=@{ $env{$name} };
                    901:         } else {
                    902:             $values[0]=$env{$name};
                    903:         }
                    904:     }
                    905:     return(@values);
                    906: }
                    907: 
1.958     www       908: # ------------------------------------------------------------------- Locking
                    909: 
                    910: sub set_lock {
                    911:     my ($text)=@_;
                    912:     $locknum++;
                    913:     my $id=$$.'-'.$locknum;
                    914:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    915:              'session.lock.'.$id => $text});
                    916:     return $id;
                    917: }
                    918: 
                    919: sub get_locks {
                    920:     my $num=0;
                    921:     my %texts=();
                    922:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    923:        if ($lock=~/\w/) {
                    924:           $num++;
                    925:           $texts{$lock}=$env{'session.lock.'.$lock};
                    926:        }
                    927:    }
                    928:    return ($num,%texts);
                    929: }
                    930: 
                    931: sub remove_lock {
                    932:     my ($id)=@_;
                    933:     my $newlocks='';
                    934:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    935:        if (($lock=~/\w/) && ($lock ne $id)) {
                    936:           $newlocks.=','.$lock;
                    937:        }
                    938:     }
                    939:     &appenv({'session.locks' => $newlocks});
                    940:     &delenv('session.lock.'.$id);
                    941: }
                    942: 
                    943: sub remove_all_locks {
                    944:     my $activelocks=$env{'session.locks'};
                    945:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    946:        if ($lock=~/\w/) {
                    947:           &remove_lock($lock);
                    948:        }
                    949:     }
                    950: }
                    951: 
                    952: 
1.369     albertel  953: # ------------------------------------------ Find out current server userload
                    954: sub userload {
                    955:     my $numusers=0;
                    956:     {
                    957: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    958: 	my $filename;
                    959: 	my $curtime=time;
                    960: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  961: 	    next if ($filename eq '.' || $filename eq '..');
                    962: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.1390    raeburn   963:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
1.404     albertel  964: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  965: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  966: 	}
                    967: 	closedir(LONIDS);
                    968:     }
                    969:     my $userloadpercent=0;
                    970:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    971:     if ($maxuserload) {
1.371     albertel  972: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  973:     }
1.372     albertel  974:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  975:     return $userloadpercent;
1.283     www       976: }
                    977: 
1.1       albertel  978: # ------------------------------ Find server with least workload from spare.tab
1.11      www       979: 
1.1       albertel  980: sub spareserver {
1.1451    raeburn   981:     my ($r,$loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  982:     my $spare_server;
1.370     albertel  983:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  984:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    985:                                                      :  $userloadpercent;
1.1083    raeburn   986:     my ($uint_dom,$remotesessions);
                    987:     if (($udom ne '') && (&domain($udom) ne '')) {
                    988:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    989:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    990:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    991:         $remotesessions = $udomdefaults{'remotesessions'};
                    992:     }
1.1123    raeburn   993:     my $spareshash = &this_host_spares($udom);
                    994:     if (ref($spareshash) eq 'HASH') {
                    995:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    996:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279    raeburn   997:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    998:                                              $try_server));
1.1123    raeburn   999: 	        ($spare_server, $lowest_load) =
                   1000: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                   1001:             }
1.1083    raeburn  1002:         }
1.784     albertel 1003: 
1.1123    raeburn  1004:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                   1005: 
                   1006:         if (!$found_server) {
                   1007:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                   1008: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn  1009:                     next unless (&spare_can_host($udom,$uint_dom,
                   1010:                                                  $remotesessions,$try_server));
1.1123    raeburn  1011: 	            ($spare_server, $lowest_load) =
                   1012: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                   1013:                 }
                   1014: 	    }
                   1015:         }
1.784     albertel 1016:     }
                   1017: 
                   1018:     if (!$want_server_name) {
1.1001    raeburn  1019:         if (defined($spare_server)) {
                   1020:             my $hostname = &hostname($spare_server);
1.1083    raeburn  1021:             if (defined($hostname)) {
1.1397    raeburn  1022:                 my $protocol = 'http';
                   1023:                 if ($protocol{$spare_server} eq 'https') {
                   1024:                     $protocol = $protocol{$spare_server};
                   1025:                 }
1.1451    raeburn  1026:                 my $alias = &Apache::lonnet::use_proxy_alias($r,$spare_server);
                   1027:                 $hostname = $alias if ($alias ne '');
1.1001    raeburn  1028: 	        $spare_server = $protocol.'://'.$hostname;
                   1029:             }
                   1030:         }
1.784     albertel 1031:     }
                   1032:     return $spare_server;
                   1033: }
                   1034: 
                   1035: sub compare_server_load {
1.1253    raeburn  1036:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                   1037: 
                   1038:     if ($required) {
                   1039:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   1040:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1041:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   1042:         if (($major eq '' && $minor eq '') ||
                   1043:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   1044:             return ($spare_server,$lowest_load);
                   1045:         }
                   1046:     }
1.784     albertel 1047: 
                   1048:     my $loadans     = &reply('load',    $try_server);
                   1049:     my $userloadans = &reply('userload',$try_server);
                   1050: 
                   1051:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn  1052: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel 1053:     }
                   1054: 
                   1055:     my $load;
                   1056:     if ($loadans =~ /\d/) {
                   1057: 	if ($userloadans =~ /\d/) {
                   1058: 	    #both are numbers, pick the bigger one
                   1059: 	    $load = ($loadans > $userloadans) ? $loadans 
                   1060: 		                              : $userloadans;
1.411     albertel 1061: 	} else {
1.784     albertel 1062: 	    $load = $loadans;
1.411     albertel 1063: 	}
1.784     albertel 1064:     } else {
                   1065: 	$load = $userloadans;
                   1066:     }
                   1067: 
                   1068:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                   1069: 	$spare_server = $try_server;
                   1070: 	$lowest_load  = $load;
1.370     albertel 1071:     }
1.784     albertel 1072:     return ($spare_server,$lowest_load);
1.202     matthew  1073: }
1.914     albertel 1074: 
                   1075: # --------------------------- ask offload servers if user already has a session
                   1076: sub find_existing_session {
                   1077:     my ($udom,$uname) = @_;
1.1123    raeburn  1078:     my $spareshash = &this_host_spares($udom);
                   1079:     if (ref($spareshash) eq 'HASH') {
                   1080:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1081:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1082:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1083:             }
                   1084:         }
                   1085:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1086:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1087:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1088:             }
                   1089:         }
1.914     albertel 1090:     }
                   1091:     return;
                   1092: }
                   1093: 
1.1411    raeburn  1094: sub delusersession {
                   1095:     my ($lonid,$udom,$uname) = @_;
                   1096:     my $uprimary_id = &domain($udom,'primary');
                   1097:     my $uintdom = &internet_dom($uprimary_id);
                   1098:     my $intdom = &internet_dom($lonid);
                   1099:     my $serverhomedom = &host_domain($lonid);
                   1100:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1101:         return &reply(join(':','delusersession',
                   1102:                             map {&escape($_)} ($udom,$uname)),$lonid);
                   1103:     }
                   1104:     return;
                   1105: }
                   1106: 
1.1389    raeburn  1107: # check if user's browser sent load balancer cookie and server still has session
                   1108: # and is not overloaded.
                   1109: sub check_for_balancer_cookie {
                   1110:     my ($r,$update_mtime) = @_;
                   1111:     my ($otherserver,$cookie);
                   1112:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                   1113:     if (exists($cookies{'balanceID'})) {
                   1114:         my $balid = $cookies{'balanceID'};
                   1115:         $cookie=&LONCAPA::clean_handle($balid->value);
                   1116:         my $balancedir=$r->dir_config('lonBalanceDir');
                   1117:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
                   1118:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
                   1119:                 my ($possudom,$possuname) = ($1,$2);
                   1120:                 my $has_session = 0;
                   1121:                 if ((&domain($possudom) ne '') &&
                   1122:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
                   1123:                     my $try_server;
                   1124:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
                   1125:                     if ($opened) {
                   1126:                         flock($idf,LOCK_SH);
                   1127:                         while (my $line = <$idf>) {
                   1128:                             chomp($line);
                   1129:                             if (&hostname($line) ne '') {
                   1130:                                 $try_server = $line;
                   1131:                                 last;
                   1132:                             }
                   1133:                         }
                   1134:                         close($idf);
                   1135:                         if (($try_server) &&
                   1136:                             (&has_user_session($try_server,$possudom,$possuname))) {
                   1137:                             my $lowest_load = 30000;
                   1138:                             ($otherserver,$lowest_load) =
                   1139:                                 &compare_server_load($try_server,undef,$lowest_load);
                   1140:                             if ($otherserver ne '' && $lowest_load < 100) {
                   1141:                                 $has_session = 1;
                   1142:                             } else {
                   1143:                                 undef($otherserver);
                   1144:                             }
                   1145:                         }
                   1146:                     }
                   1147:                 }
                   1148:                 if ($has_session) {
                   1149:                     if ($update_mtime) {
                   1150:                         my $atime = my $mtime = time;
                   1151:                         utime($atime,$mtime,"$balancedir/$cookie.id");
                   1152:                     }
                   1153:                 } else {
                   1154:                     unlink("$balancedir/$cookie.id");
                   1155:                 }
                   1156:             }
                   1157:         }
                   1158:     }
                   1159:     return ($otherserver,$cookie);
                   1160: }
                   1161: 
1.1431    raeburn  1162: sub updatebalcookie {
                   1163:     my ($cookie,$balancer,$lastentry)=@_;
                   1164:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1165:         my ($udom,$uname) = ($1,$2);
                   1166:         my $uprimary_id = &domain($udom,'primary');
                   1167:         my $uintdom = &internet_dom($uprimary_id);
                   1168:         my $intdom = &internet_dom($balancer);
                   1169:         my $serverhomedom = &host_domain($balancer);
                   1170:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1171:             return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
                   1172:         }
                   1173:     }
                   1174:     return;
                   1175: }
                   1176: 
1.1389    raeburn  1177: sub delbalcookie {
                   1178:     my ($cookie,$balancer) =@_;
                   1179:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
                   1180:         my ($udom,$uname) = ($1,$2);
                   1181:         my $uprimary_id = &domain($udom,'primary');
                   1182:         my $uintdom = &internet_dom($uprimary_id);
                   1183:         my $intdom = &internet_dom($balancer);
                   1184:         my $serverhomedom = &host_domain($balancer);
                   1185:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
1.1431    raeburn  1186:             return &reply('delbalcookie:'.&escape($cookie),$balancer);
1.1389    raeburn  1187:         }
                   1188:     }
                   1189: }
                   1190: 
1.914     albertel 1191: # -------------------------------- ask if server already has a session for user
                   1192: sub has_user_session {
                   1193:     my ($lonid,$udom,$uname) = @_;
                   1194:     my $result = &reply(join(':','userhassession',
                   1195: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1196:     return 1 if ($result eq 'ok');
                   1197: 
                   1198:     return 0;
                   1199: }
                   1200: 
1.1076    raeburn  1201: # --------- determine least loaded server in a user's domain which allows login
                   1202: 
                   1203: sub choose_server {
1.1259    raeburn  1204:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1205:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1206:     my %servers = &get_servers($udom);
1.1076    raeburn  1207:     my $lowest_load = 30000;
1.1259    raeburn  1208:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1209:     if ($skiploadbal) {
                   1210:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1211:         unless (defined($cached)) {
                   1212:             my $cachetime = 60*60*24;
                   1213:             my %domconfig =
                   1214:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1215:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1216:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1217:                                            $cachetime);
                   1218:             }
                   1219:         }
                   1220:     }
1.1076    raeburn  1221:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn  1222:         if ($skiploadbal) {
                   1223:             if (ref($balancers) eq 'HASH') {
                   1224:                 next if (exists($balancers->{$lonhost}));
                   1225:             }
1.1389    raeburn  1226:         }
1.1115    raeburn  1227:         my $loginvia;
                   1228:         if ($checkloginvia) {
                   1229:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1230:             if ($loginvia) {
                   1231:                 my ($server,$path) = split(/:/,$loginvia);
                   1232:                 ($login_host, $lowest_load) =
1.1253    raeburn  1233:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1234:                 if ($login_host eq $server) {
                   1235:                     $portal_path = $path;
1.1151    raeburn  1236:                     $isredirect = 1;
1.1116    raeburn  1237:                 }
                   1238:             } else {
                   1239:                 ($login_host, $lowest_load) =
1.1253    raeburn  1240:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1241:                 if ($login_host eq $lonhost) {
                   1242:                     $portal_path = '';
1.1151    raeburn  1243:                     $isredirect = ''; 
1.1116    raeburn  1244:                 }
                   1245:             }
                   1246:         } else {
1.1076    raeburn  1247:             ($login_host, $lowest_load) =
1.1253    raeburn  1248:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1249:         }
                   1250:     }
                   1251:     if ($login_host ne '') {
1.1116    raeburn  1252:         $hostname = &hostname($login_host);
1.1076    raeburn  1253:     }
1.1331    raeburn  1254:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1255: }
                   1256: 
1.1420    raeburn  1257: sub get_course_sessions {
                   1258:     my ($cnum,$cdom,$lastactivity) = @_;
                   1259:     my %servers = &internet_dom_servers($cdom);
                   1260:     my %returnhash;
                   1261:     foreach my $server (sort(keys(%servers))) {
                   1262:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
                   1263:         my @pairs=split(/\&/,$rep);
                   1264:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
                   1265:             foreach my $item (@pairs) {
                   1266:                 my ($key,$value)=split(/=/,$item,2);
                   1267:                 $key = &unescape($key);
                   1268:                 next if ($key =~ /^error: 2 /);
                   1269:                 if (exists($returnhash{$key})) {
                   1270:                     next if ($value < $returnhash{$key});
                   1271:                 }
                   1272:                 $returnhash{$key}=$value;
                   1273:             }
                   1274:         }
                   1275:     }
                   1276:     return %returnhash;
                   1277: }
                   1278: 
1.202     matthew  1279: # --------------------------------------------- Try to change a user's password
                   1280: 
                   1281: sub changepass {
1.799     raeburn  1282:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1283:     $currentpass = &escape($currentpass);
                   1284:     $newpass     = &escape($newpass);
1.1030    raeburn  1285:     my $lonhost = $perlvar{'lonHostID'};
                   1286:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1287: 		       $server);
                   1288:     if (! $answer) {
                   1289: 	&logthis("No reply on password change request to $server ".
                   1290: 		 "by $uname in domain $udom.");
                   1291:     } elsif ($answer =~ "^ok") {
                   1292:         &logthis("$uname in $udom successfully changed their password ".
                   1293: 		 "on $server.");
                   1294:     } elsif ($answer =~ "^pwchange_failure") {
                   1295: 	&logthis("$uname in $udom was unable to change their password ".
                   1296: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1297: 		 "or pwchange");
                   1298:     } elsif ($answer =~ "^non_authorized") {
                   1299:         &logthis("$uname in $udom did not get their password correct when ".
                   1300: 		 "attempting to change it on $server.");
                   1301:     } elsif ($answer =~ "^auth_mode_error") {
                   1302:         &logthis("$uname in $udom attempted to change their password despite ".
                   1303: 		 "not being locally or internally authenticated on $server.");
                   1304:     } elsif ($answer =~ "^unknown_user") {
                   1305:         &logthis("$uname in $udom attempted to change their password ".
                   1306: 		 "on $server but were unable to because $server is not ".
                   1307: 		 "their home server.");
                   1308:     } elsif ($answer =~ "^refused") {
                   1309: 	&logthis("$server refused to change $uname in $udom password because ".
                   1310: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1311:     } elsif ($answer =~ "invalid_client") {
                   1312:         &logthis("$server refused to change $uname in $udom password because ".
                   1313:                  "it was a reset by e-mail originating from an invalid server.");
1.1408    raeburn  1314:     } elsif ($answer =~ "^prioruse") {
                   1315:        &logthis("$server refused to change $uname in $udom password because ".
                   1316:                 "the password had been used before");
1.202     matthew  1317:     }
                   1318:     return $answer;
1.1       albertel 1319: }
                   1320: 
1.169     harris41 1321: # ----------------------- Try to determine user's current authentication scheme
                   1322: 
                   1323: sub queryauthenticate {
                   1324:     my ($uname,$udom)=@_;
1.456     albertel 1325:     my $uhome=&homeserver($uname,$udom);
                   1326:     if (!$uhome) {
                   1327: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1328: 	return 'no_host';
                   1329:     }
                   1330:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1331:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1332: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1333:     }
1.456     albertel 1334:     return $answer;
1.169     harris41 1335: }
                   1336: 
1.1       albertel 1337: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1338: 
1.1       albertel 1339: sub authenticate {
1.1073    raeburn  1340:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1341:     $upass=&escape($upass);
                   1342:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1343:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1344:     my $newhome;
1.836     www      1345:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1346: # Maybe the machine was offline and only re-appeared again recently?
                   1347:         &reconlonc();
                   1348: # One more
1.952     raeburn  1349: 	$uhome=&homeserver($uname,$udom,1);
                   1350:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1351:             if (defined(&domain($udom,'primary'))) {
                   1352:                 $newhome=&domain($udom,'primary');
                   1353:             }
                   1354:             if ($newhome ne '') {
                   1355:                 $uhome = $newhome;
                   1356:             }
                   1357:         }
1.836     www      1358: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1359: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1360: 	    return 'no_host';
                   1361:         }
1.1       albertel 1362:     }
1.1073    raeburn  1363:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1364:     if ($answer eq 'authorized') {
1.952     raeburn  1365:         if ($newhome) {
                   1366:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1367:             return 'no_account_on_host'; 
                   1368:         } else {
                   1369:             &logthis("User $uname at $udom authorized by $uhome");
                   1370:             return $uhome;
                   1371:         }
1.471     albertel 1372:     }
                   1373:     if ($answer eq 'non_authorized') {
                   1374: 	&logthis("User $uname at $udom rejected by $uhome");
                   1375: 	return 'no_host'; 
1.9       www      1376:     }
1.471     albertel 1377:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1378:     return 'no_host';
                   1379: }
                   1380: 
1.1073    raeburn  1381: sub can_host_session {
1.1074    raeburn  1382:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1383:     my $canhost = 1;
1.1074    raeburn  1384:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1385:     if (ref($remotesessions) eq 'HASH') {
                   1386:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1387:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1388:                 $canhost = 0;
                   1389:             } else {
                   1390:                 $canhost = 1;
                   1391:             }
                   1392:         }
                   1393:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1394:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1395:                 $canhost = 1;
                   1396:             } else {
                   1397:                 $canhost = 0;
                   1398:             }
                   1399:         }
                   1400:         if ($canhost) {
                   1401:             if ($remotesessions->{'version'} ne '') {
                   1402:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1403:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1404:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1405:                         my $major = $1;
                   1406:                         my $minor = $2;
                   1407:                         if (($major < $reqmajor ) ||
                   1408:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1409:                             $canhost = 0;
                   1410:                         }
                   1411:                     } else {
                   1412:                         $canhost = 0;
                   1413:                     }
                   1414:                 }
                   1415:             }
                   1416:         }
                   1417:     }
                   1418:     if ($canhost) {
                   1419:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1420:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1421:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1422:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1423:                 if (($uint_dom ne '') && 
                   1424:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1425:                     $canhost = 0;
                   1426:                 } else {
                   1427:                     $canhost = 1;
                   1428:                 }
                   1429:             }
                   1430:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1431:                 if (($uint_dom ne '') && 
                   1432:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1433:                     $canhost = 1;
                   1434:                 } else {
                   1435:                     $canhost = 0;
                   1436:                 }
                   1437:             }
                   1438:         }
                   1439:     }
                   1440:     return $canhost;
                   1441: }
                   1442: 
1.1083    raeburn  1443: sub spare_can_host {
                   1444:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1445:     my $canhost=1;
1.1279    raeburn  1446:     my $try_server_hostname = &hostname($try_server);
                   1447:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1448:     my $serverhomedom = &host_domain($serverhomeID);
                   1449:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1450:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1451:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1452:             $canhost = 0;
                   1453:         }
                   1454:     }
1.1439    raeburn  1455:     if ($canhost) {
                   1456:         if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
                   1457:             if ($defdomdefaults{'offloadoth'}{$try_server}) {
                   1458:                 unless (&shared_institution($udom,$try_server)) {
                   1459:                     $canhost = 0;
                   1460:                 }
                   1461:             }
                   1462:         }
                   1463:     }
1.1279    raeburn  1464:     if (($canhost) && ($uint_dom)) {
                   1465:         my @intdoms;
                   1466:         my $internet_names = &get_internet_names($try_server);
                   1467:         if (ref($internet_names) eq 'ARRAY') {
                   1468:             @intdoms = @{$internet_names};
                   1469:         }
                   1470:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1471:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1472:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1473:                                          $remotesessions,
                   1474:                                          $defdomdefaults{'hostedsessions'});
                   1475:         }
1.1083    raeburn  1476:     }
                   1477:     return $canhost;
                   1478: }
                   1479: 
1.1123    raeburn  1480: sub this_host_spares {
                   1481:     my ($dom) = @_;
1.1126    raeburn  1482:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1483:     my @hosts = &current_machine_ids();
                   1484:     foreach my $lonhost (@hosts) {
                   1485:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1486:             $dom_in_use = $dom;
                   1487:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1488:             last;
                   1489:         }
                   1490:     }
1.1126    raeburn  1491:     if ($dom_in_use ne '') {
                   1492:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1493:     }
                   1494:     if (ref($result) ne 'HASH') {
                   1495:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1496:         $dom_in_use = &host_domain($lonhost_in_use);
                   1497:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1498:         if (ref($result) ne 'HASH') {
                   1499:             $result = \%spareid;
                   1500:         }
                   1501:     }
                   1502:     return $result;
                   1503: }
                   1504: 
                   1505: sub spares_for_offload  {
                   1506:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1507:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1508:     if (defined($cached)) {
                   1509:         return $result;
                   1510:     } else {
1.1126    raeburn  1511:         my $cachetime = 60*60*24;
                   1512:         my %domconfig =
                   1513:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1514:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1515:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1516:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1517:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1518:                 }
                   1519:             }
                   1520:         }
                   1521:     }
1.1126    raeburn  1522:     return;
1.1123    raeburn  1523: }
                   1524: 
1.1129    raeburn  1525: sub get_lonbalancer_config {
                   1526:     my ($servers) = @_;
                   1527:     my ($currbalancer,$currtargets);
                   1528:     if (ref($servers) eq 'HASH') {
                   1529:         foreach my $server (keys(%{$servers})) {
                   1530:             my %what = (
                   1531:                          spareid => 1,
                   1532:                          perlvar => 1,
                   1533:                        );
                   1534:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1535:             if ($result eq 'ok') {
                   1536:                 if (ref($returnhash) eq 'HASH') {
                   1537:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1538:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1539:                             $currbalancer = $server;
                   1540:                             $currtargets = {};
                   1541:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1542:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1543:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1544:                                 }
                   1545:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1546:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1547:                                 }
                   1548:                             }
                   1549:                             last;
                   1550:                         }
                   1551:                     }
                   1552:                 }
                   1553:             }
                   1554:         }
                   1555:     }
                   1556:     return ($currbalancer,$currtargets);
                   1557: }
                   1558: 
                   1559: sub check_loadbalancing {
1.1331    raeburn  1560:     my ($uname,$udom,$caller) = @_;
1.1191    raeburn  1561:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1.1391    raeburn  1562:         $rule_in_effect,$offloadto,$otherserver,$setcookie,$dom_balancers);
1.1129    raeburn  1563:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1564:     my @hosts = &current_machine_ids();
1.1129    raeburn  1565:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1566:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1567:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1568:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1569:     my $domneedscache;
1.1129    raeburn  1570:     my $cachetime = 60*60*24;
                   1571: 
                   1572:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1573:         $dom_in_use = $udom;
                   1574:         $homeintdom = 1;
                   1575:     } else {
                   1576:         $dom_in_use = $serverhomedom;
                   1577:     }
                   1578:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1579:     unless (defined($cached)) {
                   1580:         my %domconfig =
                   1581:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1582:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1583:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1584:         } else {
                   1585:             $domneedscache = $dom_in_use;
1.1129    raeburn  1586:         }
                   1587:     }
                   1588:     if (ref($result) eq 'HASH') {
1.1391    raeburn  1589:         ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1590:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1591:         if ($is_balancer) {
                   1592:             if (ref($currrules) eq 'HASH') {
                   1593:                 if ($homeintdom) {
                   1594:                     if ($uname ne '') {
                   1595:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1596:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1597:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1598:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1599:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1600:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1601:                             }
                   1602:                         }
                   1603:                         if ($rule_in_effect eq '') {
                   1604:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1605:                             if ($userenv{'inststatus'} ne '') {
                   1606:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1607:                                 my ($othertitle,$usertypes,$types) =
                   1608:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1609:                                 if (ref($types) eq 'ARRAY') {
                   1610:                                     foreach my $type (@{$types}) {
                   1611:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1612:                                             if (exists($currrules->{$type})) {
                   1613:                                                 $rule_in_effect = $currrules->{$type};
                   1614:                                             }
                   1615:                                         }
                   1616:                                     }
                   1617:                                 }
                   1618:                             } else {
                   1619:                                 if (exists($currrules->{'default'})) {
                   1620:                                     $rule_in_effect = $currrules->{'default'};
                   1621:                                 }
                   1622:                             }
                   1623:                         }
                   1624:                     } else {
                   1625:                         if (exists($currrules->{'default'})) {
                   1626:                             $rule_in_effect = $currrules->{'default'};
                   1627:                         }
                   1628:                     }
                   1629:                 } else {
                   1630:                     if ($currrules->{'_LC_external'} ne '') {
                   1631:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1632:                     }
                   1633:                 }
                   1634:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1635:                                                        $uname,$udom);
                   1636:             }
                   1637:         }
                   1638:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1639:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1640:         unless (defined($cached)) {
                   1641:             my %domconfig =
                   1642:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1643:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1644:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1645:             } else {
                   1646:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1647:             }
                   1648:         }
                   1649:         if (ref($result) eq 'HASH') {
1.1391    raeburn  1650:             ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers) =
1.1191    raeburn  1651:                 &check_balancer_result($result,@hosts);
                   1652:             if ($is_balancer) {
1.1129    raeburn  1653:                 if (ref($currrules) eq 'HASH') {
                   1654:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1655:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1656:                     }
                   1657:                 }
                   1658:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1659:                                                        $uname,$udom);
                   1660:             }
                   1661:         } else {
                   1662:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1663:                 $is_balancer = 1;
                   1664:                 $offloadto = &this_host_spares($dom_in_use);
                   1665:             }
1.1307    raeburn  1666:             unless (defined($cached)) {
                   1667:                 $domneedscache = $serverhomedom;
                   1668:             }
1.1129    raeburn  1669:         }
                   1670:     } else {
                   1671:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1672:             $is_balancer = 1;
                   1673:             $offloadto = &this_host_spares($dom_in_use);
                   1674:         }
1.1307    raeburn  1675:         unless (defined($cached)) {
                   1676:             $domneedscache = $serverhomedom;
                   1677:         }
                   1678:     }
                   1679:     if ($domneedscache) {
                   1680:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1681:     }
1.1430    raeburn  1682:     if (($is_balancer) && ($caller ne 'switchserver')) {
1.1176    raeburn  1683:         my $lowest_load = 30000;
                   1684:         if (ref($offloadto) eq 'HASH') {
                   1685:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1686:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1687:                     ($otherserver,$lowest_load) =
                   1688:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1689:                 }
1.1129    raeburn  1690:             }
1.1176    raeburn  1691:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1692: 
1.1176    raeburn  1693:             if (!$found_server) {
                   1694:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1695:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1696:                         ($otherserver,$lowest_load) =
                   1697:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1698:                     }
                   1699:                 }
                   1700:             }
                   1701:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1702:             if (@{$offloadto} == 1) {
                   1703:                 $otherserver = $offloadto->[0];
                   1704:             } elsif (@{$offloadto} > 1) {
                   1705:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1706:                     ($otherserver,$lowest_load) =
                   1707:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1708:                 }
                   1709:             }
                   1710:         }
1.1331    raeburn  1711:         unless ($caller eq 'login') {
                   1712:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1713:                 $is_balancer = 0;
                   1714:                 if ($uname ne '' && $udom ne '') {
                   1715:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1389    raeburn  1716:                         &appenv({'user.loadbalexempt'     => $lonhost,
1.1331    raeburn  1717:                                  'user.loadbalcheck.time' => time});
                   1718:                     }
1.1176    raeburn  1719:                 }
1.1129    raeburn  1720:             }
                   1721:         }
1.1430    raeburn  1722:     }
                   1723:     if (($is_balancer) && (!$homeintdom)) {
                   1724:         undef($setcookie);
1.1129    raeburn  1725:     }
1.1391    raeburn  1726:     return ($is_balancer,$otherserver,$setcookie,$offloadto,$dom_balancers);
1.1129    raeburn  1727: }
                   1728: 
1.1191    raeburn  1729: sub check_balancer_result {
                   1730:     my ($result,@hosts) = @_;
1.1391    raeburn  1731:     my ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1732:     if (ref($result) eq 'HASH') {
                   1733:         if ($result->{'lonhost'} ne '') {
                   1734:             my $currbalancer = $result->{'lonhost'};
                   1735:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1736:                 $is_balancer = 1;
                   1737:                 $currtargets = $result->{'targets'};
                   1738:                 $currrules = $result->{'rules'};
                   1739:             }
1.1391    raeburn  1740:             $dom_balancers = $currbalancer;
1.1191    raeburn  1741:         } else {
1.1391    raeburn  1742:             if (keys(%{$result})) {
                   1743:                 foreach my $key (keys(%{$result})) {
                   1744:                     if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1745:                         (ref($result->{$key}) eq 'HASH')) {
                   1746:                         $is_balancer = 1;
                   1747:                         $currrules = $result->{$key}{'rules'};
                   1748:                         $currtargets = $result->{$key}{'targets'};
                   1749:                         $setcookie = $result->{$key}{'cookie'};
                   1750:                         last;
                   1751:                     }
1.1191    raeburn  1752:                 }
1.1391    raeburn  1753:                 $dom_balancers = join(',',sort(keys(%{$result})));
1.1191    raeburn  1754:             }
                   1755:         }
                   1756:     }
1.1391    raeburn  1757:     return ($is_balancer,$currtargets,$currrules,$setcookie,$dom_balancers);
1.1191    raeburn  1758: }
                   1759: 
1.1129    raeburn  1760: sub get_loadbalancer_targets {
                   1761:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1762:     my $offloadto;
1.1175    raeburn  1763:     if ($rule_in_effect eq 'none') {
                   1764:         return [$perlvar{'lonHostID'}];
                   1765:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1766:         $offloadto = $currtargets;
                   1767:     } else {
                   1768:         if ($rule_in_effect eq 'homeserver') {
                   1769:             my $homeserver = &homeserver($uname,$udom);
                   1770:             if ($homeserver ne 'no_host') {
                   1771:                 $offloadto = [$homeserver];
                   1772:             }
                   1773:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1774:             my %domconfig =
                   1775:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1776:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1777:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1778:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1779:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1780:                     }
                   1781:                 }
                   1782:             } else {
1.1178    raeburn  1783:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1784:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1785:                 if (&hostname($remotebalancer) ne '') {
                   1786:                     $offloadto = [$remotebalancer];
                   1787:                 }
                   1788:             }
                   1789:         } elsif (&hostname($rule_in_effect) ne '') {
                   1790:             $offloadto = [$rule_in_effect];
                   1791:         }
                   1792:     }
                   1793:     return $offloadto;
                   1794: }
                   1795: 
1.1127    raeburn  1796: sub internet_dom_servers {
                   1797:     my ($dom) = @_;
                   1798:     my (%uniqservers,%servers);
                   1799:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1800:     my @machinedoms = &machine_domains($primaryserver);
                   1801:     foreach my $mdom (@machinedoms) {
                   1802:         my %currservers = %servers;
                   1803:         my %server = &get_servers($mdom);
                   1804:         %servers = (%currservers,%server);
                   1805:     }
                   1806:     my %by_hostname;
                   1807:     foreach my $id (keys(%servers)) {
                   1808:         push(@{$by_hostname{$servers{$id}}},$id);
                   1809:     }
                   1810:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1811:         if (@{$by_hostname{$hostname}} > 1) {
                   1812:             my $match = 0;
                   1813:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1814:                 if (&host_domain($id) eq $dom) {
                   1815:                     $uniqservers{$id} = $hostname;
                   1816:                     $match = 1;
                   1817:                 }
                   1818:             }
                   1819:             unless ($match) {
                   1820:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1821:             }
                   1822:         } else {
                   1823:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1824:         }
                   1825:     }
                   1826:     return %uniqservers;
                   1827: }
                   1828: 
1.1347    raeburn  1829: sub trusted_domains {
                   1830:     my ($cmdtype,$calldom) = @_;
1.1349    raeburn  1831:     my ($trusted,$untrusted);
1.1347    raeburn  1832:     if (&domain($calldom) eq '') {
1.1349    raeburn  1833:         return ($trusted,$untrusted);
1.1347    raeburn  1834:     }
1.1395    raeburn  1835:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|othcoau|domroles|catalog|reqcrs|msg)$/) {
1.1349    raeburn  1836:         return ($trusted,$untrusted);
1.1347    raeburn  1837:     }
                   1838:     my $callprimary = &domain($calldom,'primary');
                   1839:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
                   1840:     if ($intcalldom eq '') {
1.1349    raeburn  1841:         return ($trusted,$untrusted);
1.1347    raeburn  1842:     }
                   1843: 
                   1844:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
                   1845:     unless (defined($cached)) {
                   1846:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
                   1847:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
                   1848:         $trustconfig = $domconfig{'trust'};
                   1849:     }
                   1850:     if (ref($trustconfig)) {
                   1851:         my (%possexc,%possinc,@allexc,@allinc); 
                   1852:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
                   1853:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
                   1854:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
                   1855:             }
                   1856:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
1.1395    raeburn  1857:                 $possinc{$intcalldom} = 1;
1.1347    raeburn  1858:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
                   1859:             }
                   1860:         }
                   1861:         if (keys(%possexc)) {
                   1862:             if (keys(%possinc)) {
                   1863:                 foreach my $key (sort(keys(%possexc))) {
                   1864:                     next if ($key eq $intcalldom);
                   1865:                     unless ($possinc{$key}) {
                   1866:                         push(@allexc,$key);
                   1867:                     }
                   1868:                 }
                   1869:             } else {
                   1870:                 @allexc = sort(keys(%possexc));
                   1871:             }
                   1872:         }
                   1873:         if (keys(%possinc)) {
                   1874:             $possinc{$intcalldom} = 1;
                   1875:             @allinc = sort(keys(%possinc));
                   1876:         }
                   1877:         if ((@allexc > 0) || (@allinc > 0)) {
                   1878:             my %doms_by_intdom;
                   1879:             my %allintdoms = &all_host_intdom();
                   1880:             my %alldoms = &all_host_domain();
                   1881:             foreach my $key (%allintdoms) {
                   1882:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
                   1883:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
                   1884:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
                   1885:                     }
                   1886:                 } else {
                   1887:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
                   1888:                 }
                   1889:             }
                   1890:             foreach my $exc (@allexc) {
                   1891:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1395    raeburn  1892:                     push(@{$untrusted},@{$doms_by_intdom{$exc}});
1.1347    raeburn  1893:                 }
                   1894:             }
                   1895:             foreach my $inc (@allinc) {
                   1896:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1395    raeburn  1897:                     push(@{$trusted},@{$doms_by_intdom{$inc}});
1.1347    raeburn  1898:                 }
                   1899:             }
                   1900:         }
                   1901:     }
1.1349    raeburn  1902:     return ($trusted,$untrusted);
1.1347    raeburn  1903: }
                   1904: 
                   1905: sub will_trust {
                   1906:     my ($cmdtype,$domain,$possdom) = @_;
                   1907:     return 1 if ($domain eq $possdom);
                   1908:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
                   1909:     my $willtrust; 
                   1910:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
                   1911:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
                   1912:             $willtrust = 1;
                   1913:         }
                   1914:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
                   1915:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
                   1916:             $willtrust = 1;
                   1917:         }
                   1918:     } else {
                   1919:         $willtrust = 1;
                   1920:     }
                   1921:     return $willtrust;
                   1922: }
                   1923: 
1.1       albertel 1924: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1925: 
1.599     albertel 1926: my %homecache;
1.1       albertel 1927: sub homeserver {
1.230     stredwic 1928:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1929:     my $index="$uname:$udom";
1.426     albertel 1930: 
1.599     albertel 1931:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1932: 
                   1933:     my %servers = &get_servers($udom,'library');
                   1934:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1935:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1936: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1937: 
                   1938: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1939: 	if ($answer eq 'found') {
                   1940: 	    delete($badServerCache{$tryserver}); 
                   1941: 	    return $homecache{$index}=$tryserver;
                   1942: 	} elsif ($answer eq 'no_host') {
                   1943: 	    $badServerCache{$tryserver}=1;
                   1944: 	}
1.1       albertel 1945:     }    
                   1946:     return 'no_host';
1.70      www      1947: }
                   1948: 
1.1300    raeburn  1949: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1950: 
                   1951: sub idget {
1.1300    raeburn  1952:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1953:     my %returnhash=();
1.1300    raeburn  1954:     my @ids=(); 
                   1955:     if (ref($idsref) eq 'ARRAY') {
                   1956:         @ids = @{$idsref};
                   1957:     } else {
                   1958:         return %returnhash; 
                   1959:     }
                   1960:     if ($namespace eq '') {
                   1961:         $namespace = 'ids';
                   1962:     }
1.70      www      1963:     
1.841     albertel 1964:     my %servers = &get_servers($udom,'library');
                   1965:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1966: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1967: 	if ($namespace eq 'ids') {
                   1968: 	    $idlist=~tr/A-Z/a-z/;
                   1969: 	}
                   1970: 	my $reply;
                   1971: 	if ($namespace eq 'ids') {
                   1972: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1973: 	} else {
                   1974: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1975: 	}
1.841     albertel 1976: 	my @answer=();
                   1977: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1978: 	    @answer=split(/\&/,$reply);
                   1979: 	}                    ;
                   1980: 	my $i;
                   1981: 	for ($i=0;$i<=$#ids;$i++) {
                   1982: 	    if ($answer[$i]) {
1.1299    raeburn  1983: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1984: 	    }
1.841     albertel 1985: 	}
1.1300    raeburn  1986:     }
1.70      www      1987:     return %returnhash;
                   1988: }
                   1989: 
                   1990: # ------------------------------------- Find the IDs behind a list of usernames
                   1991: 
                   1992: sub idrget {
                   1993:     my ($udom,@unames)=@_;
                   1994:     my %returnhash=();
1.800     albertel 1995:     foreach my $uname (@unames) {
                   1996:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1997:     }
1.70      www      1998:     return %returnhash;
                   1999: }
                   2000: 
1.1300    raeburn  2001: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      2002: 
                   2003: sub idput {
1.1300    raeburn  2004:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      2005:     my %servers=();
1.1300    raeburn  2006:     my %ids=();
                   2007:     my %byid = ();
                   2008:     if (ref($idsref) eq 'HASH') {
                   2009:         %ids=%{$idsref};
                   2010:     }
                   2011:     if ($namespace eq '') {
                   2012:         $namespace = 'ids'; 
                   2013:     }
1.800     albertel 2014:     foreach my $uname (keys(%ids)) {
                   2015: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  2016:         if ($uhom eq '') {
                   2017:             $uhom=&homeserver($uname,$udom);
                   2018:         }
1.70      www      2019:         if ($uhom ne 'no_host') {
1.800     albertel 2020:             my $esc_unam=&escape($uname);
1.1300    raeburn  2021:             if ($namespace eq 'ids') {
                   2022:                 my $id=&escape($ids{$uname});
                   2023:                 $id=~tr/A-Z/a-z/;
                   2024:                 my $esc_unam=&escape($uname);
                   2025:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      2026:             } else {
1.1300    raeburn  2027:                 my @currids = split(/,/,$ids{$uname});
                   2028:                 foreach my $id (@currids) {
                   2029:                     $byid{$uhom}{$id} .= $uname.',';
                   2030:                 }
                   2031:             }
                   2032:         }
                   2033:     }
                   2034:     if ($namespace eq 'clickers') {
                   2035:         foreach my $server (keys(%byid)) {
                   2036:             if (ref($byid{$server}) eq 'HASH') {
                   2037:                 foreach my $id (keys(%{$byid{$server}})) {
                   2038:                     $byid{$server} =~ s/,$//;
                   2039:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   2040:                 }
1.70      www      2041:             }
                   2042:         }
1.191     harris41 2043:     }
1.800     albertel 2044:     foreach my $server (keys(%servers)) {
1.1300    raeburn  2045:         $servers{$server} =~ s/\&$//;
                   2046:         if ($namespace eq 'ids') {     
                   2047:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   2048:         } else {
                   2049:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   2050:         }
1.191     harris41 2051:     }
1.344     www      2052: }
                   2053: 
1.1300    raeburn  2054: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  2055: 
                   2056: sub iddel {
1.1300    raeburn  2057:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  2058:     my %result=();
1.1300    raeburn  2059:     my %ids=();
                   2060:     my %byid = ();
                   2061:     if (ref($idshashref) eq 'HASH') {
                   2062:         %ids=%{$idshashref};
                   2063:     } else {
1.1231    raeburn  2064:         return %result;
                   2065:     }
1.1300    raeburn  2066:     if ($namespace eq '') {
                   2067:         $namespace = 'ids';
                   2068:     }
1.1231    raeburn  2069:     my %servers=();
1.1300    raeburn  2070:     while (my ($id,$unamestr) = each(%ids)) {
                   2071:         if ($namespace eq 'ids') {
                   2072:             my $uhom = $uhome;
                   2073:             if ($uhom eq '') { 
                   2074:                 $uhom=&homeserver($unamestr,$udom);
                   2075:             }
                   2076:             if ($uhom ne 'no_host') {
                   2077:                 $servers{$uhom}.='&'.&escape($id);
                   2078:             }
                   2079:          } else {
                   2080:             my @curritems = split(/,/,$ids{$id});
                   2081:             foreach my $uname (@curritems) {
                   2082:                 my $uhom = $uhome;
                   2083:                 if ($uhom eq '') {
                   2084:                     $uhom=&homeserver($uname,$udom);
                   2085:                 }
                   2086:                 if ($uhom ne 'no_host') { 
                   2087:                     $byid{$uhom}{$id} .= $uname.',';
                   2088:                 }
                   2089:             }
1.1231    raeburn  2090:         }
1.1300    raeburn  2091:     }
                   2092:     if ($namespace eq 'clickers') {
                   2093:         foreach my $server (keys(%byid)) {
                   2094:             if (ref($byid{$server}) eq 'HASH') {
                   2095:                 foreach my $id (keys(%{$byid{$server}})) {
                   2096:                     $byid{$server}{$id} =~ s/,$//;
                   2097:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   2098:                 }
1.1231    raeburn  2099:             }
                   2100:         }
                   2101:     }
                   2102:     foreach my $server (keys(%servers)) {
1.1300    raeburn  2103:         $servers{$server} =~ s/\&$//;
                   2104:         if ($namespace eq 'ids') {
                   2105:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   2106:         } elsif ($namespace eq 'clickers') {
                   2107:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   2108:         }
1.1231    raeburn  2109:     }
                   2110:     return %result;
                   2111: }
                   2112: 
1.1300    raeburn  2113: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   2114: 
                   2115: sub updateclickers {
                   2116:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   2117:     my %clickers;
                   2118:     if (ref($idshashref) eq 'HASH') {
                   2119:         %clickers=%{$idshashref};
                   2120:     } else {
                   2121:         return;
                   2122:     }
                   2123:     my $items='';
                   2124:     foreach my $item (keys(%clickers)) {
                   2125:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   2126:     }
                   2127:     $items=~s/\&$//;
                   2128:     my $request = "updateclickers:$udom:$action:$items";
                   2129:     if ($critical) {
                   2130:         return &critical($request,$uhome);
                   2131:     } else {
                   2132:         return &reply($request,$uhome);
                   2133:     }
                   2134: }
                   2135: 
1.1023    raeburn  2136: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  2137: sub dump_dom {
1.1165    droeschl 2138:     my ($namespace, $udom, $regexp) = @_;
                   2139: 
                   2140:     $udom ||= $env{'user.domain'};
                   2141: 
                   2142:     return () unless $udom;
                   2143: 
                   2144:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  2145: }
                   2146: 
1.1023    raeburn  2147: # ------------------------------------------ get items from domain db files   
1.806     raeburn  2148: 
                   2149: sub get_dom {
1.1462    raeburn  2150:     my ($namespace,$storearr,$udom,$uhome,$encrypt)=@_;
1.1267    raeburn  2151:     return if ($udom eq 'public');
1.806     raeburn  2152:     my $items='';
                   2153:     foreach my $item (@$storearr) {
                   2154:         $items.=&escape($item).'&';
                   2155:     }
                   2156:     $items=~s/\&$//;
1.860     raeburn  2157:     if (!$udom) {
                   2158:         $udom=$env{'user.domain'};
1.1267    raeburn  2159:         return if ($udom eq 'public');
1.860     raeburn  2160:         if (defined(&domain($udom,'primary'))) {
                   2161:             $uhome=&domain($udom,'primary');
                   2162:         } else {
1.874     albertel 2163:             undef($uhome);
1.860     raeburn  2164:         }
                   2165:     } else {
                   2166:         if (!$uhome) {
                   2167:             if (defined(&domain($udom,'primary'))) {
                   2168:                 $uhome=&domain($udom,'primary');
                   2169:             }
                   2170:         }
                   2171:     }
                   2172:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344    raeburn  2173:         my $rep;
1.1442    raeburn  2174:         if (grep { $_ eq $uhome } &current_machine_ids()) {
                   2175:             # domain information is hosted on this machine
1.1462    raeburn  2176:             $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
1.1344    raeburn  2177:         } else {
1.1462    raeburn  2178:             if ($encrypt) {
1.1442    raeburn  2179:                 $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   2180:             } else {
                   2181:                 $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   2182:             }
1.1344    raeburn  2183:         }
1.866     raeburn  2184:         my %returnhash;
1.875     albertel 2185:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  2186:             return %returnhash;
                   2187:         }
1.806     raeburn  2188:         my @pairs=split(/\&/,$rep);
                   2189:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   2190:             return @pairs;
                   2191:         }
                   2192:         my $i=0;
                   2193:         foreach my $item (@$storearr) {
                   2194:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   2195:             $i++;
                   2196:         }
                   2197:         return %returnhash;
                   2198:     } else {
1.880     banghart 2199:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  2200:     }
                   2201: }
                   2202: 
                   2203: # -------------------------------------------- put items in domain db files 
                   2204: 
                   2205: sub put_dom {
1.1462    raeburn  2206:     my ($namespace,$storehash,$udom,$uhome,$encrypt)=@_;
1.860     raeburn  2207:     if (!$udom) {
                   2208:         $udom=$env{'user.domain'};
                   2209:         if (defined(&domain($udom,'primary'))) {
                   2210:             $uhome=&domain($udom,'primary');
                   2211:         } else {
1.874     albertel 2212:             undef($uhome);
1.860     raeburn  2213:         }
                   2214:     } else {
                   2215:         if (!$uhome) {
                   2216:             if (defined(&domain($udom,'primary'))) {
                   2217:                 $uhome=&domain($udom,'primary');
                   2218:             }
                   2219:         }
                   2220:     } 
                   2221:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  2222:         my $items='';
                   2223:         foreach my $item (keys(%$storehash)) {
                   2224:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   2225:         }
                   2226:         $items=~s/\&$//;
1.1462    raeburn  2227:         if ($encrypt) {
1.1344    raeburn  2228:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   2229:         } else {
                   2230:             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   2231:         }
1.806     raeburn  2232:     } else {
1.860     raeburn  2233:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  2234:     }
                   2235: }
                   2236: 
1.1023    raeburn  2237: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  2238: sub newput_dom {
1.1023    raeburn  2239:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  2240:     my $result;
                   2241:     if (!$udom) {
                   2242:         $udom=$env{'user.domain'};
                   2243:     }
1.1023    raeburn  2244:     if ($udom) {
                   2245:         my $uname = &get_domainconfiguser($udom);
                   2246:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2247:     }
                   2248:     return $result;
                   2249: }
                   2250: 
1.1023    raeburn  2251: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2252: sub del_dom {
1.1023    raeburn  2253:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2254:     if (ref($storearr) eq 'ARRAY') {
                   2255:         if (!$udom) {
                   2256:             $udom=$env{'user.domain'};
                   2257:         }
1.1023    raeburn  2258:         if ($udom) {
                   2259:             my $uname = &get_domainconfiguser($udom); 
                   2260:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2261:         }
                   2262:     }
                   2263: }
                   2264: 
1.1481    raeburn  2265: sub store_dom {
1.1482  ! raeburn  2266:     my ($storehash,$id,$namespace,$dom,$home,$encrypt) = @_;
1.1481    raeburn  2267:     $$storehash{'ip'}=&get_requestor_ip();
                   2268:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   2269:     my $namevalue='';
                   2270:     foreach my $key (keys(%{$storehash})) {
                   2271:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   2272:     }
                   2273:     $namevalue=~s/\&$//;
                   2274:     if (grep { $_ eq $home } current_machine_ids()) {
                   2275:         return LONCAPA::Lond::store_dom("storedom:$dom:$namespace:$id:$namevalue");
                   2276:     } else {
                   2277:         if ($namespace eq 'private') {
                   2278:             return 'refused';
1.1482  ! raeburn  2279:         } elsif ($encrypt) {
        !          2280:             return reply("encrypt:storedom:$dom:$namespace:$id:$namevalue",$home);
1.1481    raeburn  2281:         } else {
1.1482  ! raeburn  2282:             return reply("storedom:$dom:$namespace:$id:$namevalue",$home);
1.1481    raeburn  2283:         }
                   2284:     }
                   2285: }
                   2286: 
1.1482  ! raeburn  2287: sub restore_dom {
        !          2288:     my ($id,$namespace,$dom,$home,$encrypt) = @_;
        !          2289:     my $answer;
        !          2290:     if (grep { $_ eq $home } current_machine_ids()) {
        !          2291:         $answer = LONCAPA::Lond::restore_dom("restoredom:$dom:$namespace:$id");
        !          2292:     } elsif ($namespace ne 'private') {
        !          2293:         if ($encrypt) {
        !          2294:             $answer=&reply("encrypt:restoredom:$dom:$namespace:$id",$home);
        !          2295:         } else {
        !          2296:             $answer=&reply("restoredom:$dom:$namespace:$id",$home);
        !          2297:         }
        !          2298:     }
        !          2299:     my %returnhash=();
        !          2300:     unless (($answer eq '') || ($answer eq 'con_lost') || ($answer eq 'refused') || 
        !          2301:             ($answer eq 'unknown_cmd') || ($answer eq 'rejected')) {
        !          2302:         foreach my $line (split(/\&/,$answer)) {
        !          2303:             my ($name,$value)=split(/\=/,$line);
        !          2304:             $returnhash{&unescape($name)}=&thaw_unescape($value);
        !          2305:         }
        !          2306:         my $version;
        !          2307:         for ($version=1;$version<=$returnhash{'version'};$version++) {
        !          2308:             foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
        !          2309:                 $returnhash{$item}=$returnhash{$version.':'.$item};
        !          2310:             }
        !          2311:         }
        !          2312:     }
        !          2313:     return %returnhash;
        !          2314: }
        !          2315: 
1.1023    raeburn  2316: # ----------------------------------construct domainconfig user for a domain 
                   2317: sub get_domainconfiguser {
                   2318:     my ($udom) = @_;
                   2319:     return $udom.'-domainconfig';
                   2320: }
                   2321: 
1.837     raeburn  2322: sub retrieve_inst_usertypes {
                   2323:     my ($udom) = @_;
                   2324:     my (%returnhash,@order);
1.989     raeburn  2325:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2326:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2327:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  2328:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2329:     } else {
                   2330:         if (defined(&domain($udom,'primary'))) {
                   2331:             my $uhome=&domain($udom,'primary');
                   2332:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2333:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  2334:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2335:                 return (\%returnhash,\@order);
                   2336:             }
                   2337:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2338:             my @pairs=split(/\&/,$hashitems);
                   2339:             foreach my $item (@pairs) {
                   2340:                 my ($key,$value)=split(/=/,$item,2);
                   2341:                 $key = &unescape($key);
                   2342:                 next if ($key =~ /^error: 2 /);
                   2343:                 $returnhash{$key}=&thaw_unescape($value);
                   2344:             }
                   2345:             my @esc_order = split(/\&/,$orderitems);
                   2346:             foreach my $item (@esc_order) {
                   2347:                 push(@order,&unescape($item));
                   2348:             }
                   2349:         } else {
1.1256    raeburn  2350:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2351:         }
1.1256    raeburn  2352:         return (\%returnhash,\@order);
1.837     raeburn  2353:     }
                   2354: }
                   2355: 
1.868     raeburn  2356: sub is_domainimage {
                   2357:     my ($url) = @_;
1.1468    raeburn  2358:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo|login)/+[^/]-) {
1.868     raeburn  2359:         if (&domain($1) ne '') {
                   2360:             return '1';
                   2361:         }
                   2362:     }
                   2363:     return;
                   2364: }
                   2365: 
1.899     raeburn  2366: sub inst_directory_query {
                   2367:     my ($srch) = @_;
                   2368:     my $udom = $srch->{'srchdomain'};
                   2369:     my %results;
                   2370:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2371:     my $outcome;
1.899     raeburn  2372:     if ($homeserver ne '') {
1.1357    raeburn  2373:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2374:             if ($srch->{'srchby'} eq 'email') {
1.1417    raeburn  2375:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
1.1357    raeburn  2376:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2377:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2378:                     (($major == 2) && ($minor < 12))) {
                   2379:                     return;
                   2380:                 }
                   2381:             }
                   2382:         }
1.904     albertel 2383: 	my $queryid=&reply("querysend:instdirsearch:".
                   2384: 			   &escape($srch->{'srchby'}).':'.
                   2385: 			   &escape($srch->{'srchterm'}).':'.
                   2386: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2387: 	my $host=&hostname($homeserver);
                   2388: 	if ($queryid !~/^\Q$host\E\_/) {
1.1343    raeburn  2389: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2390: 	    return;
                   2391: 	}
                   2392: 	my $response = &get_query_reply($queryid);
                   2393: 	my $maxtries = 5;
                   2394: 	my $tries = 1;
                   2395: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2396: 	    $response = &get_query_reply($queryid);
                   2397: 	    $tries ++;
                   2398: 	}
                   2399: 
                   2400:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2401:             if ($response eq 'unavailable') {
                   2402:                 $outcome = $response;
                   2403:             } else {
                   2404:                 $outcome = 'ok';
                   2405:                 my @matches = split(/\n/,$response);
                   2406:                 foreach my $match (@matches) {
                   2407:                     my ($key,$value) = split(/=/,$match);
                   2408:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2409:                 }
1.899     raeburn  2410:             }
                   2411:         }
                   2412:     }
1.909     raeburn  2413:     return ($outcome,%results);
1.899     raeburn  2414: }
                   2415: 
                   2416: sub usersearch {
                   2417:     my ($srch) = @_;
                   2418:     my $dom = $srch->{'srchdomain'};
                   2419:     my %results;
                   2420:     my %libserv = &all_library();
                   2421:     my $query = 'usersearch';
                   2422:     foreach my $tryserver (keys(%libserv)) {
                   2423:         if (&host_domain($tryserver) eq $dom) {
1.1357    raeburn  2424:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2425:                 if ($srch->{'srchby'} eq 'email') {
1.1417    raeburn  2426:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
1.1357    raeburn  2427:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2428:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2429:                              (($major == 2) && ($minor < 12)));
                   2430:                 }
                   2431:             }
1.899     raeburn  2432:             my $host=&hostname($tryserver);
                   2433:             my $queryid=
1.911     raeburn  2434:                 &reply("querysend:".&escape($query).':'.
                   2435:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2436:                        &escape($srch->{'srchtype'}).':'.
                   2437:                        &escape($srch->{'srchterm'}),$tryserver);
                   2438:             if ($queryid !~/^\Q$host\E\_/) {
                   2439:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2440:                 next;
1.899     raeburn  2441:             }
                   2442:             my $reply = &get_query_reply($queryid);
                   2443:             my $maxtries = 1;
                   2444:             my $tries = 1;
                   2445:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2446:                 $reply = &get_query_reply($queryid);
                   2447:                 $tries ++;
                   2448:             }
                   2449:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2450:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2451:             } else {
1.911     raeburn  2452:                 my @matches;
                   2453:                 if ($reply =~ /\n/) {
                   2454:                     @matches = split(/\n/,$reply);
                   2455:                 } else {
                   2456:                     @matches = split(/\&/,$reply);
                   2457:                 }
1.899     raeburn  2458:                 foreach my $match (@matches) {
                   2459:                     my ($uname,$udom,%userhash);
1.911     raeburn  2460:                     foreach my $entry (split(/:/,$match)) {
                   2461:                         my ($key,$value) =
                   2462:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2463:                         $userhash{$key} = $value;
                   2464:                         if ($key eq 'username') {
                   2465:                             $uname = $value;
                   2466:                         } elsif ($key eq 'domain') {
                   2467:                             $udom = $value;
1.911     raeburn  2468:                         }
1.899     raeburn  2469:                     }
                   2470:                     $results{$uname.':'.$udom} = \%userhash;
                   2471:                 }
                   2472:             }
                   2473:         }
                   2474:     }
                   2475:     return %results;
                   2476: }
                   2477: 
1.912     raeburn  2478: sub get_instuser {
                   2479:     my ($udom,$uname,$id) = @_;
                   2480:     my $homeserver = &domain($udom,'primary');
                   2481:     my ($outcome,%results);
                   2482:     if ($homeserver ne '') {
                   2483:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2484:                            &escape($id).':'.&escape($udom),$homeserver);
                   2485:         my $host=&hostname($homeserver);
                   2486:         if ($queryid !~/^\Q$host\E\_/) {
                   2487:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2488:             return;
                   2489:         }
                   2490:         my $response = &get_query_reply($queryid);
                   2491:         my $maxtries = 5;
                   2492:         my $tries = 1;
                   2493:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2494:             $response = &get_query_reply($queryid);
                   2495:             $tries ++;
                   2496:         }
                   2497:         if (!&error($response) && $response ne 'refused') {
                   2498:             if ($response eq 'unavailable') {
                   2499:                 $outcome = $response;
                   2500:             } else {
                   2501:                 $outcome = 'ok';
                   2502:                 my @matches = split(/\n/,$response);
                   2503:                 foreach my $match (@matches) {
                   2504:                     my ($key,$value) = split(/=/,$match);
                   2505:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2506:                 }
                   2507:             }
                   2508:         }
                   2509:     }
                   2510:     my %userinfo;
                   2511:     if (ref($results{$uname}) eq 'HASH') {
                   2512:         %userinfo = %{$results{$uname}};
                   2513:     } 
                   2514:     return ($outcome,%userinfo);
                   2515: }
                   2516: 
1.1290    raeburn  2517: sub get_multiple_instusers {
                   2518:     my ($udom,$users,$caller) = @_;
                   2519:     my ($outcome,$results);
                   2520:     if (ref($users) eq 'HASH') {
                   2521:         my $count = keys(%{$users}); 
                   2522:         my $requested = &freeze_escape($users);
                   2523:         my $homeserver = &domain($udom,'primary');
                   2524:         if ($homeserver ne '') {
                   2525:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2526:             my $host=&hostname($homeserver);
                   2527:             if ($queryid !~/^\Q$host\E\_/) {
                   2528:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2529:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2530:                 return ($outcome,$results);
                   2531:             }
                   2532:             my $response = &get_query_reply($queryid);
                   2533:             my $maxtries = 5;
                   2534:             if ($count > 100) {
                   2535:                 $maxtries = 1+int($count/20);
                   2536:             }
                   2537:             my $tries = 1;
                   2538:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2539:                 $response = &get_query_reply($queryid);
                   2540:                 $tries ++;
                   2541:             }
                   2542:             if ($response eq '') {
                   2543:                 $results = {};
                   2544:                 foreach my $key (keys(%{$users})) {
                   2545:                     my ($uname,$id);
                   2546:                     if ($caller eq 'id') {
                   2547:                         $id = $key;
                   2548:                     } else {
                   2549:                         $uname = $key;
                   2550:                     }
                   2551:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2552:                     $outcome = $resp;
1.1290    raeburn  2553:                     if ($resp eq 'ok') {
                   2554:                         %{$results} = (%{$results}, %info);
                   2555:                     } else {
                   2556:                         last;
                   2557:                     }
                   2558:                 }
                   2559:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2560:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2561:                     $outcome = $response;
                   2562:                 } else {
1.1291    raeburn  2563:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2564:                     if ($outcome eq 'ok') {
                   2565:                         $results = &thaw_unescape($userdata); 
                   2566:                     }
                   2567:                 }
                   2568:             }
                   2569:         }
                   2570:     }
                   2571:     return ($outcome,$results);
                   2572: }
                   2573: 
1.912     raeburn  2574: sub inst_rulecheck {
1.923     raeburn  2575:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2576:     my %returnhash;
                   2577:     if ($udom ne '') {
                   2578:         if (ref($rules) eq 'ARRAY') {
                   2579:             @{$rules} = map {&escape($_);} (@{$rules});
                   2580:             my $rulestr = join(':',@{$rules});
                   2581:             my $homeserver=&domain($udom,'primary');
                   2582:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2583:                 my $response;
                   2584:                 if ($item eq 'username') {                
                   2585:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2586:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2587:                                               $homeserver));
1.923     raeburn  2588:                 } elsif ($item eq 'id') {
                   2589:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2590:                                               ':'.&escape($id).':'.$rulestr,
                   2591:                                               $homeserver));
1.945     raeburn  2592:                 } elsif ($item eq 'selfcreate') {
                   2593:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2594:                                                &escape($udom).':'.&escape($uname).
                   2595:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2596:                 }
1.912     raeburn  2597:                 if ($response ne 'refused') {
                   2598:                     my @pairs=split(/\&/,$response);
                   2599:                     foreach my $item (@pairs) {
                   2600:                         my ($key,$value)=split(/=/,$item,2);
                   2601:                         $key = &unescape($key);
                   2602:                         next if ($key =~ /^error: 2 /);
                   2603:                         $returnhash{$key}=&thaw_unescape($value);
                   2604:                     }
                   2605:                 }
                   2606:             }
                   2607:         }
                   2608:     }
                   2609:     return %returnhash;
                   2610: }
                   2611: 
                   2612: sub inst_userrules {
1.923     raeburn  2613:     my ($udom,$check) = @_;
1.912     raeburn  2614:     my (%ruleshash,@ruleorder);
                   2615:     if ($udom ne '') {
                   2616:         my $homeserver=&domain($udom,'primary');
                   2617:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2618:             my $response;
                   2619:             if ($check eq 'id') {
                   2620:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2621:                                  $homeserver);
1.943     raeburn  2622:             } elsif ($check eq 'email') {
                   2623:                 $response=&reply('instemailrules:'.&escape($udom),
                   2624:                                  $homeserver);
1.923     raeburn  2625:             } else {
                   2626:                 $response=&reply('instuserrules:'.&escape($udom),
                   2627:                                  $homeserver);
                   2628:             }
1.912     raeburn  2629:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2630:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2631:                 ($response ne 'no_such_host')) {
                   2632:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2633:                 my @pairs=split(/\&/,$hashitems);
                   2634:                 foreach my $item (@pairs) {
                   2635:                     my ($key,$value)=split(/=/,$item,2);
                   2636:                     $key = &unescape($key);
                   2637:                     next if ($key =~ /^error: 2 /);
                   2638:                     $ruleshash{$key}=&thaw_unescape($value);
                   2639:                 }
                   2640:                 my @esc_order = split(/\&/,$orderitems);
                   2641:                 foreach my $item (@esc_order) {
                   2642:                     push(@ruleorder,&unescape($item));
                   2643:                 }
                   2644:             }
                   2645:         }
                   2646:     }
                   2647:     return (\%ruleshash,\@ruleorder);
                   2648: }
                   2649: 
1.976     raeburn  2650: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2651: 
                   2652: sub get_domain_defaults {
1.1240    raeburn  2653:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2654:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2655:     my $cachetime = 60*60*24;
1.1240    raeburn  2656:     unless ($ignore_cache) {
                   2657:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2658:         if (defined($cached)) {
                   2659:             if (ref($result) eq 'HASH') {
                   2660:                 return %{$result};
                   2661:             }
1.943     raeburn  2662:         }
                   2663:     }
                   2664:     my %domdefaults;
                   2665:     my %domconfig =
1.989     raeburn  2666:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2667:                                   'requestcourses','inststatus',
1.1183    raeburn  2668:                                   'coursedefaults','usersessions',
1.1258    raeburn  2669:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2670:                                   'coursecategories','ssl','autoenroll',
1.1482  ! raeburn  2671:                                   'trust','helpsettings','wafproxy','ltisec'],$domain);
1.1305    raeburn  2672:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2673:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2674:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2675:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2676:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2677:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2678:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2679:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340    raeburn  2680:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2681:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2682:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2683:     } else {
                   2684:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2685:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2686:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2687:     }
1.976     raeburn  2688:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2689:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2690:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2691:         } else {
                   2692:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2693:         }
1.1177    raeburn  2694:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2695:         foreach my $item (@usertools) {
                   2696:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2697:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2698:             }
                   2699:         }
1.1229    raeburn  2700:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2701:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2702:         }
1.976     raeburn  2703:     }
1.985     raeburn  2704:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2705:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2706:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2707:         }
                   2708:     }
1.1183    raeburn  2709:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2710:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2711:     }
1.989     raeburn  2712:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2713:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2714:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2715:         }
                   2716:     }
1.1047    raeburn  2717:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2718:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2719:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
1.1476    raeburn  2720:         $domdefaults{'inline_chem'} = $domconfig{'coursedefaults'}{'inline_chem'};
1.1277    raeburn  2721:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2722:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2723:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2724:         }
1.1254    raeburn  2725:         foreach my $type (@coursetypes) {
                   2726:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2727:                 unless ($type eq 'community') {
                   2728:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2729:                 }
                   2730:             }
                   2731:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2732:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2733:             }
1.1277    raeburn  2734:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2735:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2736:                     $domdefaults{$type.'postsubtimeout'} = 
                   2737:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2738:                 }
                   2739:             }
1.1230    raeburn  2740:         }
1.1286    raeburn  2741:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2742:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2743:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2744:                 if (@clonecodes) {
                   2745:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2746:                 }
                   2747:             }
                   2748:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2749:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2750:         }
1.1356    raeburn  2751:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2752:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
1.1480    raeburn  2753:         }
                   2754:         if (exists($domconfig{'coursedefaults'}{'ltiauth'})) {
                   2755:             $domdefaults{'crsltiauth'} = $domconfig{'coursedefaults'}{'ltiauth'};
                   2756:         }
1.1047    raeburn  2757:     }
1.1073    raeburn  2758:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2759:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2760:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2761:         }
                   2762:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2763:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2764:         }
1.1279    raeburn  2765:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2766:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2767:         }
1.1440    raeburn  2768:         if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
1.1439    raeburn  2769:             $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
                   2770:         }
1.1073    raeburn  2771:     }
1.1254    raeburn  2772:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2773:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2774:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2775:                             'approval','limit');
                   2776:             foreach my $type (@coursetypes) {
                   2777:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2778:                     my @mgrdc = ();
                   2779:                     foreach my $item (@settings) {
                   2780:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2781:                             push(@mgrdc,$item);
                   2782:                         }
                   2783:                     }
                   2784:                     if (@mgrdc) {
                   2785:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2786:                     }
                   2787:                 }
                   2788:             }
                   2789:         }
                   2790:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2791:             foreach my $type (@coursetypes) {
                   2792:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2793:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2794:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2795:                     }
                   2796:                 }
                   2797:             }
                   2798:         }
                   2799:     }
1.1258    raeburn  2800:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2801:         $domdefaults{'catauth'} = 'std';
                   2802:         $domdefaults{'catunauth'} = 'std';
1.1413    raeburn  2803:         if ($domconfig{'coursecategories'}{'auth'}) {
1.1258    raeburn  2804:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2805:         }
                   2806:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2807:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2808:         }
                   2809:     }
1.1315    raeburn  2810:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2811:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2812:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2813:         }
1.1338    raeburn  2814:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
                   2815:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
                   2816:         }
                   2817:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
                   2818:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315    raeburn  2819:         }
                   2820:     }
1.1320    raeburn  2821:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2822:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2823:         foreach my $prefix (@prefixes) {
                   2824:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2825:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2826:             }
                   2827:         }
                   2828:     }
1.1314    raeburn  2829:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2830:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
1.1477    raeburn  2831:         $domdefaults{'failsafe'} = $domconfig{'autoenroll'}{'failsafe'};
1.1314    raeburn  2832:     }
1.1332    raeburn  2833:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2834:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2835:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2836:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2837:         }
                   2838:     }
1.1434    raeburn  2839:     if (ref($domconfig{'wafproxy'}) eq 'HASH') {
1.1449    raeburn  2840:         foreach my $item ('ipheader','trusted','vpnint','vpnext','sslopt') {
1.1434    raeburn  2841:             if ($domconfig{'wafproxy'}{$item}) {
                   2842:                 $domdefaults{'waf_'.$item} = $domconfig{'wafproxy'}{$item};
                   2843:             }
                   2844:         }
1.1482  ! raeburn  2845:     }
        !          2846:     if (ref($domconfig{'ltisec'}) eq 'HASH') {
        !          2847:         if (ref($domconfig{'ltisec'}{'encrypt'}) eq 'HASH') {
        !          2848:             $domdefaults{'linkprotenc_crs'} = $domconfig{'ltisec'}{'encrypt'}{'crs'};
        !          2849:             $domdefaults{'linkprotenc_dom'} = $domconfig{'ltisec'}{'encrypt'}{'dom'};
        !          2850:             $domdefaults{'ltienc_consumers'} = $domconfig{'ltisec'}{'encrypt'}{'consumers'};
        !          2851:         }
        !          2852:         if (ref($domconfig{'ltisec'}{'private'}) eq 'HASH') {
        !          2853:             if (ref($domconfig{'ltisec'}{'private'}{'keys'}) eq 'ARRAY') {
        !          2854:                 $domdefaults{'privhosts'} = $domconfig{'ltisec'}{'private'}{'keys'};
        !          2855:             }
        !          2856:         }
        !          2857:     }
1.1219    raeburn  2858:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2859:     return %domdefaults;
                   2860: }
                   2861: 
1.1412    raeburn  2862: sub get_dom_cats {
                   2863:     my ($dom) = @_;
                   2864:     return unless (&domain($dom));
                   2865:     my ($cats,$cached)=&is_cached_new('cats',$dom);
                   2866:     unless (defined($cached)) {
                   2867:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
                   2868:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2869:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
                   2870:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
                   2871:             } else {
                   2872:                 $cats = {};
                   2873:             }
                   2874:         } else {
                   2875:             $cats = {};
                   2876:         }
                   2877:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
                   2878:     }
1.1413    raeburn  2879:     return $cats;
                   2880: }
                   2881: 
                   2882: sub get_dom_instcats {
                   2883:     my ($dom) = @_;
                   2884:     return unless (&domain($dom));
                   2885:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
                   2886:     unless (defined($cached)) {
                   2887:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
                   2888:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
                   2889:         if ($totcodes > 0) {
                   2890:             my $caller = 'global';
                   2891:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
                   2892:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
                   2893:                 $instcats = {
                   2894:                                 codes => \%codes,
                   2895:                                 codetitles => \@codetitles,
                   2896:                                 cat_titles => \%cat_titles,
                   2897:                                 cat_order => \%cat_order,
                   2898:                             };
                   2899:                 &do_cache_new('instcats',$dom,$instcats,3600);
                   2900:             }
                   2901:         }
                   2902:     }
                   2903:     return $instcats;
                   2904: }
                   2905: 
                   2906: sub retrieve_instcodes {
                   2907:     my ($coursecodes,$dom) = @_;
                   2908:     my $totcodes;
                   2909:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
                   2910:     foreach my $course (keys(%courses)) {
                   2911:         if (ref($courses{$course}) eq 'HASH') {
                   2912:             if ($courses{$course}{'inst_code'} ne '') {
                   2913:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
                   2914:                 $totcodes ++;
                   2915:             }
                   2916:         }
                   2917:     }
                   2918:     return $totcodes;
1.1412    raeburn  2919: }
                   2920: 
1.1311    raeburn  2921: sub course_portal_url {
1.1451    raeburn  2922:     my ($cnum,$cdom,$r) = @_;
1.1311    raeburn  2923:     my $chome = &homeserver($cnum,$cdom);
                   2924:     my $hostname = &hostname($chome);
                   2925:     my $protocol = $protocol{$chome};
                   2926:     $protocol = 'http' if ($protocol ne 'https');
                   2927:     my %domdefaults = &get_domain_defaults($cdom);
                   2928:     my $firsturl;
                   2929:     if ($domdefaults{'portal_def'}) {
                   2930:         $firsturl = $domdefaults{'portal_def'};
                   2931:     } else {
1.1451    raeburn  2932:         my $alias = &Apache::lonnet::use_proxy_alias($r,$chome);
                   2933:         $hostname = $alias if ($alias ne '');
1.1311    raeburn  2934:         $firsturl = $protocol.'://'.$hostname;
                   2935:     }
                   2936:     return $firsturl;
                   2937: }
                   2938: 
1.1407    raeburn  2939: # --------------------------------------------- Get domain config for passwords
                   2940: 
                   2941: sub get_passwdconf {
                   2942:     my ($dom) = @_;
                   2943:     my (%passwdconf,$gotconf,$lookup);
                   2944:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
                   2945:     if (defined($cached)) {
                   2946:         if (ref($result) eq 'HASH') {
                   2947:             %passwdconf = %{$result};
                   2948:             $gotconf = 1;
                   2949:         }
                   2950:     }
                   2951:     unless ($gotconf) {
                   2952:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
                   2953:         if (ref($domconfig{'passwords'}) eq 'HASH') {
                   2954:             %passwdconf = %{$domconfig{'passwords'}};
                   2955:         }
                   2956:         my $cachetime = 24*60*60;
                   2957:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
                   2958:     }
                   2959:     return %passwdconf;
                   2960: }
                   2961: 
1.344     www      2962: # --------------------------------------------------- Assign a key to a student
                   2963: 
                   2964: sub assign_access_key {
1.364     www      2965: #
                   2966: # a valid key looks like uname:udom#comments
                   2967: # comments are being appended
                   2968: #
1.498     www      2969:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2970:     $kdom=
1.620     albertel 2971:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2972:     $knum=
1.620     albertel 2973:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2974:     $cdom=
1.620     albertel 2975:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2976:     $cnum=
1.620     albertel 2977:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2978:     $udom=$env{'user.name'} unless (defined($udom));
                   2979:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2980:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2981:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2982:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2983:                                                   # assigned to this person
                   2984:                                                   # - this should not happen,
1.345     www      2985:                                                   # unless something went wrong
                   2986:                                                   # the first time around
                   2987: # ready to assign
1.364     www      2988:         $logentry=$1.'; '.$logentry;
1.496     www      2989:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2990:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2991: # key now belongs to user
1.346     www      2992: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2993:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2994:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2995:                 return 'ok';
                   2996:             } else {
                   2997:                 return 
                   2998:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2999: 	    }
                   3000:         } else {
                   3001:             return 'error: Could not assign key, try again later.';
                   3002:         }
1.364     www      3003:     } elsif (!$existing{$ckey}) {
1.345     www      3004: # the key does not exist
                   3005: 	return 'error: The key does not exist';
                   3006:     } else {
                   3007: # the key is somebody else's
                   3008: 	return 'error: The key is already in use';
                   3009:     }
1.344     www      3010: }
                   3011: 
1.364     www      3012: # ------------------------------------------ put an additional comment on a key
                   3013: 
                   3014: sub comment_access_key {
                   3015: #
                   3016: # a valid key looks like uname:udom#comments
                   3017: # comments are being appended
                   3018: #
                   3019:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   3020:     $cdom=
1.620     albertel 3021:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      3022:     $cnum=
1.620     albertel 3023:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      3024:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   3025:     if ($existing{$ckey}) {
                   3026:         $existing{$ckey}.='; '.$logentry;
                   3027: # ready to assign
1.367     www      3028:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      3029:                                                  $cdom,$cnum) eq 'ok') {
                   3030: 	    return 'ok';
                   3031:         } else {
                   3032: 	    return 'error: Count not store comment.';
                   3033:         }
                   3034:     } else {
                   3035: # the key does not exist
                   3036: 	return 'error: The key does not exist';
                   3037:     }
                   3038: }
                   3039: 
1.344     www      3040: # ------------------------------------------------------ Generate a set of keys
                   3041: 
                   3042: sub generate_access_keys {
1.364     www      3043:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      3044:     $cdom=
1.620     albertel 3045:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      3046:     $cnum=
1.620     albertel 3047:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      3048:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      3049:     unless (($cdom) && ($cnum)) { return 0; }
                   3050:     if ($number>10000) { return 0; }
                   3051:     sleep(2); # make sure don't get same seed twice
                   3052:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   3053:     my $total=0;
                   3054:     for (my $i=1;$i<=$number;$i++) {
                   3055:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   3056:                   sprintf("%lx",int(100000*rand)).'-'.
                   3057:                   sprintf("%lx",int(100000*rand));
                   3058:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   3059:        $newkey=~s/0/h/g; # and also 0 and O
                   3060:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   3061:        if ($existing{$newkey}) {
                   3062:            $i--;
                   3063:        } else {
1.364     www      3064: 	  if (&put('accesskeys',
                   3065:               { $newkey => '# generated '.localtime().
1.620     albertel 3066:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      3067:                            '; '.$logentry },
                   3068: 		   $cdom,$cnum) eq 'ok') {
1.344     www      3069:               $total++;
                   3070: 	  }
                   3071:        }
                   3072:     }
1.620     albertel 3073:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      3074:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   3075:     return $total;
                   3076: }
                   3077: 
                   3078: # ------------------------------------------------------- Validate an accesskey
                   3079: 
                   3080: sub validate_access_key {
                   3081:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   3082:     $cdom=
1.620     albertel 3083:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      3084:     $cnum=
1.620     albertel 3085:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   3086:     $udom=$env{'user.domain'} unless (defined($udom));
                   3087:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      3088:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 3089:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      3090: }
                   3091: 
                   3092: # ------------------------------------- Find the section of student in a course
1.652     albertel 3093: sub devalidate_getsection_cache {
                   3094:     my ($udom,$unam,$courseid)=@_;
                   3095:     my $hashid="$udom:$unam:$courseid";
                   3096:     &devalidate_cache_new('getsection',$hashid);
                   3097: }
1.298     matthew  3098: 
1.815     albertel 3099: sub courseid_to_courseurl {
                   3100:     my ($courseid) = @_;
                   3101:     #already url style courseid
                   3102:     return $courseid if ($courseid =~ m{^/});
                   3103: 
                   3104:     if (exists($env{'course.'.$courseid.'.num'})) {
                   3105: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   3106: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   3107: 	return "/$cdom/$cnum";
                   3108:     }
                   3109: 
                   3110:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   3111:     if (exists($courseinfo{'num'})) {
                   3112: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   3113:     }
                   3114: 
                   3115:     return undef;
                   3116: }
                   3117: 
1.298     matthew  3118: sub getsection {
                   3119:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 3120:     my $cachetime=1800;
1.551     albertel 3121: 
                   3122:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 3123:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 3124:     if (defined($cached)) { return $result; }
                   3125: 
1.298     matthew  3126:     my %Pending; 
                   3127:     my %Expired;
                   3128:     #
                   3129:     # Each role can either have not started yet (pending), be active, 
                   3130:     #    or have expired.
                   3131:     #
                   3132:     # If there is an active role, we are done.
                   3133:     #
                   3134:     # If there is more than one role which has not started yet, 
                   3135:     #     choose the one which will start sooner
                   3136:     # If there is one role which has not started yet, return it.
                   3137:     #
                   3138:     # If there is more than one expired role, choose the one which ended last.
                   3139:     # If there is a role which has expired, return it.
                   3140:     #
1.815     albertel 3141:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  3142:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  3143:     foreach my $key (keys(%roleshash)) {
1.479     albertel 3144:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  3145:         my $section=$1;
                   3146:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  3147:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  3148:         my $now=time;
1.548     albertel 3149:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  3150:             $Expired{$end}=$section;
                   3151:             next;
                   3152:         }
1.548     albertel 3153:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  3154:             $Pending{$start}=$section;
                   3155:             next;
                   3156:         }
1.599     albertel 3157:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  3158:     }
                   3159:     #
                   3160:     # Presumedly there will be few matching roles from the above
                   3161:     # loop and the sorting time will be negligible.
                   3162:     if (scalar(keys(%Pending))) {
                   3163:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 3164:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  3165:     } 
                   3166:     if (scalar(keys(%Expired))) {
                   3167:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   3168:         my $time = pop(@sorted);
1.599     albertel 3169:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  3170:     }
1.599     albertel 3171:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  3172: }
1.70      www      3173: 
1.599     albertel 3174: sub save_cache {
                   3175:     &purge_remembered();
1.722     albertel 3176:     #&Apache::loncommon::validate_page();
1.620     albertel 3177:     undef(%env);
1.780     albertel 3178:     undef($env_loaded);
1.599     albertel 3179: }
1.452     albertel 3180: 
1.599     albertel 3181: my $to_remember=-1;
                   3182: my %remembered;
                   3183: my %accessed;
                   3184: my $kicks=0;
                   3185: my $hits=0;
1.849     albertel 3186: sub make_key {
                   3187:     my ($name,$id) = @_;
1.872     albertel 3188:     if (length($id) > 65 
                   3189: 	&& length(&escape($id)) > 200) {
                   3190: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   3191:     }
1.849     albertel 3192:     return &escape($name.':'.$id);
                   3193: }
                   3194: 
1.599     albertel 3195: sub devalidate_cache_new {
                   3196:     my ($name,$id,$debug) = @_;
                   3197:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  3198:     my $remembered_id=$name.':'.$id;
1.849     albertel 3199:     $id=&make_key($name,$id);
1.599     albertel 3200:     $memcache->delete($id);
1.1319    damieng  3201:     delete($remembered{$remembered_id});
                   3202:     delete($accessed{$remembered_id});
1.599     albertel 3203: }
                   3204: 
                   3205: sub is_cached_new {
                   3206:     my ($name,$id,$debug) = @_;
1.1319    damieng  3207:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   3208:     if (exists($remembered{$remembered_id})) {
                   3209: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   3210: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3211: 	$hits++;
1.1319    damieng  3212: 	return ($remembered{$remembered_id},1);
1.599     albertel 3213:     }
1.1319    damieng  3214:     $id=&make_key($name,$id);
1.599     albertel 3215:     my $value = $memcache->get($id);
                   3216:     if (!(defined($value))) {
                   3217: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 3218: 	return (undef,undef);
1.416     albertel 3219:     }
1.599     albertel 3220:     if ($value eq '__undef__') {
                   3221: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   3222: 	$value=undef;
                   3223:     }
1.1319    damieng  3224:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3225:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   3226:     return ($value,1);
                   3227: }
                   3228: 
                   3229: sub do_cache_new {
                   3230:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  3231:     my $remembered_id=$name.':'.$id;
1.849     albertel 3232:     $id=&make_key($name,$id);
1.599     albertel 3233:     my $setvalue=$value;
                   3234:     if (!defined($setvalue)) {
                   3235: 	$setvalue='__undef__';
                   3236:     }
1.623     albertel 3237:     if (!defined($time) ) {
                   3238: 	$time=600;
                   3239:     }
1.599     albertel 3240:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 3241:     my $result = $memcache->set($id,$setvalue,$time);
                   3242:     if (! $result) {
1.872     albertel 3243: 	&logthis("caching of id -> $id  failed");
1.910     albertel 3244: 	$memcache->disconnect_all();
1.872     albertel 3245:     }
1.600     albertel 3246:     # need to make a copy of $value
1.1319    damieng  3247:     &make_room($remembered_id,$value,$debug);
1.599     albertel 3248:     return $value;
                   3249: }
                   3250: 
                   3251: sub make_room {
1.1319    damieng  3252:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 3253: 
1.1319    damieng  3254:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 3255:                                     : $value;
1.599     albertel 3256:     if ($to_remember<0) { return; }
1.1319    damieng  3257:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 3258:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   3259:     my $to_kick;
                   3260:     my $max_time=0;
                   3261:     foreach my $other (keys(%accessed)) {
                   3262: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   3263: 	    $to_kick=$other;
                   3264: 	    $max_time=&tv_interval($accessed{$other});
                   3265: 	}
                   3266:     }
                   3267:     delete($remembered{$to_kick});
                   3268:     delete($accessed{$to_kick});
                   3269:     $kicks++;
                   3270:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 3271:     return;
                   3272: }
                   3273: 
1.599     albertel 3274: sub purge_remembered {
1.604     albertel 3275:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   3276:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 3277:     undef(%remembered);
                   3278:     undef(%accessed);
1.428     albertel 3279: }
1.70      www      3280: # ------------------------------------- Read an entry from a user's environment
                   3281: 
                   3282: sub userenvironment {
                   3283:     my ($udom,$unam,@what)=@_;
1.976     raeburn  3284:     my $items;
                   3285:     foreach my $item (@what) {
                   3286:         $items.=&escape($item).'&';
                   3287:     }
                   3288:     $items=~s/\&$//;
1.70      www      3289:     my %returnhash=();
1.1009    raeburn  3290:     my $uhome = &homeserver($unam,$udom);
                   3291:     unless ($uhome eq 'no_host') {
                   3292:         my @answer=split(/\&/, 
                   3293:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  3294:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   3295:             return %returnhash;
                   3296:         }
1.1009    raeburn  3297:         my $i;
                   3298:         for ($i=0;$i<=$#what;$i++) {
                   3299: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   3300:         }
1.70      www      3301:     }
                   3302:     return %returnhash;
1.1       albertel 3303: }
                   3304: 
1.617     albertel 3305: # ---------------------------------------------------------- Get a studentphoto
                   3306: sub studentphoto {
                   3307:     my ($udom,$unam,$ext) = @_;
                   3308:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  3309:     if (defined($env{'request.course.id'})) {
1.708     raeburn  3310:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  3311:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   3312:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   3313:             } else {
                   3314:                 my ($result,$perm_reqd)=
1.707     albertel 3315: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3316:                 if ($result eq 'ok') {
                   3317:                     if (!($perm_reqd eq 'yes')) {
                   3318:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   3319:                     }
                   3320:                 }
                   3321:             }
                   3322:         }
                   3323:     } else {
                   3324:         my ($result,$perm_reqd) = 
1.707     albertel 3325: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  3326:         if ($result eq 'ok') {
                   3327:             if (!($perm_reqd eq 'yes')) {
                   3328:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   3329:             }
                   3330:         }
                   3331:     }
                   3332:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   3333: }
                   3334: 
                   3335: sub retrievestudentphoto {
                   3336:     my ($udom,$unam,$ext,$type) = @_;
                   3337:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   3338:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   3339:     if ($ret eq 'ok') {
                   3340:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   3341:         if ($type eq 'thumbnail') {
                   3342:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   3343:         }
                   3344:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   3345:         return $tokenurl;
                   3346:     } else {
                   3347:         if ($type eq 'thumbnail') {
                   3348:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   3349:         } else { 
                   3350:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   3351:         }
1.617     albertel 3352:     }
                   3353: }
                   3354: 
1.263     www      3355: # -------------------------------------------------------------------- New chat
                   3356: 
                   3357: sub chatsend {
1.724     raeburn  3358:     my ($newentry,$anon,$group)=@_;
1.620     albertel 3359:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3360:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3361:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      3362:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 3363: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  3364: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      3365: }
                   3366: 
                   3367: # ------------------------------------------ Find current version of a resource
                   3368: 
                   3369: sub getversion {
                   3370:     my $fname=&clutter(shift);
1.1189    raeburn  3371:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      3372:     return &currentversion(&filelocation('',$fname));
                   3373: }
                   3374: 
                   3375: sub currentversion {
                   3376:     my $fname=shift;
                   3377:     my $author=$fname;
                   3378:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3379:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3380:     my $home=&homeserver($uname,$udom);
1.292     www      3381:     if ($home eq 'no_host') { 
                   3382:         return -1; 
                   3383:     }
1.1112    www      3384:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3385:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3386: 	return -1;
                   3387:     }
1.1112    www      3388:     return $answer;
1.263     www      3389: }
                   3390: 
1.1111    www      3391: #
                   3392: # Return special version number of resource if set by override, empty otherwise
                   3393: #
                   3394: sub usedversion {
                   3395:     my $fname=shift;
                   3396:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3397:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3398:     if ($urlversion) { return $urlversion; }
                   3399:     return '';
                   3400: }
                   3401: 
1.1       albertel 3402: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3403: 
1.1       albertel 3404: sub subscribe {
                   3405:     my $fname=shift;
1.761     raeburn  3406:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3407:     $fname=~s/[\n\r]//g;
1.1       albertel 3408:     my $author=$fname;
                   3409:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3410:     my ($udom,$uname)=split(/\//,$author);
                   3411:     my $home=homeserver($uname,$udom);
1.335     albertel 3412:     if ($home eq 'no_host') {
                   3413:         return 'not_found';
1.1       albertel 3414:     }
                   3415:     my $answer=reply("sub:$fname",$home);
1.64      www      3416:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3417: 	$answer.=' by '.$home;
                   3418:     }
1.1       albertel 3419:     return $answer;
                   3420: }
                   3421:     
1.8       www      3422: # -------------------------------------------------------------- Replicate file
                   3423: 
                   3424: sub repcopy {
                   3425:     my $filename=shift;
1.23      www      3426:     $filename=~s/\/+/\//g;
1.1142    raeburn  3427:     my $londocroot = $perlvar{'lonDocRoot'};
                   3428:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3429:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3430:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3431: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3432: 	return &repcopy_userfile($filename);
                   3433:     }
1.532     albertel 3434:     $filename=~s/[\n\r]//g;
1.8       www      3435:     my $transname="$filename.in.transfer";
1.828     www      3436: # FIXME: this should flock
1.607     raeburn  3437:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3438:     my $remoteurl=subscribe($filename);
1.64      www      3439:     if ($remoteurl =~ /^con_lost by/) {
                   3440: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3441:            return 'unavailable';
1.8       www      3442:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3443: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3444: 	   return 'not_found';
1.64      www      3445:     } elsif ($remoteurl =~ /^rejected by/) {
                   3446: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3447:            return 'forbidden';
1.20      www      3448:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3449:            return 'ok';
1.8       www      3450:     } else {
1.290     www      3451:         my $author=$filename;
                   3452:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3453:         my ($udom,$uname)=split(/\//,$author);
                   3454:         my $home=homeserver($uname,$udom);
                   3455:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3456:            my @parts=split(/\//,$filename);
                   3457:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3458:            if ($path ne "$londocroot/res") {
1.8       www      3459:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3460: 	       return 'bad_request';
1.8       www      3461:            }
                   3462:            my $count;
                   3463:            for ($count=5;$count<$#parts;$count++) {
                   3464:                $path.="/$parts[$count]";
                   3465:                if ((-e $path)!=1) {
                   3466: 		   mkdir($path,0777);
                   3467:                }
                   3468:            }
                   3469:            my $request=new HTTP::Request('GET',"$remoteurl");
1.1345    raeburn  3470:            my $response;
                   3471:            if ($remoteurl =~ m{/raw/}) {
                   3472:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
                   3473:            } else {
                   3474:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
                   3475:            }
1.8       www      3476:            if ($response->is_error()) {
                   3477: 	       unlink($transname);
                   3478:                my $message=$response->status_line;
1.672     albertel 3479:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3480:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3481:                return 'unavailable';
1.8       www      3482:            } else {
1.16      www      3483: 	       if ($remoteurl!~/\.meta$/) {
                   3484:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345    raeburn  3485:                   my $mresponse;
                   3486:                   if ($remoteurl =~ m{/raw/}) {
                   3487:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
                   3488:                   } else {
                   3489:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
                   3490:                   }
1.16      www      3491:                   if ($mresponse->is_error()) {
                   3492: 		      unlink($filename.'.meta');
                   3493:                       &logthis(
1.672     albertel 3494:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3495:                   }
                   3496: 	       }
1.8       www      3497:                rename($transname,$filename);
1.607     raeburn  3498:                return 'ok';
1.8       www      3499:            }
1.290     www      3500:        }
1.8       www      3501:     }
1.330     www      3502: }
                   3503: 
1.1422    raeburn  3504: # ------------------------------------------------- Unsubscribe from a resource
                   3505: 
                   3506: sub unsubscribe {
                   3507:     my ($fname) = @_;
                   3508:     my $answer;
                   3509:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
                   3510:     $fname=~s/[\n\r]//g;
                   3511:     my $author=$fname;
                   3512:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3513:     my ($udom,$uname)=split(/\//,$author);
                   3514:     my $home=homeserver($uname,$udom);
                   3515:     if ($home eq 'no_host') {
                   3516:         $answer = 'no_host';
                   3517:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
                   3518:         $answer = 'home';
                   3519:     } else {
                   3520:         my $defdom = $perlvar{'lonDefDomain'};
                   3521:         if (&will_trust('content',$defdom,$udom)) {
                   3522:             $answer = reply("unsub:$fname",$home);
                   3523:         } else {
                   3524:             $answer = 'untrusted';
                   3525:         }
                   3526:     }
                   3527:     return $answer;
                   3528: }
                   3529: 
1.330     www      3530: # ------------------------------------------------ Get server side include body
                   3531: sub ssi_body {
1.381     albertel 3532:     my ($filelink,%form)=@_;
1.606     matthew  3533:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3534:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3535:     }
1.953     www      3536:     my $output='';
                   3537:     my $response;
1.980     raeburn  3538:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3539:        ($output,$response)=&externalssi($filelink);
1.953     www      3540:     } else {
1.1004    droeschl 3541:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3542:        $filelink .= 'inhibitmenu=yes';
1.953     www      3543:        ($output,$response)=&ssi($filelink,%form);
                   3544:     }
1.778     albertel 3545:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3546:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3547:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3548:     if (wantarray) {
                   3549:         return ($output, $response);
                   3550:     } else {
                   3551:         return $output;
                   3552:     }
1.8       www      3553: }
                   3554: 
1.15      www      3555: # --------------------------------------------------------- Server Side Include
                   3556: 
1.782     albertel 3557: sub absolute_url {
1.1447    raeburn  3558:     my ($host_name,$unalias,$keep_proto) = @_;
1.782     albertel 3559:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3560:     if ($host_name eq '') {
                   3561: 	$host_name = $ENV{'SERVER_NAME'};
                   3562:     }
1.1447    raeburn  3563:     if ($unalias) {
                   3564:         my $alias = &get_proxy_alias();
                   3565:         if ($alias eq $host_name) {
                   3566:             my $lonhost = $perlvar{'lonHostID'};
                   3567:             my $hostname = &hostname($lonhost);
                   3568:             my $lcproto; 
                   3569:             if (($keep_proto) || ($hostname eq '')) {
                   3570:                 $lcproto = $protocol;
                   3571:             } else {
                   3572:                 $lcproto = $protocol{$lonhost};
                   3573:                 $lcproto = 'http' if ($lcproto ne 'https');
                   3574:                 $lcproto .= '://';
                   3575:             }
                   3576:             unless ($hostname eq '') {
                   3577:                 return $lcproto.$hostname;
                   3578:             }
                   3579:         }
                   3580:     }
1.782     albertel 3581:     return $protocol.$host_name;
                   3582: }
                   3583: 
1.942     foxr     3584: #
                   3585: #   Server side include.
                   3586: # Parameters:
                   3587: #  fn     Possibly encrypted resource name/id.
                   3588: #  form   Hash that describes how the rendering should be done
                   3589: #         and other things.
1.944     foxr     3590: # Returns:
1.950     raeburn  3591: #   Scalar context: The content of the response.
                   3592: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3593: #     
1.15      www      3594: sub ssi {
                   3595: 
1.944     foxr     3596:     my ($fn,%form)=@_;
1.1447    raeburn  3597:     my ($host,$request,$response);
                   3598:     $host = &absolute_url('',1);
1.711     albertel 3599: 
                   3600:     $form{'no_update_last_known'}=1;
1.895     albertel 3601:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3602:     if (%form) {
1.1447    raeburn  3603:       $request=new HTTP::Request('POST',$host.$fn);
1.1272    droeschl 3604:       $request->content(join('&',map { 
                   3605:             my $name = escape($_);
                   3606:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3607:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3608:             : &escape($form{$_}) );    
                   3609:         } keys(%form)));
1.23      www      3610:     } else {
1.1447    raeburn  3611:       $request=new HTTP::Request('GET',$host.$fn);
1.23      www      3612:     }
                   3613: 
1.15      www      3614:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345    raeburn  3615:     my $lonhost = $perlvar{'lonHostID'};
1.1385    raeburn  3616:     my $islocal;
                   3617:     if (($env{'request.course.id'}) &&
                   3618:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
                   3619:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
                   3620:         ($form{'grade_symb'} ne '') &&
                   3621:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
                   3622:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
                   3623:         $islocal = 1;
                   3624:     }
1.1447    raeburn  3625:     $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,
                   3626:                                              '','','',$islocal);
1.1182    foxr     3627: 
1.944     foxr     3628:     if (wantarray) {
1.1345    raeburn  3629: 	return ($response->content, $response);
1.944     foxr     3630:     } else {
1.1345    raeburn  3631: 	return $response->content;
1.942     foxr     3632:     }
1.324     www      3633: }
                   3634: 
                   3635: sub externalssi {
                   3636:     my ($url)=@_;
                   3637:     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn  3638:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954     raeburn  3639:     if (wantarray) {
                   3640:         return ($response->content, $response);
                   3641:     } else {
                   3642:         return $response->content;
                   3643:     }
1.15      www      3644: }
1.254     www      3645: 
1.1354    raeburn  3646: 
                   3647: # If the local copy of a replicated resource is outdated, trigger a  
                   3648: # connection from the homeserver to flush the delayed queue. If no update 
                   3649: # happens, remove local copies of outdated resource (and corresponding
                   3650: # metadata file).
                   3651: 
1.1352    raeburn  3652: sub remove_stale_resfile {
                   3653:     my ($url) = @_;
1.1354    raeburn  3654:     my $removed;
1.1352    raeburn  3655:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3656:         my $audom = $1;
                   3657:         my $auname = $2;
1.1353    raeburn  3658:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352    raeburn  3659:             my $homeserver = &homeserver($auname,$audom);
                   3660:             unless (($homeserver eq 'no_host') ||
                   3661:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3662:                 my $fname = &filelocation('',$url);
                   3663:                 if (-e $fname) {
                   3664:                     my $hostname = &hostname($homeserver);
                   3665:                     if ($hostname) {
1.1397    raeburn  3666:                         my $protocol = $protocol{$homeserver};
                   3667:                         $protocol = 'http' if ($protocol ne 'https');
1.1352    raeburn  3668:                         my $uri = &declutter($url);
                   3669:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
                   3670:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
                   3671:                         if ($response->is_success()) {
                   3672:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3673:                             my $locmodtime = (stat($fname))[9];
                   3674:                             if ($locmodtime < $remmodtime) {
1.1354    raeburn  3675:                                 my $stale;
                   3676:                                 my $answer = &reply('pong',$homeserver);
                   3677:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3678:                                     sleep(0.2);
                   3679:                                     $locmodtime = (stat($fname))[9];
                   3680:                                     if ($locmodtime < $remmodtime) {
                   3681:                                         my $posstransfer = $fname.'.in.transfer';
                   3682:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3683:                                             $removed = 1;
                   3684:                                         } else {
                   3685:                                             $stale = 1;
                   3686:                                         }
                   3687:                                     } else {
                   3688:                                         $removed = 1;
                   3689:                                     }
                   3690:                                 } else {
                   3691:                                     $stale = 1;
                   3692:                                 }
                   3693:                                 if ($stale) {
1.1421    raeburn  3694:                                     if (unlink($fname)) {
                   3695:                                         if ($uri!~/\.meta$/) {
                   3696:                                             if (-e $fname.'.meta') {
                   3697:                                                 unlink($fname.'.meta');
                   3698:                                             }
                   3699:                                         }
1.1422    raeburn  3700:                                         my $unsubresult = &unsubscribe($fname);
                   3701:                                         unless ($unsubresult eq 'ok') {
                   3702:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
                   3703:                                         }
1.1421    raeburn  3704:                                         $removed = 1;
1.1354    raeburn  3705:                                     }
1.1352    raeburn  3706:                                 }
                   3707:                             }
                   3708:                         }
                   3709:                     }
                   3710:                 }
                   3711:             }
                   3712:         }
                   3713:     }
1.1354    raeburn  3714:     return $removed;
1.1352    raeburn  3715: }
                   3716: 
1.492     albertel 3717: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3718: 
                   3719: sub allowuploaded {
                   3720:     my ($srcurl,$url)=@_;
                   3721:     $url=&clutter(&declutter($url));
                   3722:     my $dir=$url;
                   3723:     $dir=~s/\/[^\/]+$//;
                   3724:     my %httpref=();
                   3725:     my $httpurl=&hreflocation('',$url);
                   3726:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3727:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3728: }
1.477     raeburn  3729: 
1.1193    raeburn  3730: #
                   3731: # Determine if the current user should be able to edit a particular resource,
                   3732: # when viewing in course context.
                   3733: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3734: #     Functions.
                   3735: # (b) When displaying folder contents in course editor, used to determine if
                   3736: #     "Edit" link will be displayed alongside resource.
                   3737: #
1.1196    raeburn  3738: #  input: six args -- filename (decluttered), course number, course domain,
                   3739: #                   url, symb (if registered) and group (if this is a group
                   3740: #                   item -- e.g., bulletin board, group page etc.).
                   3741: #  output: array of five scalars -- 
1.1193    raeburn  3742: #          $cfile -- url for file editing if editable on current server
                   3743: #          $home -- homeserver of resource (i.e., for author if published,
                   3744: #                                           or course if uploaded.).
                   3745: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3746: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3747: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3748: #
                   3749: 
                   3750: sub can_edit_resource {
1.1194    raeburn  3751:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3752:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3753: #
                   3754: # For aboutme pages user can only edit his/her own.
                   3755: #
1.1199    raeburn  3756:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3757:         my ($sdom,$sname) = ($1,$2);
                   3758:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3759:             $home = $env{'user.home'};
                   3760:             $cfile = $resurl;
                   3761:             if ($env{'form.forceedit'}) {
                   3762:                 $forceview = 1;
                   3763:             } else {
                   3764:                 $forceedit = 1;
                   3765:             }
                   3766:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3767:         } else {
                   3768:             return;
                   3769:         }
                   3770:     }
                   3771: 
                   3772:     if ($env{'request.course.id'}) {
                   3773:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3774:         if ($group ne '') {
                   3775: # if this is a group homepage or group bulletin board, check group privs
                   3776:             my $allowed = 0;
1.1197    raeburn  3777:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3778:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3779:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3780:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3781:                     $allowed = 1;
                   3782:                 }
1.1197    raeburn  3783:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3784:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3785:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3786:                     $allowed = 1;
                   3787:                 }
                   3788:             }
                   3789:             if ($allowed) {
                   3790:                 $home=&homeserver($cnum,$cdom);
                   3791:                 if ($env{'form.forceedit'}) {
                   3792:                     $forceview = 1;
                   3793:                 } else {
                   3794:                     $forceedit = 1;
                   3795:                 }
                   3796:                 $cfile = $resurl;
                   3797:             } else {
                   3798:                 return;
                   3799:             }
                   3800:         } else {
1.1208    raeburn  3801:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3802:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3803:                     return;
                   3804:                 }
                   3805:             } elsif (!$crsedit) {
1.1194    raeburn  3806: #
                   3807: # No edit allowed where CC has switched to student role.
                   3808: #
                   3809:                 return;
                   3810:             }
                   3811:         }
                   3812:     }
                   3813: 
1.1193    raeburn  3814:     if ($file ne '') {
                   3815:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3816:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3817:                 $uploaded = 1;
                   3818:                 $incourse = 1;
1.1193    raeburn  3819:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3820:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3821:                     if ($env{'form.forceedit'}) {
                   3822:                         $forceview = 1;
                   3823:                     } else {
                   3824:                         $forceedit = 1;
                   3825:                     }
1.1194    raeburn  3826:                 }
                   3827:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3828:                 $incourse = 1;
                   3829:                 if ($env{'form.forceedit'}) {
                   3830:                     $forceview = 1;
                   3831:                 } else {
                   3832:                     $forceedit = 1;
                   3833:                 }
                   3834:                 $cfile = $resurl;
                   3835:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3836:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3837:                     $incourse = 1;
                   3838:                     if ($env{'form.forceedit'}) {
                   3839:                         $forceview = 1;
                   3840:                     } else {
                   3841:                         $forceedit = 1;
                   3842:                     }
                   3843:                     $cfile = $resurl;
1.1199    raeburn  3844:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3845:                     $incourse = 1;
                   3846:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3847:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3848:                     $incourse = 1;
1.1199    raeburn  3849:                     if ($env{'form.forceedit'}) {
                   3850:                         $forceview = 1;
                   3851:                     } else {
                   3852:                         $forceedit = 1;
                   3853:                     }
                   3854:                     $cfile = $resurl;
1.1419    raeburn  3855:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
                   3856:                     my ($map,$id,$res) = &decode_symb($symb);
                   3857:                     if ($map =~ /\.page$/) {
                   3858:                         $incourse = 1;
                   3859:                         if ($env{'form.forceedit'}) {
                   3860:                             $forceview = 1;
                   3861:                             $cfile = $map;
                   3862:                         } else {
                   3863:                             $forceedit = 1;
                   3864:                             $cfile =  '/adm/wrapper'.$resurl;
                   3865:                         }
                   3866:                     }
1.1343    raeburn  3867:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3868:                     $incourse = 1;
                   3869:                     if ($env{'form.forceedit'}) {
                   3870:                         $forceview = 1;
                   3871:                     } else {
                   3872:                         $forceedit = 1;
                   3873:                     }
                   3874:                     $cfile = $resurl;
1.1208    raeburn  3875:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3876:                     $incourse = 1;
                   3877:                     if ($env{'form.forceedit'}) {
                   3878:                         $forceview = 1;
                   3879:                     } else {
                   3880:                         $forceedit = 1;
                   3881:                     }
                   3882:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3883:                 }
                   3884:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3885:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3886:                 if (&is_on_map($template)) { 
                   3887:                     $incourse = 1;
                   3888:                     $forceview = 1;
                   3889:                     $cfile = $template;
1.1193    raeburn  3890:                 }
1.1199    raeburn  3891:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1418    raeburn  3892:                 $incourse = 1;
                   3893:                 if ($env{'form.forceedit'}) {
                   3894:                     $forceview = 1;
                   3895:                 } else {
                   3896:                     $forceedit = 1;
                   3897:                 }
                   3898:                 $cfile = $resurl;
1.1343    raeburn  3899:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298    raeburn  3900:                 $incourse = 1;
                   3901:                 if ($env{'form.forceedit'}) {
                   3902:                     $forceview = 1;
                   3903:                 } else {
                   3904:                     $forceedit = 1;
                   3905:                 }
                   3906:                 $cfile = $resurl;
1.1199    raeburn  3907:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3908:                 $incourse = 1;
                   3909:                 $forceview = 1;
                   3910:                 if ($symb) {
                   3911:                     my ($map,$id,$res)=&decode_symb($symb);
                   3912:                     $env{'request.symb'} = $symb;
                   3913:                     $cfile = &clutter($res);
                   3914:                 } else {
                   3915:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3916:                     my $escfile = &unescape($cfile);
1.1343    raeburn  3917:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3918:                         $cfile = '/adm/wrapper'.$escfile;
                   3919:                     } else {
                   3920:                         $escfile =~ s{^http://}{};
                   3921:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3922:                     }
1.1199    raeburn  3923:                 }
1.1234    raeburn  3924:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3925:                 if ($env{'form.forceedit'}) {
                   3926:                     $forceview = 1;
                   3927:                 } else {
                   3928:                     $forceedit = 1;
                   3929:                 }
                   3930:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3931:             }
                   3932:         }
1.1194    raeburn  3933:         if ($uploaded || $incourse) {
                   3934:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3935:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3936:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3937:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3938:             # Check that the user has permission to edit this resource
                   3939:             my $setpriv = 1;
                   3940:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3941:             if (defined($cfudom)) {
                   3942:                 $home=&homeserver($cfuname,$cfudom);
                   3943:                 $cfile=$file;
                   3944:             }
                   3945:         }
1.1194    raeburn  3946:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3947:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3948:             my @ids=&current_machine_ids();
                   3949:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3950:                 $switchserver=1;
                   3951:             }
                   3952:         }
                   3953:     }
1.1194    raeburn  3954:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3955: }
                   3956: 
                   3957: sub is_course_upload {
                   3958:     my ($file,$cnum,$cdom) = @_;
                   3959:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3960:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3961:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3962:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3963:         return 1;
                   3964:     }
                   3965:     return;
                   3966: }
                   3967: 
1.1194    raeburn  3968: sub in_course {
1.1195    raeburn  3969:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3970:     if ($hideprivileged) {
                   3971:         my $skipuser;
1.1219    raeburn  3972:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3973:         my @possdoms = ($cdom);  
                   3974:         if ($coursehash{'checkforpriv'}) { 
                   3975:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3976:         }
                   3977:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3978:             $skipuser = 1;
                   3979:             if ($coursehash{'nothideprivileged'}) {
                   3980:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3981:                     my $user;
                   3982:                     if ($item =~ /:/) {
                   3983:                         $user = $item;
                   3984:                     } else {
                   3985:                         $user = join(':',split(/[\@]/,$item));
                   3986:                     }
                   3987:                     if ($user eq $uname.':'.$udom) {
                   3988:                         undef($skipuser);
                   3989:                         last;
                   3990:                     }
                   3991:                 }
                   3992:             }
                   3993:             if ($skipuser) {
                   3994:                 return 0;
                   3995:             }
                   3996:         }
                   3997:     }
1.1194    raeburn  3998:     $type ||= 'any';
                   3999:     if (!defined($cdom) || !defined($cnum)) {
                   4000:         my $cid  = $env{'request.course.id'};
                   4001:         $cdom = $env{'course.'.$cid.'.domain'};
                   4002:         $cnum = $env{'course.'.$cid.'.num'};
                   4003:     }
                   4004:     my $typesref;
1.1195    raeburn  4005:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  4006:         $typesref = ['active','previous','future'];
                   4007:     } elsif ($type eq 'previous' || $type eq 'future') {
                   4008:         $typesref = [$type];
                   4009:     }
                   4010:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   4011:                               $typesref,undef,[$cdom]);
                   4012:     my ($tmp) = keys(%roles);
                   4013:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   4014:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   4015:     if (@course_roles > 0) {
                   4016:         return 1;
                   4017:     }
                   4018:     return 0;
                   4019: }
                   4020: 
1.478     albertel 4021: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 4022: # input: action, courseID, current domain, intended
1.637     raeburn  4023: #        path to file, source of file, instruction to parse file for objects,
                   4024: #        ref to hash for embedded objects,
                   4025: #        ref to hash for codebase of java objects.
1.1095    raeburn  4026: #        reference to scalar to accommodate mime type determined
                   4027: #          from File::MMagic if $parser = parse.
1.637     raeburn  4028: #
1.485     raeburn  4029: # output: url to file (if action was uploaddoc), 
                   4030: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  4031: #
1.478     albertel 4032: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   4033: # course.
1.477     raeburn  4034: #
1.478     albertel 4035: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   4036: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   4037: #          course's home server.
1.477     raeburn  4038: #
1.478     albertel 4039: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   4040: #          be copied from $source (current location) to 
                   4041: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   4042: #         and will then be copied to
                   4043: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   4044: #         course's home server.
1.485     raeburn  4045: #
1.481     raeburn  4046: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 4047: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  4048: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   4049: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   4050: #         in course's home server.
1.637     raeburn  4051: #
1.477     raeburn  4052: 
                   4053: sub process_coursefile {
1.1095    raeburn  4054:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   4055:         $mimetype)=@_;
1.477     raeburn  4056:     my $fetchresult;
1.638     albertel 4057:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  4058:     if ($action eq 'propagate') {
1.638     albertel 4059:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   4060: 			     $home);
1.481     raeburn  4061:     } else {
1.477     raeburn  4062:         my $fpath = '';
                   4063:         my $fname = $file;
1.478     albertel 4064:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  4065:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  4066:         my $filepath = &build_filepath($fpath);
1.481     raeburn  4067:         if ($action eq 'copy') {
                   4068:             if ($source eq '') {
                   4069:                 $fetchresult = 'no source file';
                   4070:                 return $fetchresult;
                   4071:             } else {
                   4072:                 my $destination = $filepath.'/'.$fname;
                   4073:                 rename($source,$destination);
                   4074:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4075:                                  $home);
1.481     raeburn  4076:             }
                   4077:         } elsif ($action eq 'uploaddoc') {
1.1359    raeburn  4078:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 4079:             print $fh $env{'form.'.$source};
1.481     raeburn  4080:             close($fh);
1.637     raeburn  4081:             if ($parser eq 'parse') {
1.1024    raeburn  4082:                 my $mm = new File::MMagic;
1.1095    raeburn  4083:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   4084:                 if ($type eq 'text/html') {
1.1024    raeburn  4085:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   4086:                     unless ($parse_result eq 'ok') {
                   4087:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   4088:                     }
1.637     raeburn  4089:                 }
1.1095    raeburn  4090:                 if (ref($mimetype)) {
                   4091:                     $$mimetype = $type;
                   4092:                 } 
1.637     raeburn  4093:             }
1.477     raeburn  4094:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4095:                                  $home);
1.481     raeburn  4096:             if ($fetchresult eq 'ok') {
                   4097:                 return '/uploaded/'.$fpath.'/'.$fname;
                   4098:             } else {
                   4099:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 4100:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  4101:                 return '/adm/notfound.html';
                   4102:             }
1.477     raeburn  4103:         }
                   4104:     }
1.485     raeburn  4105:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  4106:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 4107:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  4108:     }
                   4109:     return $fetchresult;
                   4110: }
                   4111: 
1.637     raeburn  4112: sub build_filepath {
                   4113:     my ($fpath) = @_;
                   4114:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   4115:     unless ($fpath eq '') {
                   4116:         my @parts=split('/',$fpath);
                   4117:         foreach my $part (@parts) {
                   4118:             $filepath.= '/'.$part;
                   4119:             if ((-e $filepath)!=1) {
                   4120:                 mkdir($filepath,0777);
                   4121:             }
                   4122:         }
                   4123:     }
                   4124:     return $filepath;
                   4125: }
                   4126: 
                   4127: sub store_edited_file {
1.638     albertel 4128:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  4129:     my $file = $primary_url;
                   4130:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   4131:     my $fpath = '';
                   4132:     my $fname = $file;
                   4133:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   4134:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   4135:     my $filepath = &build_filepath($fpath);
1.1359    raeburn  4136:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  4137:     print $fh $content;
                   4138:     close($fh);
1.638     albertel 4139:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  4140:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 4141: 			  $home);
1.637     raeburn  4142:     if ($$fetchresult eq 'ok') {
                   4143:         return '/uploaded/'.$fpath.'/'.$fname;
                   4144:     } else {
1.638     albertel 4145:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   4146: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  4147:         return '/adm/notfound.html';
                   4148:     }
                   4149: }
                   4150: 
1.531     albertel 4151: sub clean_filename {
1.831     albertel 4152:     my ($fname,$args)=@_;
1.315     www      4153: # Replace Windows backslashes by forward slashes
1.257     www      4154:     $fname=~s/\\/\//g;
1.831     albertel 4155:     if (!$args->{'keep_path'}) {
                   4156:         # Get rid of everything but the actual filename
                   4157: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   4158:     }
1.315     www      4159: # Replace spaces by underscores
                   4160:     $fname=~s/\s+/\_/g;
1.1406    raeburn  4161: # Transliterate non-ascii text to ascii
                   4162:     my $lang = &Apache::lonlocal::current_language();
                   4163:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
1.315     www      4164: # Replace all other weird characters by nothing
1.831     albertel 4165:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 4166: # Replace all .\d. sequences with _\d. so they no longer look like version
                   4167: # numbers
                   4168:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.1443    raeburn  4169: # Replace three or more adjacent underscores with one for consistency 
                   4170: # with loncfile::filename_check() so complete url can be extracted by
                   4171: # lonnet::decode_symb()
                   4172:     $fname=~s/_{3,}/_/g;
1.531     albertel 4173:     return $fname;
                   4174: }
1.1406    raeburn  4175: 
1.1051    raeburn  4176: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   4177: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   4178: # image with the same aspect ratio as the original, but with dimensions which do 
                   4179: # not exceed $resizewidth and $resizeheight.
                   4180:  
1.984     neumanie 4181: sub resizeImage {
1.1051    raeburn  4182:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   4183:     my $ima = Image::Magick->new;
                   4184:     my $resized;
                   4185:     if (-e $img_path) {
                   4186:         $ima->Read($img_path);
                   4187:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   4188:             my $width = $ima->Get('width');
                   4189:             my $height = $ima->Get('height');
                   4190:             if ($width > $resizewidth) {
                   4191: 	        my $factor = $width/$resizewidth;
                   4192:                 my $newheight = $height/$factor;
                   4193:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   4194:                 $resized = 1;
                   4195:             }
                   4196:         }
                   4197:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   4198:             my $width = $ima->Get('width');
                   4199:             my $height = $ima->Get('height');
                   4200:             if ($height > $resizeheight) {
                   4201:                 my $factor = $height/$resizeheight;
                   4202:                 my $newwidth = $width/$factor;
                   4203:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   4204:                 $resized = 1;
                   4205:             }
                   4206:         }
                   4207:         if ($resized) {
                   4208:             $ima->Write($img_path);
                   4209:         }
                   4210:     }
                   4211:     return;
1.977     amueller 4212: }
                   4213: 
1.608     albertel 4214: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 4215: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  4216: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  4217: #        $context - possible values: coursedoc, existingfile, overwrite, 
1.1401    raeburn  4218: #                                    canceloverwrite, scantron or ''.
1.1090    raeburn  4219: #                   if 'coursedoc': upload to the current course
                   4220: #                   if 'existingfile': write file to tmp/overwrites directory 
                   4221: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   4222: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 4223: #        $subdir - directory in userfile to store the file into
1.1401    raeburn  4224: #        $parser - instruction to parse file for objects ($parser = parse) or
                   4225: #                  if context is 'scantron', $parser is hashref of csv column mapping
                   4226: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3, 
                   4227: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
1.858     raeburn  4228: #        $allfiles - reference to hash for embedded objects
                   4229: #        $codebase - reference to hash for codebase of java objects
                   4230: #        $desuname - username for permanent storage of uploaded file
                   4231: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  4232: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   4233: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  4234: #        $resizewidth - width (pixels) to which to resize uploaded image
                   4235: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  4236: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  4237: #                    from File::MMagic.
1.858     raeburn  4238: # 
1.686     albertel 4239: # output: url of file in userspace, or error: <message> 
                   4240: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 4241: 
1.531     albertel 4242: sub userfileupload {
1.1090    raeburn  4243:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  4244:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 4245:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 4246:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 4247:     $fname=&clean_filename($fname);
1.1090    raeburn  4248:     # See if there is anything left
1.257     www      4249:     unless ($fname) { return 'error: no uploaded file'; }
1.1406    raeburn  4250:     # If filename now begins with a . prepend unix timestamp _ milliseconds
                   4251:     if ($fname =~ /^\./) {
                   4252:         my ($s,$usec) = &gettimeofday();
                   4253:         while (length($usec) < 6) {
                   4254:             $usec = '0'.$usec;
                   4255:         }
                   4256:         $fname = $s.'_'.substr($usec,0,3).$fname;
                   4257:     }
1.1090    raeburn  4258:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   4259:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   4260:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   4261:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  4262:         my $now = time;
1.1090    raeburn  4263:         my $filepath;
1.1095    raeburn  4264:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  4265:              $filepath = 'tmp/helprequests/'.$now;
                   4266:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   4267:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   4268:                          '_'.$env{'user.domain'}.'/pending';
                   4269:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   4270:             my ($docuname,$docudom);
1.1350    raeburn  4271:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  4272:                 $docudom = $destudom;
                   4273:             } else {
                   4274:                 $docudom = $env{'user.domain'};
                   4275:             }
1.1350    raeburn  4276:             if ($destuname =~ /^$match_username$/) {
1.1090    raeburn  4277:                 $docuname = $destuname;
                   4278:             } else {
                   4279:                 $docuname = $env{'user.name'};
                   4280:             }
                   4281:             if (exists($env{'form.group'})) {
                   4282:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4283:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4284:             }
                   4285:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   4286:             if ($context eq 'canceloverwrite') {
                   4287:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   4288:                 if (-e  $tempfile) {
                   4289:                     my @info = stat($tempfile);
                   4290:                     if ($info[9] eq $env{'form.timestamp'}) {
                   4291:                         unlink($tempfile);
                   4292:                     }
                   4293:                 }
                   4294:                 return;
1.523     raeburn  4295:             }
                   4296:         }
1.1090    raeburn  4297:         # Create the directory if not present
1.741     raeburn  4298:         my @parts=split(/\//,$filepath);
                   4299:         my $fullpath = $perlvar{'lonDaemons'};
                   4300:         for (my $i=0;$i<@parts;$i++) {
                   4301:             $fullpath .= '/'.$parts[$i];
                   4302:             if ((-e $fullpath)!=1) {
                   4303:                 mkdir($fullpath,0777);
                   4304:             }
                   4305:         }
1.1359    raeburn  4306:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  4307:         print $fh $env{'form.'.$formname};
                   4308:         close($fh);
1.1090    raeburn  4309:         if ($context eq 'existingfile') {
                   4310:             my @info = stat($fullpath.'/'.$fname);
                   4311:             return ($fullpath.'/'.$fname,$info[9]);
                   4312:         } else {
                   4313:             return $fullpath.'/'.$fname;
                   4314:         }
1.523     raeburn  4315:     }
1.995     raeburn  4316:     if ($subdir eq 'scantron') {
                   4317:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  4318:     } else {
1.995     raeburn  4319:         $fname="$subdir/$fname";
                   4320:     }
1.1090    raeburn  4321:     if ($context eq 'coursedoc') {
1.638     albertel 4322: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4323: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  4324:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 4325:             return &finishuserfileupload($docuname,$docudom,
                   4326: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  4327: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  4328:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  4329:         } else {
1.1218    raeburn  4330:             if ($env{'form.folder'}) {
                   4331:                 $fname=$env{'form.folder'}.'/'.$fname;
                   4332:             }
1.638     albertel 4333:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   4334: 				       $fname,$formname,$parser,
1.1095    raeburn  4335: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  4336:         }
1.719     banghart 4337:     } elsif (defined($destuname)) {
                   4338:         my $docuname=$destuname;
                   4339:         my $docudom=$destudom;
1.860     raeburn  4340: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4341: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4342:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4343:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4344:     } else {
1.638     albertel 4345:         my $docuname=$env{'user.name'};
                   4346:         my $docudom=$env{'user.domain'};
1.1220    raeburn  4347:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  4348:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   4349:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   4350:         }
1.860     raeburn  4351: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   4352: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  4353:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  4354:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      4355:     }
1.271     www      4356: }
                   4357: 
                   4358: sub finishuserfileupload {
1.860     raeburn  4359:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  4360:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  4361:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      4362:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 4363:   
1.860     raeburn  4364:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 4365:     $file=$fname;
                   4366:     if ($fname=~m|/|) {
                   4367:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   4368: 	$path.=$fnamepath.'/';
                   4369:     }
1.259     www      4370:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      4371:     my $count;
                   4372:     for ($count=4;$count<=$#parts;$count++) {
                   4373:         $filepath.="/$parts[$count]";
                   4374:         if ((-e $filepath)!=1) {
                   4375: 	    mkdir($filepath,0777);
                   4376:         }
                   4377:     }
1.984     neumanie 4378: 
1.258     www      4379: # Save the file
                   4380:     {
1.1359    raeburn  4381: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 4382: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   4383: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   4384: 	    return '/adm/notfound.html';
                   4385: 	}
1.1090    raeburn  4386:         if ($context eq 'overwrite') {
1.1117    foxr     4387:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  4388:             my $target = $filepath.'/'.$file;
                   4389:             if (-e $source) {
                   4390:                 my @info = stat($source);
                   4391:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   4392:                     unless (&File::Copy::move($source,$target)) {
                   4393:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   4394:                         return "Moving from $source failed";
                   4395:                     }
                   4396:                 } else {
                   4397:                     return "Temporary file: $source had unexpected date/time for last modification";
                   4398:                 }
                   4399:             } else {
                   4400:                 return "Temporary file: $source missing";
                   4401:             }
                   4402:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 4403: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   4404: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   4405: 	    return '/adm/notfound.html';
                   4406: 	}
1.570     albertel 4407: 	close(FH);
1.1051    raeburn  4408:         if ($resizewidth && $resizeheight) {
                   4409:             my $mm = new File::MMagic;
                   4410:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   4411:             if ($mime_type =~ m{^image/}) {
                   4412: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   4413:             }  
1.977     amueller 4414: 	}
1.258     www      4415:     }
1.1152    raeburn  4416:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   4417:         if (ref($mimetype)) {
                   4418:             if ($$mimetype eq '') {
                   4419:                 my $mm = new File::MMagic;
                   4420:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   4421:                 $$mimetype = $type;
                   4422:             }
                   4423:         }
                   4424:     }
1.1401    raeburn  4425:     if (($context ne 'scantron') && ($parser eq 'parse')) {
1.1152    raeburn  4426:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  4427:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   4428:                                                        $allfiles,$codebase);
                   4429:             unless ($parse_result eq 'ok') {
                   4430:                 &logthis('Failed to parse '.$filepath.$file.
                   4431: 	   	         ' for embedded media: '.$parse_result); 
                   4432:             }
1.637     raeburn  4433:         }
1.1401    raeburn  4434:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
                   4435:         my $format = $env{'form.scantron_format'};
                   4436:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
1.637     raeburn  4437:     }
1.860     raeburn  4438:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   4439:         my $input = $filepath.'/'.$file;
                   4440:         my $output = $filepath.'/'.'tn-'.$file;
                   4441:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359    raeburn  4442:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   4443:         system({$args[0]} @args);
1.860     raeburn  4444:         if (-e $filepath.'/'.'tn-'.$file) {
                   4445:             $fetchthumb  = 1; 
                   4446:         }
                   4447:     }
1.858     raeburn  4448:  
1.259     www      4449: # Notify homeserver to grep it
                   4450: #
1.984     neumanie 4451:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 4452:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      4453:     if ($fetchresult eq 'ok') {
1.860     raeburn  4454:         if ($fetchthumb) {
                   4455:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   4456:             if ($thumbresult ne 'ok') {
                   4457:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   4458:                          $docuhome.': '.$thumbresult);
                   4459:             }
                   4460:         }
1.259     www      4461: #
1.258     www      4462: # Return the URL to it
1.494     albertel 4463:         return '/uploaded/'.$path.$file;
1.263     www      4464:     } else {
1.494     albertel 4465:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   4466: 		 ': '.$fetchresult);
1.263     www      4467:         return '/adm/notfound.html';
1.858     raeburn  4468:     }
1.493     albertel 4469: }
                   4470: 
1.637     raeburn  4471: sub extract_embedded_items {
1.961     raeburn  4472:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  4473:     my @state = ();
1.1164    raeburn  4474:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4475:     my %javafiles = (
                   4476:                       codebase => '',
                   4477:                       code => '',
                   4478:                       archive => ''
                   4479:                     );
                   4480:     my %mediafiles = (
                   4481:                       src => '',
                   4482:                       movie => '',
                   4483:                      );
1.648     raeburn  4484:     my $p;
                   4485:     if ($content) {
                   4486:         $p = HTML::LCParser->new($content);
                   4487:     } else {
1.961     raeburn  4488:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4489:     }
1.641     albertel 4490:     while (my $t=$p->get_token()) {
1.640     albertel 4491: 	if ($t->[0] eq 'S') {
                   4492: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4493: 	    push(@state, $tagname);
1.648     raeburn  4494:             if (lc($tagname) eq 'allow') {
                   4495:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4496:             }
1.640     albertel 4497: 	    if (lc($tagname) eq 'img') {
                   4498: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4499: 	    }
1.886     albertel 4500: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  4501:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  4502:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4503:                 }
1.886     albertel 4504: 	    }
1.645     raeburn  4505:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4506:                 my $src;
1.645     raeburn  4507:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4508:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4509:                 } else {
1.1164    raeburn  4510:                     if ($attr->{'src'} ne '') {
                   4511:                         $src = $attr->{'src'};
                   4512:                         &add_filetype($allfiles,$src,'src');
                   4513:                     }
                   4514:                 }
                   4515:                 my $text = $p->get_trimmed_text();
                   4516:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4517:                     my @swfargs = split(/,/,$1);
                   4518:                     foreach my $item (@swfargs) {
                   4519:                         $item =~ s/["']//g;
                   4520:                         $item =~ s/^\s+//;
                   4521:                         $item =~ s/\s+$//;
                   4522:                     }
                   4523:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4524:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4525:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4526:                         } else {
                   4527:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4528:                         }
                   4529:                     }
1.645     raeburn  4530:                 }
                   4531:             }
                   4532:             if (lc($tagname) eq 'link') {
                   4533:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4534:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4535:                 }
                   4536:             }
1.640     albertel 4537: 	    if (lc($tagname) eq 'object' ||
                   4538: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4539: 		foreach my $item (keys(%javafiles)) {
                   4540: 		    $javafiles{$item} = '';
                   4541: 		}
1.1164    raeburn  4542:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4543:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4544:                 }
1.640     albertel 4545: 	    }
                   4546: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4547: 		my $name = lc($attr->{'name'});
                   4548: 		foreach my $item (keys(%javafiles)) {
                   4549: 		    if ($name eq $item) {
                   4550: 			$javafiles{$item} = $attr->{'value'};
                   4551: 			last;
                   4552: 		    }
                   4553: 		}
1.1164    raeburn  4554:                 my $pathfrom;
1.640     albertel 4555: 		foreach my $item (keys(%mediafiles)) {
                   4556: 		    if ($name eq $item) {
1.1164    raeburn  4557:                         $pathfrom = $attr->{'value'};
                   4558:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4559: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4560: 			last;
                   4561: 		    }
                   4562: 		}
1.1164    raeburn  4563:                 if ($name eq 'flashvars') {
                   4564:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4565:                 }
                   4566:                 if ($pathfrom ne '') {
                   4567:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4568:                                          $pathfrom);
                   4569:                 }
1.640     albertel 4570: 	    }
                   4571: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4572: 		foreach my $item (keys(%javafiles)) {
                   4573: 		    if ($attr->{$item}) {
                   4574: 			$javafiles{$item} = $attr->{$item};
                   4575: 			last;
                   4576: 		    }
                   4577: 		}
                   4578: 		foreach my $item (keys(%mediafiles)) {
                   4579: 		    if ($attr->{$item}) {
                   4580: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4581: 			last;
                   4582: 		    }
                   4583: 		}
1.1164    raeburn  4584:                 if (lc($tagname) eq 'embed') {
                   4585:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4586:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4587:                                              $attr->{'src'});
                   4588:                     }
                   4589:                 }
1.640     albertel 4590: 	    }
1.1243    raeburn  4591:             if (lc($tagname) eq 'iframe') {
                   4592:                 my $src = $attr->{'src'} ;
                   4593:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4594:                     &add_filetype($allfiles,$src,'src');
                   4595:                 } elsif ($src =~ m{^/}) {
                   4596:                     if ($env{'request.course.id'}) {
                   4597:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4598:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4599:                         my $url = &hreflocation('',$fullpath);
                   4600:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4601:                             my $relpath = $1;
                   4602:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4603:                                 &add_filetype($allfiles,$1,'src');
                   4604:                             }
                   4605:                         }
                   4606:                     }
                   4607:                 }
                   4608:             }
1.1164    raeburn  4609:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  4610:                 pop(@state);
1.1164    raeburn  4611:             }
1.640     albertel 4612: 	} elsif ($t->[0] eq 'E') {
                   4613: 	    my ($tagname) = ($t->[1]);
                   4614: 	    if ($javafiles{'codebase'} ne '') {
                   4615: 		$javafiles{'codebase'} .= '/';
                   4616: 	    }  
                   4617: 	    if (lc($tagname) eq 'applet' ||
                   4618: 		lc($tagname) eq 'object' ||
                   4619: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4620: 		) {
                   4621: 		foreach my $item (keys(%javafiles)) {
                   4622: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4623: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4624: 			&add_filetype($allfiles,$file,$item);
                   4625: 		    }
                   4626: 		}
                   4627: 	    } 
                   4628: 	    pop @state;
                   4629: 	}
                   4630:     }
1.1164    raeburn  4631:     foreach my $id (sort(keys(%flashvars))) {
                   4632:         if ($shockwave{$id} ne '') {
                   4633:             my @pairs = split(/\&/,$flashvars{$id});
                   4634:             foreach my $pair (@pairs) {
                   4635:                 my ($key,$value) = split(/\=/,$pair);
                   4636:                 if ($key eq 'thumb') {
                   4637:                     &add_filetype($allfiles,$value,$key);
                   4638:                 } elsif ($key eq 'content') {
                   4639:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4640:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4641:                     if ($ext ne '') {
                   4642:                         &add_filetype($allfiles,$path.$value,$ext);
                   4643:                     }
                   4644:                 }
                   4645:             }
                   4646:         }
                   4647:     }
1.637     raeburn  4648:     return 'ok';
                   4649: }
                   4650: 
1.639     albertel 4651: sub add_filetype {
                   4652:     my ($allfiles,$file,$type)=@_;
                   4653:     if (exists($allfiles->{$file})) {
                   4654: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4655: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4656: 	}
                   4657:     } else {
                   4658: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4659:     }
                   4660: }
                   4661: 
1.1164    raeburn  4662: sub embedded_dependency {
                   4663:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4664:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4665:         if (($identifier ne '') &&
                   4666:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4667:             ($pathfrom ne '')) {
                   4668:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4669:             foreach my $dep (@{$related->{$identifier}}) {
                   4670:                 &add_filetype($allfiles,$path.$dep,'object');
                   4671:             }
                   4672:         }
                   4673:     }
                   4674:     return;
                   4675: }
                   4676: 
1.1401    raeburn  4677: sub bubblesheet_converter {
                   4678:     my ($cdom,$fullpath,$config,$format) = @_;
                   4679:     if ((&domain($cdom) ne '') &&
1.1403    raeburn  4680:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
1.1401    raeburn  4681:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
1.1404    raeburn  4682:         my (%csvcols,%csvoptions);
                   4683:         if (ref($config->{'fields'}) eq 'HASH') {  
                   4684:             %csvcols = %{$config->{'fields'}};
                   4685:         }
                   4686:         if (ref($config->{'options'}) eq 'HASH') {
                   4687:             %csvoptions = %{$config->{'options'}};
                   4688:         }
1.1401    raeburn  4689:         my %csvbynum = reverse(%csvcols);
                   4690:         my %scantronconf = &get_scantron_config($format,$cdom);
                   4691:         if (keys(%scantronconf)) {
                   4692:             my %bynum = (
                   4693:                           $scantronconf{CODEstart} => 'CODEstart',
                   4694:                           $scantronconf{IDstart}   => 'IDstart',
                   4695:                           $scantronconf{PaperID}   => 'PaperID',
                   4696:                           $scantronconf{FirstName} => 'FirstName',
                   4697:                           $scantronconf{LastName}  => 'LastName',
                   4698:                           $scantronconf{Qstart}    => 'Qstart',
                   4699:                         );
                   4700:             my @ordered;
                   4701:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
1.1403    raeburn  4702:                 push(@ordered,$bynum{$item});
1.1401    raeburn  4703:             }
                   4704:             my %mapstart = (
                   4705:                               CODEstart => 'CODE',
                   4706:                               IDstart   => 'ID',
                   4707:                               PaperID   => 'PaperID',
                   4708:                               FirstName => 'FirstName',
                   4709:                               LastName  => 'LastName',
                   4710:                               Qstart    => 'FirstQuestion',
                   4711:                            );
                   4712:             my %maplength = (
                   4713:                               CODEstart => 'CODElength',
                   4714:                               IDstart   => 'IDlength',
                   4715:                               PaperID   => 'PaperIDlength',
                   4716:                               FirstName => 'FirstNamelength',
                   4717:                               LastName  => 'LastNamelength',
                   4718:             );
                   4719:             if (open(my $fh,'<',$fullpath)) {
                   4720:                 my $output;
1.1403    raeburn  4721:                 my %lettdig = &letter_to_digits();
                   4722:                 my %diglett = reverse(%lettdig);
                   4723:                 my $numletts = scalar(keys(%lettdig));
1.1404    raeburn  4724:                 my $num = 0;
1.1401    raeburn  4725:                 while (my $line=<$fh>) {
1.1404    raeburn  4726:                     $num ++;
                   4727:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
1.1401    raeburn  4728:                     $line =~ s{[\r\n]+$}{};
                   4729:                     my %found;
1.1475    raeburn  4730:                     my @values = split(/,/,$line,-1);
1.1401    raeburn  4731:                     my ($qstart,$record);
                   4732:                     for (my $i=0; $i<@values; $i++) {
1.1403    raeburn  4733:                         if ((($qstart ne '') && ($i > $qstart)) ||
                   4734:                             ($csvbynum{$i} eq 'FirstQuestion')) {
                   4735:                             if ($values[$i] eq '') {
                   4736:                                 $values[$i] = $scantronconf{'Qoff'};
                   4737:                             } elsif ($scantronconf{'Qon'} eq 'number') {
                   4738:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4739:                                     $values[$i] = $lettdig{uc($values[$i])};
                   4740:                                 }
                   4741:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
                   4742:                                 if ($values[$i] =~ /^[0-9]$/) {
                   4743:                                     $values[$i] = $diglett{$values[$i]};
                   4744:                                 }
                   4745:                             } else {
                   4746:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
                   4747:                                     my $digit;
                   4748:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
                   4749:                                         $digit = $lettdig{uc($values[$i])}-1;
                   4750:                                         if ($values[$i] eq 'J') {
                   4751:                                             $digit += $numletts;
                   4752:                                         }
                   4753:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
                   4754:                                         $digit = $values[$i]-1;
                   4755:                                         if ($values[$i] eq '0') {
                   4756:                                             $digit += $numletts;
                   4757:                                         }
                   4758:                                     }
                   4759:                                     my $qval='';
                   4760:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
                   4761:                                         if ($j == $digit) {
                   4762:                                             $qval .= $scantronconf{'Qon'};
                   4763:                                         } else {
                   4764:                                             $qval .= $scantronconf{'Qoff'};
                   4765:                                         }
                   4766:                                     }
                   4767:                                     $values[$i] = $qval;
                   4768:                                 }
                   4769:                             }
                   4770:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
                   4771:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
                   4772:                             }
                   4773:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
                   4774:                             if ($numblank > 0) {
                   4775:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
                   4776:                             }
1.1401    raeburn  4777:                             if ($csvbynum{$i} eq 'FirstQuestion') {
                   4778:                                 $qstart = $i;
1.1403    raeburn  4779:                                 $found{$csvbynum{$i}} = $values[$i];
1.1401    raeburn  4780:                             } else {
1.1403    raeburn  4781:                                 $found{'FirstQuestion'} .= $values[$i];
                   4782:                             }
                   4783:                         } elsif (exists($csvbynum{$i})) {
1.1404    raeburn  4784:                             if ($csvoptions{'rem'}) {
                   4785:                                 $values[$i] =~ s/^\s+//;
                   4786:                             }
                   4787:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
1.1403    raeburn  4788:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
                   4789:                                     $values[$i] = '0'.$values[$i];
1.1401    raeburn  4790:                                 }
                   4791:                             }
                   4792:                             $found{$csvbynum{$i}} = $values[$i];
                   4793:                         }
                   4794:                     }
                   4795:                     foreach my $item (@ordered) {
                   4796:                         my $currlength = 1+length($record);
                   4797:                         my $numspaces = $scantronconf{$item} - $currlength;
                   4798:                         if ($numspaces > 0) {
                   4799:                             $record .= (' ' x $numspaces);
                   4800:                         }
                   4801:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
                   4802:                             unless ($item eq 'Qstart') {
                   4803:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
                   4804:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
                   4805:                                 }
                   4806:                             }
                   4807:                             $record .= $found{$mapstart{$item}};
                   4808:                         }
                   4809:                     }
                   4810:                     $output .= "$record\n";
                   4811:                 }
                   4812:                 close($fh);
                   4813:                 if ($output) {
                   4814:                     if (open(my $fh,'>',$fullpath)) {
                   4815:                         print $fh $output;
                   4816:                         close($fh);
                   4817:                     }
                   4818:                 }
                   4819:             }
                   4820:         }
                   4821:         return;
                   4822:     }
                   4823: }
                   4824: 
1.1403    raeburn  4825: sub letter_to_digits {
                   4826:     my %lettdig = (
                   4827:                     A => 1,
                   4828:                     B => 2,
                   4829:                     C => 3,
                   4830:                     D => 4,
                   4831:                     E => 5,
                   4832:                     F => 6,
                   4833:                     G => 7,
                   4834:                     H => 8,
                   4835:                     I => 9,
                   4836:                     J => 0,
                   4837:                   );
                   4838:     return %lettdig;
                   4839: }
                   4840: 
1.1401    raeburn  4841: sub get_scantron_config {
                   4842:     my ($which,$cdom) = @_;
                   4843:     my @lines = &get_scantronformat_file($cdom);
                   4844:     my %config;
                   4845:     #FIXME probably should move to XML it has already gotten a bit much now
                   4846:     foreach my $line (@lines) {
                   4847:         my ($name,$descrip)=split(/:/,$line);
                   4848:         if ($name ne $which ) { next; }
                   4849:         chomp($line);
                   4850:         my @config=split(/:/,$line);
                   4851:         $config{'name'}=$config[0];
                   4852:         $config{'description'}=$config[1];
                   4853:         $config{'CODElocation'}=$config[2];
                   4854:         $config{'CODEstart'}=$config[3];
                   4855:         $config{'CODElength'}=$config[4];
                   4856:         $config{'IDstart'}=$config[5];
                   4857:         $config{'IDlength'}=$config[6];
                   4858:         $config{'Qstart'}=$config[7];
                   4859:         $config{'Qlength'}=$config[8];
                   4860:         $config{'Qoff'}=$config[9];
                   4861:         $config{'Qon'}=$config[10];
                   4862:         $config{'PaperID'}=$config[11];
                   4863:         $config{'PaperIDlength'}=$config[12];
                   4864:         $config{'FirstName'}=$config[13];
                   4865:         $config{'FirstNamelength'}=$config[14];
                   4866:         $config{'LastName'}=$config[15];
                   4867:         $config{'LastNamelength'}=$config[16];
                   4868:         $config{'BubblesPerRow'}=$config[17];
                   4869:         last;
                   4870:     }
                   4871:     return %config;
                   4872: }
                   4873: 
                   4874: sub get_scantronformat_file {
                   4875:     my ($cdom) = @_;
                   4876:     if ($cdom eq '') {
                   4877:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4878:     }
                   4879:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
                   4880:     my $gottab = 0;
                   4881:     my @lines;
                   4882:     if (ref($domconfig{'scantron'}) eq 'HASH') {
                   4883:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
                   4884:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
                   4885:             if ($formatfile ne '-1') {
                   4886:                 @lines = split("\n",$formatfile,-1);
                   4887:                 $gottab = 1;
                   4888:             }
                   4889:         }
                   4890:     }
                   4891:     if (!$gottab) {
                   4892:         my $confname = $cdom.'-domainconfig';
                   4893:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
                   4894:         my $formatfile = &getfile($default);
                   4895:         if ($formatfile ne '-1') {
                   4896:             @lines = split("\n",$formatfile,-1);
                   4897:             $gottab = 1;
                   4898:         }
                   4899:     }
                   4900:     if (!$gottab) {
                   4901:         my @domains = &current_machine_domains();
                   4902:         if (grep(/^\Q$cdom\E$/,@domains)) {
                   4903:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
                   4904:                 @lines = <$fh>;
                   4905:                 close($fh);
1.1403    raeburn  4906:             }
1.1401    raeburn  4907:         } else {
                   4908:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
                   4909:                 @lines = <$fh>;
                   4910:                 close($fh);
                   4911:             }
                   4912:         }
                   4913:     }
                   4914:     return @lines;
                   4915: }
                   4916: 
1.493     albertel 4917: sub removeuploadedurl {
1.984     neumanie 4918:     my ($url)=@_;	
                   4919:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4920:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4921: }
                   4922: 
                   4923: sub removeuserfile {
                   4924:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4925:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4926:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4927:     if ($result eq 'ok') {	
1.798     raeburn  4928:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4929:             my $metafile = $fname.'.meta';
                   4930:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4931: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4932:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4933:             my $sqlresult = 
1.823     albertel 4934:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4935:                                         'portfolio_metadata',$group,
                   4936:                                         'delete');
1.798     raeburn  4937:         }
                   4938:     }
                   4939:     return $result;
1.257     www      4940: }
1.15      www      4941: 
1.530     albertel 4942: sub mkdiruserfile {
                   4943:     my ($docuname,$docudom,$dir)=@_;
                   4944:     my $home=&homeserver($docuname,$docudom);
                   4945:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4946: }
                   4947: 
1.531     albertel 4948: sub renameuserfile {
                   4949:     my ($docuname,$docudom,$old,$new)=@_;
                   4950:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4951:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4952:                         &escape("$old").':'.&escape("$new"),$home);
                   4953:     if ($result eq 'ok') {
                   4954:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4955:             my $oldmeta = $old.'.meta';
                   4956:             my $newmeta = $new.'.meta';
                   4957:             my $metaresult = 
                   4958:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4959: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4960:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4961:             my $sqlresult = 
1.823     albertel 4962:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4963:                                         'portfolio_metadata',$group,
                   4964:                                         'delete');
1.798     raeburn  4965:         }
                   4966:     }
                   4967:     return $result;
1.531     albertel 4968: }
                   4969: 
1.14      www      4970: # ------------------------------------------------------------------------- Log
                   4971: 
                   4972: sub log {
                   4973:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4974:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4975: }
                   4976: 
                   4977: # ------------------------------------------------------------------ Course Log
1.352     www      4978: #
                   4979: # This routine flushes several buffers of non-mission-critical nature
                   4980: #
1.157     www      4981: 
                   4982: sub flushcourselogs {
1.352     www      4983:     &logthis('Flushing log buffers');
                   4984: #
                   4985: # course logs
                   4986: # This is a log of all transactions in a course, which can be used
                   4987: # for data mining purposes
                   4988: #
                   4989: # It also collects the courseid database, which lists last transaction
                   4990: # times and course titles for all courseids
                   4991: #
                   4992:     my %courseidbuffer=();
1.921     raeburn  4993:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4994:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4995: 		          &escape($courselogs{$crsid}),
                   4996: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4997: 	    delete $courselogs{$crsid};
                   4998:         } else {
                   4999:             &logthis('Failed to flush log buffer for '.$crsid);
                   5000:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 5001:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      5002:                         " exceeded maximum size, deleting.</font>");
                   5003:                delete $courselogs{$crsid};
                   5004:             }
1.352     www      5005:         }
1.920     raeburn  5006:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  5007:             'description' => $coursedescrbuf{$crsid},
                   5008:             'inst_code'    => $courseinstcodebuf{$crsid},
                   5009:             'type'        => $coursetypebuf{$crsid},
                   5010:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  5011:         };
1.191     harris41 5012:     }
1.352     www      5013: #
                   5014: # Write course id database (reverse lookup) to homeserver of courses 
                   5015: # Is used in pickcourse
                   5016: #
1.840     albertel 5017:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  5018:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  5019:                                     $courseidbuffer{$crs_home},
                   5020:                                     $crs_home,'timeonly');
1.352     www      5021:     }
                   5022: #
                   5023: # File accesses
                   5024: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   5025: #
1.449     matthew  5026:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  5027:         if ($entry =~ /___count$/) {
                   5028:             my ($dom,$name);
1.807     albertel 5029:             ($dom,$name,undef)=
1.811     albertel 5030: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  5031:             if (! defined($dom) || $dom eq '' || 
                   5032:                 ! defined($name) || $name eq '') {
1.620     albertel 5033:                 my $cid = $env{'request.course.id'};
1.1472    raeburn  5034: #
                   5035: # FIXME 11/29/2021
                   5036: # Typo in rev. 1.458 (2003/12/09)??
                   5037: # These should likely by $env{'course.'.$cid.'.domain'} and $env{'course.'.$cid.'.num'}
                   5038: #
                   5039: # While these ramain as  $env{'request.'.$cid.'.domain'} and $env{'request.'.$cid.'.num'}
                   5040: # $dom and $name will always be null, so the &inc() call will default to storing this data
                   5041: # in a nohist_accesscount.db file for the user rather than the course.
                   5042: #
                   5043: # That said there is a lot of noise in the data being stored.
                   5044: # So counts for prtspool/  and adm/ etc. are recorded.
                   5045: #
                   5046: # A review of which items ending '___count' are written to %accesshash should likely be 
                   5047: # made before deciding whether to set these to 'course.' instead of 'request.'
                   5048: #
                   5049: # Under the current scheme each user receives a nohist_accesscount.db file listing 
                   5050: # accesses for things which are not published resources, regardless of course, and
                   5051: # there is not a nohist_accesscount.db file in a course, which might log accesses from
                   5052: # anyone in the course for things which are not published resources.
                   5053: #
                   5054: # For an author, nohist_accesscount.db ends up having records for other items
                   5055: # mixed up with the legitimate access counts for the author's published resources.
                   5056: #
1.620     albertel 5057:                 $dom  = $env{'request.'.$cid.'.domain'};
                   5058:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  5059:             }
1.450     matthew  5060:             my $value = $accesshash{$entry};
                   5061:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   5062:             my %temphash=($url => $value);
1.449     matthew  5063:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   5064:             if ($result eq 'ok') {
                   5065:                 delete $accesshash{$entry};
                   5066:             }
                   5067:         } else {
1.811     albertel 5068:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      5069:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  5070:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  5071:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   5072:                 delete $accesshash{$entry};
                   5073:             }
1.185     www      5074:         }
1.191     harris41 5075:     }
1.352     www      5076: #
                   5077: # Roles
                   5078: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   5079: #
1.800     albertel 5080:     foreach my $entry (keys(%userrolehash)) {
1.351     www      5081:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      5082: 	    split(/\:/,$entry);
                   5083:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      5084:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      5085:                 $rudom,$runame) eq 'ok') {
                   5086: 	    delete $userrolehash{$entry};
                   5087:         }
                   5088:     }
1.662     raeburn  5089: #
1.1334    raeburn  5090: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  5091: #
                   5092:     my %domrolebuffer = ();
1.1000    raeburn  5093:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 5094:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  5095:         if ($domrolebuffer{$rudom}) {
                   5096:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   5097:                       '='.&escape($domainrolehash{$entry});
                   5098:         } else {
                   5099:             $domrolebuffer{$rudom}.=&escape($entry).
                   5100:                       '='.&escape($domainrolehash{$entry});
                   5101:         }
                   5102:         delete $domainrolehash{$entry};
                   5103:     }
                   5104:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  5105: 	my %servers;
                   5106: 	if (defined(&domain($dom,'primary'))) {
                   5107: 	    my $primary=&domain($dom,'primary');
                   5108: 	    my $hostname=&hostname($primary);
                   5109: 	    $servers{$primary} = $hostname;
                   5110: 	} else { 
                   5111: 	    %servers = &get_servers($dom,'library');
                   5112: 	}
1.841     albertel 5113: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  5114: 	    if (&reply('domroleput:'.$dom.':'.
                   5115: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   5116: 		last;
                   5117: 	    } else {  
1.841     albertel 5118: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   5119: 	    }
1.662     raeburn  5120:         }
                   5121:     }
1.186     www      5122:     $dumpcount++;
1.157     www      5123: }
                   5124: 
                   5125: sub courselog {
                   5126:     my $what=shift;
1.158     www      5127:     $what=time.':'.$what;
1.620     albertel 5128:     unless ($env{'request.course.id'}) { return ''; }
                   5129:     $coursedombuf{$env{'request.course.id'}}=
                   5130:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5131:     $coursenumbuf{$env{'request.course.id'}}=
                   5132:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   5133:     $coursehombuf{$env{'request.course.id'}}=
                   5134:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   5135:     $coursedescrbuf{$env{'request.course.id'}}=
                   5136:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   5137:     $courseinstcodebuf{$env{'request.course.id'}}=
                   5138:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   5139:     $courseownerbuf{$env{'request.course.id'}}=
                   5140:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  5141:     $coursetypebuf{$env{'request.course.id'}}=
                   5142:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 5143:     if (defined $courselogs{$env{'request.course.id'}}) {
                   5144: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      5145:     } else {
1.620     albertel 5146: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      5147:     }
1.620     albertel 5148:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      5149: 	&flushcourselogs();
                   5150:     }
1.158     www      5151: }
                   5152: 
                   5153: sub courseacclog {
                   5154:     my $fnsymb=shift;
1.620     albertel 5155:     unless ($env{'request.course.id'}) { return ''; }
                   5156:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      5157:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      5158:         $what.=':POST';
1.583     matthew  5159:         # FIXME: Probably ought to escape things....
1.800     albertel 5160: 	foreach my $key (keys(%env)) {
                   5161:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  5162:                 my $formitem = $1;
                   5163:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   5164:                     $what.=':'.$formitem.'='.$env{$key};
                   5165:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
1.1432    raeburn  5166:                     if ($formitem eq 'proctorpassword') {
1.1433    raeburn  5167:                         $what.=':'.$formitem.'=' . '*' x length($env{$key});
1.1432    raeburn  5168:                     } else {
                   5169:                         $what.=':'.$formitem.'='.$env{$key};
                   5170:                     }
1.975     raeburn  5171:                 }
1.158     www      5172:             }
1.191     harris41 5173:         }
1.583     matthew  5174:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   5175:         # FIXME: We should not be depending on a form parameter that someone
                   5176:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 5177:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  5178:             $what.= ':POST';
                   5179:             # FIXME: Probably ought to escape things....
                   5180:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   5181:                                  'crsdiscuss') {
1.620     albertel 5182:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  5183:             }
                   5184:         }
1.158     www      5185:     }
                   5186:     &courselog($what);
1.149     www      5187: }
                   5188: 
1.185     www      5189: sub countacc {
                   5190:     my $url=&declutter(shift);
1.458     matthew  5191:     return if (! defined($url) || $url eq '');
1.620     albertel 5192:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      5193: #
                   5194: # Mark that this url was used in this course
                   5195: #
1.620     albertel 5196:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      5197: #
                   5198: # Increase the access count for this resource in this child process
                   5199: #
1.281     www      5200:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  5201:     $accesshash{$key}++;
1.185     www      5202: }
1.349     www      5203: 
1.361     www      5204: sub linklog {
                   5205:     my ($from,$to)=@_;
                   5206:     $from=&declutter($from);
                   5207:     $to=&declutter($to);
                   5208:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   5209:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   5210: }
1.1160    www      5211: 
                   5212: sub statslog {
                   5213:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   5214:     if ($users<2) { return; }
                   5215:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   5216:             'course'       => $env{'request.course.id'},
                   5217:             'sections'     => '"all"',
                   5218:             'num_students' => $users,
                   5219:             'part'         => $part,
                   5220:             'symb'         => $symb,
                   5221:             'mean_tries'   => $av_attempts,
                   5222:             'deg_of_diff'  => $degdiff});
                   5223:     foreach my $key (keys(%dynstore)) {
                   5224:         $accesshash{$key}=$dynstore{$key};
                   5225:     }
                   5226: }
1.361     www      5227:   
1.349     www      5228: sub userrolelog {
                   5229:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 5230:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      5231:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5232:        $userrolehash
                   5233:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      5234:                     =$tend.':'.$tstart;
1.662     raeburn  5235:     }
1.1169    droeschl 5236:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 5237:        $userrolehash
                   5238:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   5239:                     =$tend.':'.$tstart;
                   5240:     }
1.1334    raeburn  5241:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  5242:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   5243:        $domainrolehash
                   5244:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   5245:                     = $tend.':'.$tstart;
                   5246:     }
1.351     www      5247: }
                   5248: 
1.957     raeburn  5249: sub courserolelog {
                   5250:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  5251:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   5252:         my $cdom = $1;
                   5253:         my $cnum = $2;
                   5254:         my $sec = $3;
                   5255:         my $namespace = 'rolelog';
                   5256:         my %storehash = (
                   5257:                            role    => $trole,
                   5258:                            start   => $tstart,
                   5259:                            end     => $tend,
                   5260:                            selfenroll => $selfenroll,
                   5261:                            context    => $context,
                   5262:                         );
                   5263:         if ($trole eq 'gr') {
                   5264:             $namespace = 'groupslog';
                   5265:             $storehash{'group'} = $sec;
                   5266:         } else {
                   5267:             $storehash{'section'} = $sec;
                   5268:         }
1.1188    raeburn  5269:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   5270:                    $domain,$cnum,$cdom);
1.1184    raeburn  5271:         if (($trole ne 'st') || ($sec ne '')) {
                   5272:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  5273:         }
                   5274:     }
                   5275:     return;
                   5276: }
                   5277: 
1.1184    raeburn  5278: sub domainrolelog {
                   5279:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5280:     if ($area =~ m{^/($match_domain)/$}) {
                   5281:         my $cdom = $1;
                   5282:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   5283:         my $namespace = 'rolelog';
                   5284:         my %storehash = (
                   5285:                            role    => $trole,
                   5286:                            start   => $tstart,
                   5287:                            end     => $tend,
                   5288:                            context => $context,
                   5289:                         );
1.1188    raeburn  5290:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   5291:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  5292:     }
                   5293:     return;
                   5294: 
                   5295: }
                   5296: 
                   5297: sub coauthorrolelog {
                   5298:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   5299:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   5300:         my $audom = $1;
                   5301:         my $auname = $2;
                   5302:         my $namespace = 'rolelog';
                   5303:         my %storehash = (
                   5304:                            role    => $trole,
                   5305:                            start   => $tstart,
                   5306:                            end     => $tend,
                   5307:                            context => $context,
                   5308:                         );
1.1188    raeburn  5309:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   5310:                    $domain,$auname,$audom);
1.1184    raeburn  5311:     }
                   5312:     return;
                   5313: }
                   5314: 
1.351     www      5315: sub get_course_adv_roles {
1.948     raeburn  5316:     my ($cid,$codes) = @_;
1.620     albertel 5317:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      5318:     my %coursehash=&coursedescription($cid);
1.988     raeburn  5319:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      5320:     my %nothide=();
1.800     albertel 5321:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  5322:         if ($user !~ /:/) {
                   5323: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   5324:         } else {
                   5325:             $nothide{$user}=1;
                   5326:         }
1.470     www      5327:     }
1.1219    raeburn  5328:     my @possdoms = ($coursehash{'domain'});
                   5329:     if ($coursehash{'checkforpriv'}) {
                   5330:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   5331:     }
1.351     www      5332:     my %returnhash=();
                   5333:     my %dumphash=
                   5334:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   5335:     my $now=time;
1.997     raeburn  5336:     my %privileged;
1.1000    raeburn  5337:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 5338: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      5339:         if (($tstart) && ($tstart<0)) { next; }
                   5340:         if (($tend) && ($tend<$now)) { next; }
                   5341:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 5342:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 5343: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  5344:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  5345:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 5346: 	if ($role eq 'cr') { next; }
1.948     raeburn  5347:         if ($codes) {
                   5348:             if ($section) { $role .= ':'.$section; }
                   5349:             if ($returnhash{$role}) {
                   5350:                 $returnhash{$role}.=','.$username.':'.$domain;
                   5351:             } else {
                   5352:                 $returnhash{$role}=$username.':'.$domain;
                   5353:             }
1.351     www      5354:         } else {
1.988     raeburn  5355:             my $key=&plaintext($role,$crstype);
1.973     bisitz   5356:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  5357:             if ($returnhash{$key}) {
                   5358: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   5359:             } else {
                   5360:                 $returnhash{$key}=$username.':'.$domain;
                   5361:             }
1.351     www      5362:         }
1.948     raeburn  5363:     }
1.400     www      5364:     return %returnhash;
                   5365: }
                   5366: 
                   5367: sub get_my_roles {
1.937     raeburn  5368:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 5369:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   5370:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  5371:     my (%dumphash,%nothide);
1.1086    raeburn  5372:     if ($context eq 'userroles') {
1.1166    raeburn  5373:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  5374:     } else {
1.1219    raeburn  5375:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  5376:         if ($hidepriv) {
                   5377:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   5378:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   5379:                 if ($user !~ /:/) {
                   5380:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   5381:                 } else {
                   5382:                     $nothide{$user} = 1;
                   5383:                 }
                   5384:             }
                   5385:         }
1.858     raeburn  5386:     }
1.400     www      5387:     my %returnhash=();
                   5388:     my $now=time;
1.999     raeburn  5389:     my %privileged;
1.800     albertel 5390:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  5391:         my ($role,$tend,$tstart);
                   5392:         if ($context eq 'userroles') {
1.1149    raeburn  5393:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  5394: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   5395:         } else {
                   5396:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   5397:         }
1.400     www      5398:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  5399:         my $status = 'active';
1.939     raeburn  5400:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  5401:             $status = 'previous';
                   5402:         } 
                   5403:         if (($tstart) && ($now<$tstart)) {
                   5404:             $status = 'future';
                   5405:         }
                   5406:         if (ref($types) eq 'ARRAY') {
                   5407:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   5408:                 next;
                   5409:             } 
                   5410:         } else {
                   5411:             if ($status ne 'active') {
                   5412:                 next;
                   5413:             }
                   5414:         }
1.867     raeburn  5415:         my ($rolecode,$username,$domain,$section,$area);
                   5416:         if ($context eq 'userroles') {
1.1186    raeburn  5417:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  5418:             (undef,$domain,$username,$section) = split(/\//,$area);
                   5419:         } else {
                   5420:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   5421:         }
1.832     raeburn  5422:         if (ref($roledoms) eq 'ARRAY') {
                   5423:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   5424:                 next;
                   5425:             }
                   5426:         }
                   5427:         if (ref($roles) eq 'ARRAY') {
                   5428:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  5429:                 if ($role =~ /^cr\//) {
                   5430:                     if (!grep(/^cr$/,@{$roles})) {
                   5431:                         next;
                   5432:                     }
1.1104    raeburn  5433:                 } elsif ($role =~ /^gr\//) {
                   5434:                     if (!grep(/^gr$/,@{$roles})) {
                   5435:                         next;
                   5436:                     }
1.922     raeburn  5437:                 } else {
                   5438:                     next;
                   5439:                 }
1.832     raeburn  5440:             }
1.867     raeburn  5441:         }
1.937     raeburn  5442:         if ($hidepriv) {
1.1219    raeburn  5443:             my @privroles = ('dc','su');
1.999     raeburn  5444:             if ($context eq 'userroles') {
1.1219    raeburn  5445:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  5446:             } else {
1.1219    raeburn  5447:                 my $possdoms = [$domain];
                   5448:                 if (ref($roledoms) eq 'ARRAY') {
                   5449:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  5450:                 }
1.1219    raeburn  5451:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  5452:                     if (!$nothide{$username.':'.$domain}) {
                   5453:                         next;
                   5454:                     }
                   5455:                 }
1.937     raeburn  5456:             }
                   5457:         }
1.933     raeburn  5458:         if ($withsec) {
                   5459:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   5460:                 $tstart.':'.$tend;
                   5461:         } else {
                   5462:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   5463:         }
1.832     raeburn  5464:     }
1.373     www      5465:     return %returnhash;
1.399     www      5466: }
                   5467: 
1.1333    raeburn  5468: sub get_all_adhocroles {
                   5469:     my ($dom) = @_;
                   5470:     my @roles_by_num = ();
                   5471:     my %domdefaults = &get_domain_defaults($dom);
                   5472:     my (%description,%access_in_dom,%access_info);
                   5473:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   5474:         my $count = 0;
                   5475:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   5476:         my %ordered;
                   5477:         foreach my $role (sort(keys(%domcurrent))) {
                   5478:             my ($order,$desc,$access_in_dom);
                   5479:             if (ref($domcurrent{$role}) eq 'HASH') {
                   5480:                 $order = $domcurrent{$role}{'order'};
                   5481:                 $desc = $domcurrent{$role}{'desc'};
                   5482:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   5483:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   5484:             }
                   5485:             if ($order eq '') {
                   5486:                 $order = $count;
                   5487:             }
                   5488:             $ordered{$order} = $role;
                   5489:             if ($desc ne '') {
                   5490:                 $description{$role} = $desc;
                   5491:             } else {
                   5492:                 $description{$role}= $role;
                   5493:             }
                   5494:             $count++;
                   5495:         }
                   5496:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   5497:             push(@roles_by_num,$ordered{$item});
                   5498:         }
                   5499:     }
                   5500:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   5501: }
                   5502: 
1.1332    raeburn  5503: sub get_my_adhocroles {
1.1333    raeburn  5504:     my ($cid,$checkreg) = @_;
                   5505:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   5506:     if ($env{'request.course.id'} eq $cid) {
                   5507:         $cdom = $env{'course.'.$cid.'.domain'};
                   5508:         $cnum = $env{'course.'.$cid.'.num'};
                   5509:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   5510:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   5511:         $cdom = $1;
                   5512:         $cnum = $2;
                   5513:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   5514:                                      $cdom,$cnum);
                   5515:     }
                   5516:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   5517:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   5518:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   5519:         if ($rosterhash{$user} ne '') {
                   5520:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   5521:             return ([],{}) if ($type eq 'auto');
                   5522:         }
                   5523:     }
                   5524:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  5525:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  5526:             my $then=$env{'user.login.time'};
                   5527:             my $update=$env{'user.update.time'};
1.1335    raeburn  5528:             if (!$update) {
                   5529:                 $update = $then;
                   5530:             }
                   5531:             my @liveroles;
1.1334    raeburn  5532:             foreach my $role ('dh','da') {
                   5533:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  5534:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  5535:                     my $limit = $update;
                   5536:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   5537:                         $limit = $then;
                   5538:                     }
1.1335    raeburn  5539:                     my $activerole = 1;
                   5540:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   5541:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   5542:                     if ($activerole) {
                   5543:                         push(@liveroles,$role);
                   5544:                     }
1.1334    raeburn  5545:                 }
1.1332    raeburn  5546:             }
1.1335    raeburn  5547:             if (@liveroles) {
1.1332    raeburn  5548:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  5549:                     my ($accessref,$accessinfo,%access_in_dom);
                   5550:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   5551:                     if (ref($roles_by_num) eq 'ARRAY') {
                   5552:                         if (@{$roles_by_num}) {
1.1332    raeburn  5553:                             my %settings;
                   5554:                             if ($env{'request.course.id'} eq $cid) {
                   5555:                                 foreach my $envkey (keys(%env)) {
                   5556:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   5557:                                         $settings{$1} = $env{$envkey};
                   5558:                                     }
                   5559:                                 }
                   5560:                             } else {
                   5561:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   5562:                             }
                   5563:                             my %setincrs;
                   5564:                             if ($settings{'internal.adhocaccess'}) {
                   5565:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   5566:                             }
                   5567:                             my @statuses;
                   5568:                             if ($env{'environment.inststatus'}) {
                   5569:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   5570:                             }
                   5571:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  5572:                             if (ref($accessref) eq 'HASH') {
                   5573:                                 %access_in_dom = %{$accessref};
                   5574:                             }
                   5575:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  5576:                                 my ($curraccess,@okstatus,@personnel);
                   5577:                                 if ($setincrs{$role}) {
                   5578:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   5579:                                     if ($curraccess eq 'status') {
                   5580:                                         @okstatus = split(/\&/,$rest);
                   5581:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5582:                                         @personnel = split(/\&/,$rest);
                   5583:                                     }
                   5584:                                 } else {
                   5585:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  5586:                                     if (ref($accessinfo) eq 'HASH') {
                   5587:                                         if ($curraccess eq 'status') {
                   5588:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5589:                                                 @okstatus = @{$accessinfo->{$role}};
                   5590:                                             }
                   5591:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5592:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   5593:                                                 @personnel = @{$accessinfo->{$role}};
                   5594:                                             }
1.1332    raeburn  5595:                                         }
                   5596:                                     }
                   5597:                                 }
                   5598:                                 if ($curraccess eq 'none') {
                   5599:                                     next;
                   5600:                                 } elsif ($curraccess eq 'all') {
                   5601:                                     push(@possroles,$role);
1.1336    raeburn  5602:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  5603:                                     if (grep(/^dh$/,@liveroles)) {
                   5604:                                         push(@possroles,$role);
                   5605:                                     } else {
                   5606:                                         next;
                   5607:                                     }
1.1336    raeburn  5608:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  5609:                                     if (grep(/^da$/,@liveroles)) {
                   5610:                                         push(@possroles,$role);
                   5611:                                     } else {
                   5612:                                         next;
                   5613:                                     }
1.1332    raeburn  5614:                                 } elsif ($curraccess eq 'status') {
                   5615:                                     if (@okstatus) {
                   5616:                                         if (!@statuses) {
                   5617:                                             if (grep(/^default$/,@okstatus)) {
                   5618:                                                 push(@possroles,$role);
                   5619:                                             }
                   5620:                                         } else {
                   5621:                                             foreach my $status (@okstatus) {
                   5622:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   5623:                                                     push(@possroles,$role);
                   5624:                                                     last;
                   5625:                                                 }
                   5626:                                             }
                   5627:                                         }
                   5628:                                     }
                   5629:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   5630:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   5631:                                         if ($curraccess eq 'exc') {
                   5632:                                             push(@possroles,$role);
                   5633:                                         }
                   5634:                                     } elsif ($curraccess eq 'inc') {
                   5635:                                         push(@possroles,$role);
                   5636:                                     }
                   5637:                                 }
                   5638:                             }
                   5639:                         }
                   5640:                     }
                   5641:                 }
                   5642:             }
                   5643:         }
                   5644:     }
1.1333    raeburn  5645:     unless (ref($description) eq 'HASH') {
                   5646:         if (ref($roles_by_num) eq 'ARRAY') {
                   5647:             my %desc;
                   5648:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   5649:             $description = \%desc;
                   5650:         } else {
                   5651:             $description = {};
                   5652:         }
                   5653:     }
                   5654:     return (\@possroles,$description);
1.1332    raeburn  5655: }
                   5656: 
1.399     www      5657: # ----------------------------------------------------- Frontpage Announcements
                   5658: #
                   5659: #
                   5660: 
                   5661: sub postannounce {
                   5662:     my ($server,$text)=@_;
1.844     albertel 5663:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      5664:     unless ($text=~/\w/) { $text=''; }
                   5665:     return &reply('setannounce:'.&escape($text),$server);
                   5666: }
                   5667: 
                   5668: sub getannounce {
1.448     albertel 5669: 
1.1359    raeburn  5670:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      5671: 	my $announcement='';
1.800     albertel 5672: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 5673: 	close($fh);
1.399     www      5674: 	if ($announcement=~/\w/) { 
                   5675: 	    return 
                   5676:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 5677:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      5678: 	} else {
                   5679: 	    return '';
                   5680: 	}
                   5681:     } else {
                   5682: 	return '';
                   5683:     }
1.351     www      5684: }
1.353     www      5685: 
                   5686: # ---------------------------------------------------------- Course ID routines
                   5687: # Deal with domain's nohist_courseid.db files
                   5688: #
                   5689: 
                   5690: sub courseidput {
1.921     raeburn  5691:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  5692:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  5693:     my $outcome;
                   5694:     if ($caller eq 'timeonly') {
                   5695:         my $cids = '';
                   5696:         foreach my $item (keys(%$storehash)) {
                   5697:             $cids.=&escape($item).'&';
                   5698:         }
                   5699:         $cids=~s/\&$//;
                   5700:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   5701:                           $coursehome);       
                   5702:     } else {
                   5703:         my $items = '';
                   5704:         foreach my $item (keys(%$storehash)) {
                   5705:             $items.= &escape($item).'='.
                   5706:                      &freeze_escape($$storehash{$item}).'&';
                   5707:         }
                   5708:         $items=~s/\&$//;
                   5709:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   5710:                           $coursehome);
1.918     raeburn  5711:     }
                   5712:     if ($outcome eq 'unknown_cmd') {
                   5713:         my $what;
                   5714:         foreach my $cid (keys(%$storehash)) {
                   5715:             $what .= &escape($cid).'=';
1.921     raeburn  5716:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  5717:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  5718:             }
                   5719:             $what =~ s/\:$/&/;
                   5720:         }
                   5721:         $what =~ s/\&$//;  
                   5722:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   5723:     } else {
                   5724:         return $outcome;
                   5725:     }
1.353     www      5726: }
                   5727: 
                   5728: sub courseiddump {
1.921     raeburn  5729:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  5730:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  5731:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  5732:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  5733:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  5734:     my $as_hash = 1;
                   5735:     my %returnhash;
                   5736:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 5737:     my %libserv = &all_library();
                   5738:     foreach my $tryserver (keys(%libserv)) {
                   5739:         if ( (  $hostidflag == 1 
                   5740: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5741: 	     || (!defined($hostidflag)) ) {
                   5742: 
1.918     raeburn  5743: 	    if (($domfilter eq '') ||
                   5744: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 5745:                 my $rep;
                   5746:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   5747:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   5748:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   5749:                                 &escape($descfilter), &escape($instcodefilter), 
                   5750:                                 &escape($ownerfilter), &escape($coursefilter),
                   5751:                                 &escape($typefilter), &escape($regexp_ok), 
                   5752:                                 $as_hash, &escape($selfenrollonly), 
                   5753:                                 &escape($catfilter), $showhidden, $caller, 
                   5754:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   5755:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  5756:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5757:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 5758:                 } else {
                   5759:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5760:                              $sincefilter.':'.&escape($descfilter).':'.
                   5761:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5762:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5763:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5764:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5765:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5766:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5767:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  5768:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5769:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 5770:                 }
                   5771:                      
1.918     raeburn  5772:                 my @pairs=split(/\&/,$rep);
                   5773:                 foreach my $item (@pairs) {
                   5774:                     my ($key,$value)=split(/\=/,$item,2);
                   5775:                     $key = &unescape($key);
                   5776:                     next if ($key =~ /^error: 2 /);
                   5777:                     my $result = &thaw_unescape($value);
                   5778:                     if (ref($result) eq 'HASH') {
                   5779:                         $returnhash{$key}=$result;
                   5780:                     } else {
1.921     raeburn  5781:                         my @responses = split(/:/,$value);
                   5782:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5783:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5784:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5785:                         }
1.1008    raeburn  5786:                     }
1.353     www      5787:                 }
                   5788:             }
                   5789:         }
                   5790:     }
                   5791:     return %returnhash;
                   5792: }
                   5793: 
1.1055    raeburn  5794: sub courselastaccess {
                   5795:     my ($cdom,$cnum,$hostidref) = @_;
                   5796:     my %returnhash;
                   5797:     if ($cdom && $cnum) {
                   5798:         my $chome = &homeserver($cnum,$cdom);
                   5799:         if ($chome ne 'no_host') {
                   5800:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5801:             &extract_lastaccess(\%returnhash,$rep);
                   5802:         }
                   5803:     } else {
                   5804:         if (!$cdom) { $cdom=''; }
                   5805:         my %libserv = &all_library();
                   5806:         foreach my $tryserver (keys(%libserv)) {
                   5807:             if (ref($hostidref) eq 'ARRAY') {
                   5808:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5809:             } 
                   5810:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5811:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5812:                 &extract_lastaccess(\%returnhash,$rep);
                   5813:             }
                   5814:         }
                   5815:     }
                   5816:     return %returnhash;
                   5817: }
                   5818: 
                   5819: sub extract_lastaccess {
                   5820:     my ($returnhash,$rep) = @_;
                   5821:     if (ref($returnhash) eq 'HASH') {
                   5822:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5823:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5824:                  $rep eq '') {
                   5825:             my @pairs=split(/\&/,$rep);
                   5826:             foreach my $item (@pairs) {
                   5827:                 my ($key,$value)=split(/\=/,$item,2);
                   5828:                 $key = &unescape($key);
                   5829:                 next if ($key =~ /^error: 2 /);
                   5830:                 $returnhash->{$key} = &thaw_unescape($value);
                   5831:             }
                   5832:         }
                   5833:     }
                   5834:     return;
                   5835: }
                   5836: 
1.658     raeburn  5837: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5838: 
                   5839: sub dcmailput {
1.685     raeburn  5840:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5841:     my $status = &Apache::lonnet::critical(
1.740     www      5842:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5843:        &escape($message),$server);
1.662     raeburn  5844:     return $status;
                   5845: }
                   5846: 
1.658     raeburn  5847: sub dcmaildump {
                   5848:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5849:     my %returnhash=();
1.846     albertel 5850: 
                   5851:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5852:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5853:                                                          &escape($enddate).':';
                   5854: 	my @esc_senders=map { &escape($_)} @$senders;
                   5855: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5856: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5857:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5858:             if (($key) && ($value)) {
                   5859:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5860:             }
                   5861:         }
                   5862:     }
                   5863:     return %returnhash;
                   5864: }
1.662     raeburn  5865: # ---------------------------------------------------------- Domain roles
                   5866: 
                   5867: sub get_domain_roles {
                   5868:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5869:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5870:         $startdate = '.';
                   5871:     }
1.1018    raeburn  5872:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5873:         $enddate = '.';
                   5874:     }
1.922     raeburn  5875:     my $rolelist;
                   5876:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  5877:         $rolelist = join('&',@{$roles});
1.922     raeburn  5878:     }
1.662     raeburn  5879:     my %personnel = ();
1.841     albertel 5880: 
                   5881:     my %servers = &get_servers($dom,'library');
                   5882:     foreach my $tryserver (keys(%servers)) {
                   5883: 	%{$personnel{$tryserver}}=();
                   5884: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5885: 					    &escape($startdate).':'.
                   5886: 					    &escape($enddate).':'.
                   5887: 					    &escape($rolelist), $tryserver))) {
                   5888: 	    my ($key,$value) = split(/\=/,$line,2);
                   5889: 	    if (($key) && ($value)) {
                   5890: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5891: 	    }
                   5892: 	}
1.662     raeburn  5893:     }
                   5894:     return %personnel;
                   5895: }
1.658     raeburn  5896: 
1.1332    raeburn  5897: sub get_active_domroles {
                   5898:     my ($dom,$roles) = @_;
                   5899:     return () unless (ref($roles) eq 'ARRAY');
                   5900:     my $now = time;
                   5901:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5902:     my %domroles;
                   5903:     foreach my $server (keys(%dompersonnel)) {
                   5904:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5905:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5906:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5907:         }
                   5908:     }
                   5909:     return %domroles;
                   5910: }
                   5911: 
1.1057    www      5912: # ----------------------------------------------------------- Interval timing 
1.149     www      5913: 
1.1153    www      5914: {
                   5915: # Caches needed for speedup of navmaps
                   5916: # We don't want to cache this for very long at all (5 seconds at most)
                   5917: # 
                   5918: # The user for whom we cache
                   5919: my $cachedkey='';
                   5920: # The cached times for this user
                   5921: my %cachedtimes=();
                   5922: # When this was last done
1.1282    raeburn  5923: my $cachedtime='';
1.1153    www      5924: 
                   5925: sub load_all_first_access {
1.1308    raeburn  5926:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5927:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  5928:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5929:         (!$ignorecache)) {
1.1154    raeburn  5930:         return;
                   5931:     }
                   5932:     $cachedtime=time;
                   5933:     $cachedkey=$uname.':'.$udom;
                   5934:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5935: }
                   5936: 
1.504     albertel 5937: sub get_first_access {
1.1308    raeburn  5938:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5939:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5940:     if ($argsymb) { $symb=$argsymb; }
                   5941:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5942:     if ($argmap) { $map = $argmap; }
1.926     albertel 5943:     if ($type eq 'course') {
                   5944: 	$res='course';
                   5945:     } elsif ($type eq 'map') {
1.588     albertel 5946: 	$res=&symbread($map);
                   5947:     } else {
                   5948: 	$res=$symb;
                   5949:     }
1.1308    raeburn  5950:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5951:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5952: }
                   5953: 
                   5954: sub set_first_access {
1.1162    raeburn  5955:     my ($type,$interval)=@_;
1.790     albertel 5956:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5957:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5958:     if ($type eq 'course') {
                   5959: 	$res='course';
                   5960:     } elsif ($type eq 'map') {
1.588     albertel 5961: 	$res=&symbread($map);
                   5962:     } else {
                   5963: 	$res=$symb;
                   5964:     }
1.1153    www      5965:     $cachedkey='';
1.1162    raeburn  5966:     my $firstaccess=&get_first_access($type,$symb,$map);
1.1386    raeburn  5967:     if ($firstaccess) {
                   5968:         &logthis("First access time already set ($firstaccess) when attempting ".
1.1393    raeburn  5969:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
                   5970:                  "in $courseid");
1.1386    raeburn  5971:         return 'already_set';
                   5972:     } else {
1.1162    raeburn  5973:         my $start = time;
                   5974: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5975:                           $udom,$uname);
                   5976:         if ($putres eq 'ok') {
                   5977:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5978:                  $udom,$uname); 
                   5979:             &appenv(
                   5980:                      {
                   5981:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5982:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5983:                      }
                   5984:                   );
1.1365    raeburn  5985:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5986:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5987:             }
1.1386    raeburn  5988:         } elsif ($putres ne 'refused') {
                   5989:             &logthis("Result: $putres when attempting to set first access time ".
                   5990:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
1.1162    raeburn  5991:         }
                   5992:         return $putres;
1.505     albertel 5993:     }
                   5994:     return 'already_set';
1.504     albertel 5995: }
1.1153    www      5996: }
1.1282    raeburn  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.1434    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.1434    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.1434    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.1269    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.1434    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.1269    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.1269    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.1434    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.1269    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.1224    raeburn  6447:         return if ($namespace eq 'courserequests');
                   6448:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 6449:     } else {
1.1224    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.1219    raeburn  6587:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 6588:     my $now = time;
1.1219    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.1275    musolffc 6615:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 6616:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  6617:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 6618:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  6619:                         or ($tstart && $tstart > $now);
1.1170    droeschl 6620:             }
1.1219    raeburn  6621:         }
                   6622:     }
                   6623:     return 0;
                   6624: }
1.1170    droeschl 6625: 
1.1219    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;
1.9       www      6674: }
1.1       albertel 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.1274    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.1341    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.1341    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.1215    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.1215    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.1250    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.1332    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.1332    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"})) {
                   6843:              next if ($item eq '');
                   6844:              my ($rule,$rest) = split(/=/,$item);
                   6845:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6846:              foreach my $priv (split(/:/,$rest)) {
                   6847:                  if ($priv ne '') {
                   6848:                      if ($rule eq 'off') {
                   6849:                          $possremove{$priv} = 1;
                   6850:                      } else {
                   6851:                          $possadd{$priv} = 1;
                   6852:                      }
                   6853:                  }
                   6854:              }
                   6855:          }
                   6856:          foreach my $priv (sort(keys(%full))) {
                   6857:              if (exists($currprivs{$priv})) {
                   6858:                  unless (exists($possremove{$priv})) {
                   6859:                      $storeprivs{$priv} = $currprivs{$priv};
                   6860:                  }
                   6861:              } elsif (exists($possadd{$priv})) {
                   6862:                  $storeprivs{$priv} = $full{$priv};
                   6863:              }
                   6864:          }
                   6865:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6866:      }
                   6867:      return $coursepriv;
                   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.1341    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.1341    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.1341    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.1250    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.1251    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.1341    raeburn  7006:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   7007:                                                                    \%groups_roles);
1.1064    raeburn  7008:                             &appenv(\%userroles,\@rolecodes);
1.1342    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.1329    raeburn  7085:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  7086:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  7087:     if ($sec) {
                   7088:         $cckey .= '/'.$sec;
                   7089:     } 
1.1185    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.1329    raeburn  7095:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  7096:             $setprivs = 1;
1.994     raeburn  7097:         }
                   7098:     } else {
1.1330    raeburn  7099:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  7100:         $setprivs = 1;
1.994     raeburn  7101:     }
1.1185    raeburn  7102:     return $setprivs;
1.994     raeburn  7103: }
                   7104: 
                   7105: sub set_adhoc_privileges {
1.1326    raeburn  7106: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  7107:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  7108:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    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.1215    raeburn  7114:                                   $env{'user.name'},1);
1.1326    raeburn  7115:     my %rolehash = ();
1.1332    raeburn  7116:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   7117:         my $rolename = $1;
1.1326    raeburn  7118:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    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.1326    raeburn  7125:     } else {
                   7126:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   7127:     }
1.1341    raeburn  7128:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  7129:     &appenv(\%userroles,[$role,'cm']);
1.1342    raeburn  7130:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1402    raeburn  7131:     unless (($caller eq 'constructaccess' && $env{'request.course.id'}) ||
                   7132:             ($caller eq 'tiny')) {
1.1088    raeburn  7133:         &appenv( {'request.role'        => $spec,
                   7134:                   'request.role.domain' => $dcdom,
1.1332    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.1180    droeschl 7189: sub unserialize {
                   7190:     my ($rep, $escapedkeys) = @_;
                   7191: 
                   7192:     return {} if $rep =~ /^error/;
                   7193: 
                   7194:     my %returnhash=();
1.1252    raeburn  7195: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 7196: 	    my ($key, $value) = split(/=/, $item, 2);
                   7197: 	    $key = unescape($key) unless $escapedkeys;
                   7198: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  7199: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 7200: 	}
                   7201:     #return %returnhash;
                   7202:     return \%returnhash;
                   7203: }        
                   7204: 
                   7205: # see Lond::dump_with_regexp
                   7206: # if $escapedkeys hash keys won't get unescaped.
1.15      www      7207: sub dump {
1.1462    raeburn  7208:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys,$encrypt)=@_;
1.755     albertel 7209:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7210:     if (!$uname) { $uname=$env{'user.name'}; }
                   7211:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 7212: 
1.1266    raeburn  7213:     if ($regexp) {
                   7214:         $regexp=&escape($regexp);
                   7215:     } else {
                   7216:         $regexp='.';
                   7217:     }
1.1180    droeschl 7218:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   7219:         # user is hosted on this machine
1.1266    raeburn  7220:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  7221:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 7222:         return %{unserialize($reply, $escapedkeys)};
                   7223:     }
1.1462    raeburn  7224:     my $rep;
                   7225:     if ($encrypt) {
                   7226:         $rep=&reply("encrypt:edump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.1463    raeburn  7227:     } else {
1.1462    raeburn  7228:         $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   7229:     }
1.755     albertel 7230:     my @pairs=split(/\&/,$rep);
                   7231:     my %returnhash=();
1.1098    foxr     7232:     if (!($rep =~ /^error/ )) {
                   7233: 	foreach my $item (@pairs) {
                   7234: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 7235:         $key = unescape($key) unless $escapedkeys;
                   7236:         #$key = &unescape($key);
1.1098    foxr     7237: 	    next if ($key =~ /^error: 2 /);
                   7238: 	    $returnhash{$key}=&thaw_unescape($value);
                   7239: 	}
1.755     albertel 7240:     }
                   7241:     return %returnhash;
1.407     www      7242: }
                   7243: 
1.1098    foxr     7244: 
1.717     albertel 7245: # --------------------------------------------------------- dumpstore interface
                   7246: 
                   7247: sub dumpstore {
                   7248:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 7249:    # same as dump but keys must be escaped. They may contain colon separated
                   7250:    # lists of values that may themself contain colons (e.g. symbs).
                   7251:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 7252: }
                   7253: 
1.407     www      7254: # -------------------------------------------------------------- keys interface
                   7255: 
                   7256: sub getkeys {
                   7257:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 7258:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7259:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      7260:    my $uhome=&homeserver($uname,$udomain);
                   7261:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   7262:    my @keyarray=();
1.800     albertel 7263:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  7264:       next if ($key =~ /^error: 2 /);
1.800     albertel 7265:       push(@keyarray,&unescape($key));
1.407     www      7266:    }
                   7267:    return @keyarray;
1.318     matthew  7268: }
                   7269: 
1.319     matthew  7270: # --------------------------------------------------------------- currentdump
                   7271: sub currentdump {
1.328     matthew  7272:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 7273:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   7274:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   7275:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  7276:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 7277:    my $rep;
                   7278: 
                   7279:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   7280:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   7281:                    $courseid)));
                   7282:    } else {
                   7283:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   7284:    }
                   7285: 
1.318     matthew  7286:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  7287:    #
1.318     matthew  7288:    my %returnhash=();
1.319     matthew  7289:    #
1.1343    raeburn  7290:    if ($rep eq 'unknown_cmd') {
1.319     matthew  7291:        # an old lond will not know currentdump
                   7292:        # Do a dump and make it look like a currentdump
1.822     albertel 7293:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  7294:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   7295:        my %hash = @tmp;
                   7296:        @tmp=();
1.424     matthew  7297:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  7298:    } else {
                   7299:        my @pairs=split(/\&/,$rep);
1.800     albertel 7300:        foreach my $pair (@pairs) {
                   7301:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  7302:            my ($symb,$param) = split(/:/,$key);
                   7303:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 7304:                                                         &thaw_unescape($value);
1.319     matthew  7305:        }
1.191     harris41 7306:    }
1.12      www      7307:    return %returnhash;
1.424     matthew  7308: }
                   7309: 
                   7310: sub convert_dump_to_currentdump{
                   7311:     my %hash = %{shift()};
                   7312:     my %returnhash;
                   7313:     # Code ripped from lond, essentially.  The only difference
                   7314:     # here is the unescaping done by lonnet::dump().  Conceivably
                   7315:     # we might run in to problems with parameter names =~ /^v\./
                   7316:     while (my ($key,$value) = each(%hash)) {
                   7317:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 7318: 	$symb  = &unescape($symb);
                   7319: 	$param = &unescape($param);
1.424     matthew  7320:         next if ($v eq 'version' || $symb eq 'keys');
                   7321:         next if (exists($returnhash{$symb}) &&
                   7322:                  exists($returnhash{$symb}->{$param}) &&
                   7323:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   7324:         $returnhash{$symb}->{$param}=$value;
                   7325:         $returnhash{$symb}->{'v.'.$param}=$v;
                   7326:     }
                   7327:     #
                   7328:     # Remove all of the keys in the hashes which keep track of
                   7329:     # the version of the parameter.
                   7330:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   7331:         # use a foreach because we are going to delete from the hash.
                   7332:         foreach my $key (keys(%$param_hash)) {
                   7333:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   7334:         }
                   7335:     }
                   7336:     return \%returnhash;
1.12      www      7337: }
                   7338: 
1.627     albertel 7339: # ------------------------------------------------------ critical inc interface
                   7340: 
                   7341: sub cinc {
                   7342:     return &inc(@_,'critical');
                   7343: }
                   7344: 
1.449     matthew  7345: # --------------------------------------------------------------- inc interface
                   7346: 
                   7347: sub inc {
1.627     albertel 7348:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 7349:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7350:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  7351:     my $uhome=&homeserver($uname,$udomain);
                   7352:     my $items='';
                   7353:     if (! ref($store)) {
                   7354:         # got a single value, so use that instead
                   7355:         $items = &escape($store).'=&';
                   7356:     } elsif (ref($store) eq 'SCALAR') {
                   7357:         $items = &escape($$store).'=&';        
                   7358:     } elsif (ref($store) eq 'ARRAY') {
                   7359:         $items = join('=&',map {&escape($_);} @{$store});
                   7360:     } elsif (ref($store) eq 'HASH') {
                   7361:         while (my($key,$value) = each(%{$store})) {
                   7362:             $items.= &escape($key).'='.&escape($value).'&';
                   7363:         }
                   7364:     }
                   7365:     $items=~s/\&$//;
1.627     albertel 7366:     if ($critical) {
                   7367: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7368:     } else {
                   7369: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   7370:     }
1.449     matthew  7371: }
                   7372: 
1.12      www      7373: # --------------------------------------------------------------- put interface
                   7374: 
                   7375: sub put {
1.1462    raeburn  7376:    my ($namespace,$storehash,$udomain,$uname,$encrypt)=@_;
1.620     albertel 7377:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7378:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7379:    my $uhome=&homeserver($uname,$udomain);
1.12      www      7380:    my $items='';
1.800     albertel 7381:    foreach my $item (keys(%$storehash)) {
                   7382:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7383:    }
1.12      www      7384:    $items=~s/\&$//;
1.1462    raeburn  7385:    if ($encrypt) {
                   7386:        return &reply("encrypt:put:$udomain:$uname:$namespace:$items",$uhome);
                   7387:    } else {
                   7388:        return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
                   7389:    }
1.47      www      7390: }
                   7391: 
1.631     albertel 7392: # ------------------------------------------------------------ newput interface
                   7393: 
                   7394: sub newput {
                   7395:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   7396:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7397:    if (!$uname) { $uname=$env{'user.name'}; }
                   7398:    my $uhome=&homeserver($uname,$udomain);
                   7399:    my $items='';
                   7400:    foreach my $key (keys(%$storehash)) {
                   7401:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7402:    }
                   7403:    $items=~s/\&$//;
                   7404:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   7405: }
                   7406: 
                   7407: # ---------------------------------------------------------  putstore interface
                   7408: 
1.524     raeburn  7409: sub putstore {
1.1269    raeburn  7410:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 7411:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7412:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  7413:    my $uhome=&homeserver($uname,$udomain);
                   7414:    my $items='';
1.715     albertel 7415:    foreach my $key (keys(%$storehash)) {
                   7416:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  7417:    }
1.715     albertel 7418:    $items=~s/\&$//;
1.716     albertel 7419:    my $esc_symb=&escape($symb);
                   7420:    my $esc_v=&escape($version);
1.715     albertel 7421:    my $reply =
1.716     albertel 7422:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 7423: 	      $uhome);
1.1269    raeburn  7424:    if (($tolog) && ($reply eq 'ok')) {
                   7425:        my $namevalue='';
                   7426:        foreach my $key (keys(%{$storehash})) {
                   7427:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   7428:        }
1.1434    raeburn  7429:        my $ip = &get_requestor_ip();
                   7430:        $namevalue .= 'ip='.&escape($ip).
1.1269    raeburn  7431:                      '&host='.&escape($perlvar{'lonHostID'}).
                   7432:                      '&version='.$esc_v.
                   7433:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   7434:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   7435:    }
1.715     albertel 7436:    if ($reply eq 'unknown_cmd') {
1.716     albertel 7437:        # gfall back to way things use to be done
1.715     albertel 7438:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   7439: 			    $uname);
1.524     raeburn  7440:    }
1.715     albertel 7441:    return $reply;
                   7442: }
                   7443: 
                   7444: sub old_putstore {
1.716     albertel 7445:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   7446:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7447:     if (!$uname) { $uname=$env{'user.name'}; }
                   7448:     my $uhome=&homeserver($uname,$udomain);
                   7449:     my %newstorehash;
1.800     albertel 7450:     foreach my $item (keys(%$storehash)) {
                   7451: 	my $key = $version.':'.&escape($symb).':'.$item;
                   7452: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 7453:     }
                   7454:     my $items='';
                   7455:     my %allitems = ();
1.800     albertel 7456:     foreach my $item (keys(%newstorehash)) {
                   7457: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 7458: 	    my $key = $1.':keys:'.$2;
                   7459: 	    $allitems{$key} .= $3.':';
                   7460: 	}
1.800     albertel 7461: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 7462:     }
1.800     albertel 7463:     foreach my $item (keys(%allitems)) {
                   7464: 	$allitems{$item} =~ s/\:$//;
                   7465: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 7466:     }
                   7467:     $items=~s/\&$//;
                   7468:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  7469: }
                   7470: 
1.47      www      7471: # ------------------------------------------------------ critical put interface
                   7472: 
                   7473: sub cput {
1.134     albertel 7474:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 7475:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7476:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 7477:    my $uhome=&homeserver($uname,$udomain);
1.47      www      7478:    my $items='';
1.800     albertel 7479:    foreach my $item (keys(%$storehash)) {
                   7480:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 7481:    }
1.47      www      7482:    $items=~s/\&$//;
1.134     albertel 7483:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7484: }
                   7485: 
                   7486: # -------------------------------------------------------------- eget interface
                   7487: 
                   7488: sub eget {
1.133     albertel 7489:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      7490:    my $items='';
1.800     albertel 7491:    foreach my $item (@$storearr) {
                   7492:        $items.=&escape($item).'&';
1.191     harris41 7493:    }
1.12      www      7494:    $items=~s/\&$//;
1.620     albertel 7495:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   7496:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 7497:    my $uhome=&homeserver($uname,$udomain);
                   7498:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      7499:    my @pairs=split(/\&/,$rep);
                   7500:    my %returnhash=();
1.42      www      7501:    my $i=0;
1.800     albertel 7502:    foreach my $item (@$storearr) {
                   7503:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      7504:       $i++;
1.191     harris41 7505:    }
1.12      www      7506:    return %returnhash;
                   7507: }
                   7508: 
1.667     albertel 7509: # ------------------------------------------------------------ tmpput interface
                   7510: sub tmpput {
1.802     raeburn  7511:     my ($storehash,$server,$context)=@_;
1.667     albertel 7512:     my $items='';
1.800     albertel 7513:     foreach my $item (keys(%$storehash)) {
                   7514: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 7515:     }
                   7516:     $items=~s/\&$//;
1.802     raeburn  7517:     if (defined($context)) {
                   7518:         $items .= ':'.&escape($context);
                   7519:     }
1.667     albertel 7520:     return &reply("tmpput:$items",$server);
                   7521: }
                   7522: 
                   7523: # ------------------------------------------------------------ tmpget interface
                   7524: sub tmpget {
1.688     albertel 7525:     my ($token,$server)=@_;
                   7526:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7527:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 7528:     my %returnhash;
1.1328    raeburn  7529:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   7530:         return %returnhash;
                   7531:     }
1.667     albertel 7532:     foreach my $item (split(/\&/,$rep)) {
                   7533: 	my ($key,$value)=split(/=/,$item);
                   7534: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   7535:     }
                   7536:     return %returnhash;
                   7537: }
                   7538: 
1.1113    raeburn  7539: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 7540: sub tmpdel {
                   7541:     my ($token,$server)=@_;
                   7542:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   7543:     return &reply("tmpdel:$token",$server);
                   7544: }
                   7545: 
1.1198    raeburn  7546: # ------------------------------------------------------------ get_timebased_id 
                   7547: 
                   7548: sub get_timebased_id {
                   7549:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   7550:         $maxtries) = @_;
                   7551:     my ($newid,$error,$dellock);
                   7552:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   7553:         return ('','ok','invalid call to get suffix');
                   7554:     }
                   7555: 
                   7556: # set defaults for any optional args for which values were not supplied
                   7557:     if ($who eq '') {
                   7558:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   7559:     }
                   7560:     if (!$locktries) {
                   7561:         $locktries = 3;
                   7562:     }
                   7563:     if (!$maxtries) {
                   7564:         $maxtries = 10;
                   7565:     }
                   7566:     
                   7567:     if (($cdom eq '') || ($cnum eq '')) {
                   7568:         if ($env{'request.course.id'}) {
                   7569:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7570:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7571:         }
                   7572:         if (($cdom eq '') || ($cnum eq '')) {
                   7573:             return ('','ok','call to get suffix not in course context');
                   7574:         }
                   7575:     }
                   7576: 
                   7577: # construct locking item
                   7578:     my $lockhash = {
                   7579:                       $prefix."\0".'locked_'.$keyid => $who,
                   7580:                    };
                   7581:     my $tries = 0;
                   7582: 
                   7583: # attempt to get lock on nohist_$namespace file
                   7584:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7585:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   7586:         $tries ++;
                   7587:         sleep 1;
                   7588:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   7589:     }
                   7590: 
                   7591: # attempt to get unique identifier, based on current timestamp
                   7592:     if ($gotlock eq 'ok') {
                   7593:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   7594:         my $id = time;
                   7595:         $newid = $id;
1.1268    raeburn  7596:         if ($idtype eq 'addcode') {
                   7597:             $newid .= &sixnum_code();
                   7598:         }
1.1198    raeburn  7599:         my $idtries = 0;
                   7600:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   7601:             if ($idtype eq 'concat') {
                   7602:                 $newid = $id.$idtries;
1.1268    raeburn  7603:             } elsif ($idtype eq 'addcode') {
                   7604:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  7605:             } else {
                   7606:                 $newid ++;
                   7607:             }
                   7608:             $idtries ++;
                   7609:         }
                   7610:         if (!exists($inuse{$prefix."\0".$newid})) {
                   7611:             my %new_item =  (
                   7612:                               $prefix."\0".$newid => $who,
                   7613:                             );
                   7614:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   7615:                                                  $cdom,$cnum);
                   7616:             if ($putresult ne 'ok') {
                   7617:                 undef($newid);
                   7618:                 $error = 'error saving new item: '.$putresult;
                   7619:             }
                   7620:         } else {
1.1268    raeburn  7621:              undef($newid);
1.1198    raeburn  7622:              $error = ('error: no unique suffix available for the new item ');
                   7623:         }
                   7624: #  remove lock
                   7625:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   7626:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   7627:     } else {
                   7628:         $error = "error: could not obtain lockfile\n";
                   7629:         $dellock = 'ok';
1.1276    raeburn  7630:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   7631:             $dellock = 'nolock';
                   7632:         }
1.1198    raeburn  7633:     }
                   7634:     return ($newid,$dellock,$error);
                   7635: }
                   7636: 
1.1268    raeburn  7637: sub sixnum_code {
                   7638:     my $code;
                   7639:     for (0..6) {
                   7640:         $code .= int( rand(9) );
                   7641:     }
                   7642:     return $code;
                   7643: }
                   7644: 
1.765     albertel 7645: # -------------------------------------------------- portfolio access checking
                   7646: 
                   7647: sub portfolio_access {
1.1270    raeburn  7648:     my ($requrl,$clientip) = @_;
1.765     albertel 7649:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  7650:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  7651:     if ($result) {
                   7652:         my %setters;
                   7653:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
1.1473    raeburn  7654:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
                   7655:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip,$unum,$udom);
                   7656:             if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  7657:                 return 'B';
                   7658:             }
                   7659:         } else {
1.1473    raeburn  7660:             my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) =
                   7661:                 &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   7662:             if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  7663:                 return 'B';
                   7664:             }
                   7665:         }
                   7666:     }
1.765     albertel 7667:     if ($result eq 'ok') {
1.766     albertel 7668:        return 'F';
1.765     albertel 7669:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 7670:        return 'A';
1.765     albertel 7671:     }
1.766     albertel 7672:     return '';
1.765     albertel 7673: }
                   7674: 
                   7675: sub get_portfolio_access {
1.1270    raeburn  7676:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 7677: 
                   7678:     if (!ref($access_hash)) {
                   7679: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   7680: 	my %access_controls = &get_access_controls($current_perms,$group,
                   7681: 						   $file_name);
                   7682: 	$access_hash = $access_controls{$file_name};
                   7683:     }
                   7684: 
1.1270    raeburn  7685:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 7686:     my $now = time;
                   7687:     if (ref($access_hash) eq 'HASH') {
                   7688:         foreach my $key (keys(%{$access_hash})) {
                   7689:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   7690:             if ($start > $now) {
                   7691:                 next;
                   7692:             }
                   7693:             if ($end && $end<$now) {
                   7694:                 next;
                   7695:             }
                   7696:             if ($scope eq 'public') {
                   7697:                 $public = $key;
                   7698:                 last;
                   7699:             } elsif ($scope eq 'guest') {
                   7700:                 $guest = $key;
                   7701:             } elsif ($scope eq 'domains') {
                   7702:                 push(@domains,$key);
                   7703:             } elsif ($scope eq 'users') {
                   7704:                 push(@users,$key);
                   7705:             } elsif ($scope eq 'course') {
                   7706:                 push(@courses,$key);
                   7707:             } elsif ($scope eq 'group') {
                   7708:                 push(@groups,$key);
1.1270    raeburn  7709:             } elsif ($scope eq 'ip') {
                   7710:                 push(@ips,$key);
1.765     albertel 7711:             }
                   7712:         }
                   7713:         if ($public) {
                   7714:             return 'ok';
1.1270    raeburn  7715:         } elsif (@ips > 0) {
                   7716:             my $allowed;
                   7717:             foreach my $ipkey (@ips) {
                   7718:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   7719:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   7720:                         $allowed = 1;
                   7721:                         last; 
                   7722:                     }
                   7723:                 }
                   7724:             }
                   7725:             if ($allowed) {
                   7726:                 return 'ok';
                   7727:             }
1.765     albertel 7728:         }
                   7729:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   7730:             if ($guest) {
                   7731:                 return $guest;
                   7732:             }
                   7733:         } else {
                   7734:             if (@domains > 0) {
                   7735:                 foreach my $domkey (@domains) {
                   7736:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   7737:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   7738:                             return 'ok';
                   7739:                         }
                   7740:                     }
                   7741:                 }
                   7742:             }
                   7743:             if (@users > 0) {
                   7744:                 foreach my $userkey (@users) {
1.865     raeburn  7745:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   7746:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   7747:                             if (ref($item) eq 'HASH') {
                   7748:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   7749:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   7750:                                     return 'ok';
                   7751:                                 }
                   7752:                             }
                   7753:                         }
                   7754:                     } 
1.765     albertel 7755:                 }
                   7756:             }
                   7757:             my %roleshash;
                   7758:             my @courses_and_groups = @courses;
                   7759:             push(@courses_and_groups,@groups); 
                   7760:             if (@courses_and_groups > 0) {
                   7761:                 my (%allgroups,%allroles); 
                   7762:                 my ($start,$end,$role,$sec,$group);
                   7763:                 foreach my $envkey (%env) {
1.1060    raeburn  7764:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7765:                         my $cid = $2.'_'.$3; 
                   7766:                         if ($1 eq 'gr') {
                   7767:                             $group = $4;
                   7768:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7769:                         } else {
                   7770:                             if ($4 eq '') {
                   7771:                                 $sec = 'none';
                   7772:                             } else {
                   7773:                                 $sec = $4;
                   7774:                             }
                   7775:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7776:                         }
1.811     albertel 7777:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7778:                         my $cid = $2.'_'.$3;
                   7779:                         if ($4 eq '') {
                   7780:                             $sec = 'none';
                   7781:                         } else {
                   7782:                             $sec = $4;
                   7783:                         }
                   7784:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7785:                     }
                   7786:                 }
                   7787:                 if (keys(%allroles) == 0) {
                   7788:                     return;
                   7789:                 }
                   7790:                 foreach my $key (@courses_and_groups) {
                   7791:                     my %content = %{$$access_hash{$key}};
                   7792:                     my $cnum = $content{'number'};
                   7793:                     my $cdom = $content{'domain'};
                   7794:                     my $cid = $cdom.'_'.$cnum;
                   7795:                     if (!exists($allroles{$cid})) {
                   7796:                         next;
                   7797:                     }    
                   7798:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7799:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7800:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7801:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7802:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7803:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7804:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7805:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7806:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7807:                                         if (grep/^all$/,@sections) {
                   7808:                                             return 'ok';
                   7809:                                         } else {
                   7810:                                             if (grep/^$sec$/,@sections) {
                   7811:                                                 return 'ok';
                   7812:                                             }
                   7813:                                         }
                   7814:                                     }
                   7815:                                 }
                   7816:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7817:                                     if (grep/^none$/,@groups) {
                   7818:                                         return 'ok';
                   7819:                                     }
                   7820:                                 } else {
                   7821:                                     if (grep/^all$/,@groups) {
                   7822:                                         return 'ok';
                   7823:                                     } 
                   7824:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7825:                                         if (grep/^$group$/,@groups) {
                   7826:                                             return 'ok';
                   7827:                                         }
                   7828:                                     }
                   7829:                                 } 
                   7830:                             }
                   7831:                         }
                   7832:                     }
                   7833:                 }
                   7834:             }
                   7835:             if ($guest) {
                   7836:                 return $guest;
                   7837:             }
                   7838:         }
                   7839:     }
                   7840:     return;
                   7841: }
                   7842: 
                   7843: sub course_group_datechecker {
                   7844:     my ($dates,$now,$status) = @_;
                   7845:     my ($start,$end) = split(/\./,$dates);
                   7846:     if (!$start && !$end) {
                   7847:         return 'ok';
                   7848:     }
                   7849:     if (grep/^active$/,@{$status}) {
                   7850:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7851:             return 'ok';
                   7852:         }
                   7853:     }
                   7854:     if (grep/^previous$/,@{$status}) {
                   7855:         if ($end > $now ) {
                   7856:             return 'ok';
                   7857:         }
                   7858:     }
                   7859:     if (grep/^future$/,@{$status}) {
                   7860:         if ($start > $now) {
                   7861:             return 'ok';
                   7862:         }
                   7863:     }
                   7864:     return; 
                   7865: }
                   7866: 
                   7867: sub parse_portfolio_url {
                   7868:     my ($url) = @_;
                   7869: 
                   7870:     my ($type,$udom,$unum,$group,$file_name);
                   7871:     
1.823     albertel 7872:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7873: 	$type = 1;
                   7874:         $udom = $1;
                   7875:         $unum = $2;
                   7876:         $file_name = $3;
1.823     albertel 7877:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7878: 	$type = 2;
                   7879:         $udom = $1;
                   7880:         $unum = $2;
                   7881:         $group = $3;
                   7882:         $file_name = $3.'/'.$4;
                   7883:     }
                   7884:     if (wantarray) {
                   7885: 	return ($type,$udom,$unum,$file_name,$group);
                   7886:     }
                   7887:     return $type;
                   7888: }
                   7889: 
                   7890: sub is_portfolio_url {
                   7891:     my ($url) = @_;
                   7892:     return scalar(&parse_portfolio_url($url));
                   7893: }
                   7894: 
1.798     raeburn  7895: sub is_portfolio_file {
                   7896:     my ($file) = @_;
1.820     raeburn  7897:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7898:         return 1;
                   7899:     }
                   7900:     return;
                   7901: }
                   7902: 
1.976     raeburn  7903: sub usertools_access {
1.1084    raeburn  7904:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7905:     my ($access,%tools);
                   7906:     if ($context eq '') {
                   7907:         $context = 'tools';
                   7908:     }
                   7909:     if ($context eq 'requestcourses') {
                   7910:         %tools = (
                   7911:                       official   => 1,
                   7912:                       unofficial => 1,
1.1006    raeburn  7913:                       community  => 1,
1.1246    raeburn  7914:                       textbook   => 1,
1.1305    raeburn  7915:                       placement  => 1,
1.1368    raeburn  7916:                       lti        => 1,
1.985     raeburn  7917:                  );
1.1183    raeburn  7918:     } elsif ($context eq 'requestauthor') {
                   7919:         %tools = (
                   7920:                       requestauthor => 1,
                   7921:                  );
1.985     raeburn  7922:     } else {
                   7923:         %tools = (
                   7924:                       aboutme   => 1,
                   7925:                       blog      => 1,
1.1177    raeburn  7926:                       webdav    => 1,
1.985     raeburn  7927:                       portfolio => 1,
                   7928:                  );
                   7929:     }
1.976     raeburn  7930:     return if (!defined($tools{$tool}));
                   7931: 
1.1242    raeburn  7932:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7933:         $udom = $env{'user.domain'};
                   7934:         $uname = $env{'user.name'};
                   7935:     }
                   7936: 
1.978     raeburn  7937:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7938:         if ($action ne 'reload') {
1.985     raeburn  7939:             if ($context eq 'requestcourses') {
                   7940:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  7941:             } elsif ($context eq 'requestauthor') {
                   7942:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7943:             } else {
                   7944:                 return $env{'environment.availabletools.'.$tool};
                   7945:             }
                   7946:         }
1.976     raeburn  7947:     }
                   7948: 
1.1183    raeburn  7949:     my ($toolstatus,$inststatus,$envkey);
                   7950:     if ($context eq 'requestauthor') {
                   7951:         $envkey = $context; 
                   7952:     } else {
                   7953:         $envkey = $context.'.'.$tool;
                   7954:     }
1.976     raeburn  7955: 
1.985     raeburn  7956:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7957:          ($action ne 'reload')) {
1.1183    raeburn  7958:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7959:         $inststatus = $env{'environment.inststatus'};
                   7960:     } else {
1.1084    raeburn  7961:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  7962:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7963:             $inststatus = $userenvref->{'inststatus'};
                   7964:         } else {
1.1183    raeburn  7965:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7966:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7967:             $inststatus = $userenv{'inststatus'};
                   7968:         }
1.976     raeburn  7969:     }
                   7970: 
                   7971:     if ($toolstatus ne '') {
                   7972:         if ($toolstatus) {
                   7973:             $access = 1;
                   7974:         } else {
                   7975:             $access = 0;
                   7976:         }
                   7977:         return $access;
                   7978:     }
                   7979: 
1.1084    raeburn  7980:     my ($is_adv,%domdef);
                   7981:     if (ref($is_advref) eq 'HASH') {
                   7982:         $is_adv = $is_advref->{'is_adv'};
                   7983:     } else {
                   7984:         $is_adv = &is_advanced_user($udom,$uname);
                   7985:     }
                   7986:     if (ref($domdefref) eq 'HASH') {
                   7987:         %domdef = %{$domdefref};
                   7988:     } else {
                   7989:         %domdef = &get_domain_defaults($udom);
                   7990:     }
1.976     raeburn  7991:     if (ref($domdef{$tool}) eq 'HASH') {
                   7992:         if ($is_adv) {
                   7993:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7994:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7995:                     $access = 1;
                   7996:                 } else {
                   7997:                     $access = 0;
                   7998:                 }
                   7999:                 return $access;
                   8000:             }
                   8001:         }
                   8002:         if ($inststatus ne '') {
                   8003:             my ($hasaccess,$hasnoaccess);
                   8004:             foreach my $affiliation (split(/:/,$inststatus)) {
                   8005:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   8006:                     if ($domdef{$tool}{$affiliation}) {
                   8007:                         $hasaccess = 1;
                   8008:                     } else {
                   8009:                         $hasnoaccess = 1;
                   8010:                     }
                   8011:                 }
                   8012:             }
                   8013:             if ($hasaccess || $hasnoaccess) {
                   8014:                 if ($hasaccess) {
                   8015:                     $access = 1;
                   8016:                 } elsif ($hasnoaccess) {
                   8017:                     $access = 0; 
                   8018:                 }
                   8019:                 return $access;
                   8020:             }
                   8021:         } else {
                   8022:             if ($domdef{$tool}{'default'} ne '') {
                   8023:                 if ($domdef{$tool}{'default'}) {
                   8024:                     $access = 1;
                   8025:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   8026:                     $access = 0;
                   8027:                 }
                   8028:                 return $access;
                   8029:             }
                   8030:         }
                   8031:     } else {
1.1177    raeburn  8032:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  8033:             $access = 1;
                   8034:         } else {
                   8035:             $access = 0;
                   8036:         }
1.976     raeburn  8037:         return $access;
                   8038:     }
                   8039: }
                   8040: 
1.1050    raeburn  8041: sub is_course_owner {
                   8042:     my ($cdom,$cnum,$udom,$uname) = @_;
                   8043:     if (($udom eq '') || ($uname eq '')) {
                   8044:         $udom = $env{'user.domain'};
                   8045:         $uname = $env{'user.name'};
                   8046:     }
                   8047:     unless (($udom eq '') || ($uname eq '')) {
                   8048:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   8049:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   8050:                 return 1;
                   8051:             } else {
                   8052:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   8053:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   8054:                     return 1;
                   8055:                 }
                   8056:             }
                   8057:         }
                   8058:     }
                   8059:     return;
                   8060: }
                   8061: 
1.976     raeburn  8062: sub is_advanced_user {
                   8063:     my ($udom,$uname) = @_;
1.1085    raeburn  8064:     if ($udom ne '' && $uname ne '') {
                   8065:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  8066:             if (wantarray) {
                   8067:                 return ($env{'user.adv'},$env{'user.author'});
                   8068:             } else {
                   8069:                 return $env{'user.adv'};
                   8070:             }
1.1085    raeburn  8071:         }
                   8072:     }
1.976     raeburn  8073:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   8074:     my %allroles;
1.1128    raeburn  8075:     my ($is_adv,$is_author);
1.976     raeburn  8076:     foreach my $role (keys(%roleshash)) {
                   8077:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   8078:         my $area = '/'.$tdomain.'/'.$trest;
                   8079:         if ($sec ne '') {
                   8080:             $area .= '/'.$sec;
                   8081:         }
                   8082:         if (($area ne '') && ($trole ne '')) {
                   8083:             my $spec=$trole.'.'.$area;
                   8084:             if ($trole =~ /^cr\//) {
                   8085:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   8086:             } elsif ($trole ne 'gr') {
                   8087:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   8088:             }
1.1128    raeburn  8089:             if ($trole eq 'au') {
                   8090:                 $is_author = 1;
                   8091:             }
1.976     raeburn  8092:         }
                   8093:     }
                   8094:     foreach my $role (keys(%allroles)) {
                   8095:         last if ($is_adv);
                   8096:         foreach my $item (split(/:/,$allroles{$role})) {
                   8097:             if ($item ne '') {
                   8098:                 my ($privilege,$restrictions)=split(/&/,$item);
                   8099:                 if ($privilege eq 'adv') {
                   8100:                     $is_adv = 1;
                   8101:                     last;
                   8102:                 }
                   8103:             }
                   8104:         }
                   8105:     }
1.1128    raeburn  8106:     if (wantarray) {
                   8107:         return ($is_adv,$is_author);
                   8108:     }
1.976     raeburn  8109:     return $is_adv;
                   8110: }
1.798     raeburn  8111: 
1.1035    raeburn  8112: sub check_can_request {
1.1368    raeburn  8113:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  8114:     my $canreq = 0;
1.1368    raeburn  8115:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8116:         $uname = $env{'user.name'};
                   8117:         $udom = $env{'user.domain'};
                   8118:     }
1.1035    raeburn  8119:     my ($types,$typename) = &Apache::loncommon::course_types();
                   8120:     my @options = ('approval','validate','autolimit');
                   8121:     my $optregex = join('|',@options);
                   8122:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   8123:         foreach my $type (@{$types}) {
1.1368    raeburn  8124:             if (&usertools_access($uname,$udom,$type,undef,
                   8125:                                   'requestcourses')) {
1.1035    raeburn  8126:                 $canreq ++;
1.1036    raeburn  8127:                 if (ref($request_domains) eq 'HASH') {
1.1368    raeburn  8128:                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  8129:                 }
1.1368    raeburn  8130:                 if ($dom eq $udom) {
1.1035    raeburn  8131:                     $can_request->{$type} = 1;
                   8132:                 }
                   8133:             }
1.1368    raeburn  8134:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   8135:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  8136:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   8137:                 if (@curr > 0) {
1.1036    raeburn  8138:                     foreach my $item (@curr) {
                   8139:                         if (ref($request_domains) eq 'HASH') {
                   8140:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   8141:                             if ($otherdom ne '') {
                   8142:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   8143:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   8144:                                         push(@{$request_domains->{$type}},$otherdom);
                   8145:                                     }
                   8146:                                 } else {
                   8147:                                     push(@{$request_domains->{$type}},$otherdom);
                   8148:                                 }
                   8149:                             }
                   8150:                         }
                   8151:                     }
1.1368    raeburn  8152:                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  8153:                         $canreq ++;
1.1035    raeburn  8154:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   8155:                             $can_request->{$type} = 1;
                   8156:                         }
                   8157:                     }
                   8158:                 }
                   8159:             }
                   8160:         }
                   8161:     }
                   8162:     return $canreq;
                   8163: }
                   8164: 
1.341     www      8165: # ---------------------------------------------- Custom access rule evaluation
                   8166: 
                   8167: sub customaccess {
                   8168:     my ($priv,$uri)=@_;
1.807     albertel 8169:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      8170:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 8171:     $udom = &LONCAPA::clean_domain($udom);
                   8172:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      8173:     my $access=0;
1.800     albertel 8174:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 8175: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   8176: 	if ($type eq 'user') {
                   8177: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 8178: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 8179: 		if ($tdom) {
                   8180: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   8181: 		}
1.896     albertel 8182: 		if ($tuname) {
                   8183: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 8184: 		}
                   8185: 		$access=($effect eq 'allow');
                   8186: 		last;
                   8187: 	    }
                   8188: 	} else {
                   8189: 	    if ($role) {
                   8190: 		if ($role ne $urole) { next; }
                   8191: 	    }
                   8192: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   8193: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   8194: 		if ($tdom) {
                   8195: 		    if ($tdom ne $udom) { next; }
                   8196: 		}
                   8197: 		if ($tcrs) {
                   8198: 		    if ($tcrs ne $ucrs) { next; }
                   8199: 		}
                   8200: 		if ($tsec) {
                   8201: 		    if ($tsec ne $usec) { next; }
                   8202: 		}
                   8203: 		$access=($effect eq 'allow');
                   8204: 		last;
                   8205: 	    }
                   8206: 	    if ($realm eq '' && $role eq '') {
                   8207: 		$access=($effect eq 'allow');
                   8208: 	    }
1.402     bowersj2 8209: 	}
1.341     www      8210:     }
                   8211:     return $access;
                   8212: }
                   8213: 
1.103     harris41 8214: # ------------------------------------------------- Check for a user privilege
1.12      www      8215: 
                   8216: sub allowed {
1.1461    raeburn  8217:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache,$nodeeplinkcheck,$nodeeplinkout)=@_;
1.705     albertel 8218:     my $ver_orguri=$uri;
1.439     www      8219:     $uri=&deversion($uri);
1.152     www      8220:     my $orguri=$uri;
1.52      www      8221:     $uri=&declutter($uri);
1.809     raeburn  8222: 
1.810     raeburn  8223:     if ($priv eq 'evb') {
1.1478    raeburn  8224: # Evade communication block restrictions for specified role in a course or domain
1.810     raeburn  8225:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   8226:             return $1;
                   8227:         } else {
                   8228:             return;
                   8229:         }
                   8230:     }
                   8231: 
1.620     albertel 8232:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      8233: # Free bre access to adm and meta resources
1.1436    raeburn  8234:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme|ext\.tool)$})) 
1.769     albertel 8235: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   8236: 	&& ($priv eq 'bre')) {
1.14      www      8237: 	return 'F';
1.159     www      8238:     }
                   8239: 
1.545     banghart 8240: # Free bre access to user's own portfolio contents
1.714     raeburn  8241:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  8242:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  8243: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  8244:         my %setters;
1.1473    raeburn  8245:         my ($startblock,$endblock,$triggerblock,$by_ip,$blockdom) = 
                   8246:             &Apache::loncommon::blockcheck(\%setters,'port',$clientip);
                   8247:         if (($startblock && $endblock) || ($by_ip)) {
1.814     raeburn  8248:             return 'B';
                   8249:         } else {
                   8250:             return 'F';
                   8251:         }
1.545     banghart 8252:     }
                   8253: 
1.762     raeburn  8254: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  8255:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   8256:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   8257:         if (exists($env{'request.course.id'})) {
                   8258:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8259:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8260:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   8261:                 my $courseprivid=$env{'request.course.id'};
                   8262:                 $courseprivid=~s/\_/\//;
                   8263:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   8264:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   8265:                     return $1; 
1.762     raeburn  8266:                 } else {
                   8267:                     if ($env{'request.course.sec'}) {
                   8268:                         $courseprivid.='/'.$env{'request.course.sec'};
                   8269:                     }
                   8270:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   8271:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   8272:                         return $2;
                   8273:                     }
1.714     raeburn  8274:                 }
                   8275:             }
                   8276:         }
                   8277:     }
                   8278: 
1.159     www      8279: # Free bre to public access
                   8280: 
                   8281:     if ($priv eq 'bre') {
1.1362    raeburn  8282:         my $copyright;
                   8283:         unless ($uri =~ /ext\.tool/) {
                   8284:             $copyright=&metadata($uri,'copyright');
                   8285:         }
1.620     albertel 8286: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      8287:            return 'F'; 
                   8288:         }
1.238     www      8289:         if ($copyright eq 'priv') {
                   8290:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8291: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      8292: 		return '';
                   8293:             }
                   8294:         }
                   8295:         if ($copyright eq 'domain') {
                   8296:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 8297: 	    unless (($env{'user.domain'} eq $1) ||
                   8298:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      8299: 		return '';
                   8300:             }
1.262     matthew  8301:         }
1.620     albertel 8302:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  8303:             # Library role, so allow browsing of resources in this domain.
                   8304:             return 'F';
1.238     www      8305:         }
1.341     www      8306:         if ($copyright eq 'custom') {
                   8307: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   8308:         }
1.14      www      8309:     }
1.264     matthew  8310:     # Domain coordinator is trying to create a course
1.620     albertel 8311:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  8312:         # uri is the requested domain in this case.
                   8313:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  8314:         # a role of dc for the domain in question.
1.620     albertel 8315:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  8316:     }
1.29      www      8317: 
1.52      www      8318:     my $thisallowed='';
                   8319:     my $statecond=0;
                   8320:     my $courseprivid='';
                   8321: 
1.1039    raeburn  8322:     my $ownaccess;
1.1043    raeburn  8323:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  8324:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   8325:         if ($uri eq '') {
                   8326:             $ownaccess = 1;
                   8327:         } else {
                   8328:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   8329:                 my $udom = $env{'user.domain'};
                   8330:                 my $uname = $env{'user.name'};
                   8331:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   8332:                     $ownaccess = 1;
1.1040    raeburn  8333:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  8334:                     unless ($uri =~ m{\.\./}) {
                   8335:                         $ownaccess = 1;
                   8336:                     }
                   8337:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   8338:                     my $now = time;
                   8339:                     if ($uri =~ m{^([^/]+)/?$}) {
                   8340:                         my $adom = $1;
                   8341:                         foreach my $key (keys(%env)) {
1.1042    raeburn  8342:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1452    raeburn  8343:                                 my ($start,$end) = split(/\./,$env{$key});
                   8344:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1039    raeburn  8345:                                     $ownaccess = 1;
                   8346:                                     last;
                   8347:                                 }
                   8348:                             }
                   8349:                         }
                   8350:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   8351:                         my $adom = $1;
                   8352:                         my $aname = $2;
1.1042    raeburn  8353:                         foreach my $role ('ca','aa') { 
                   8354:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   8355:                                 my ($start,$end) =
1.1452    raeburn  8356:                                     split(/\./,$env{"user.role.$role./$adom/$aname"});
                   8357:                                 if (($now >= $start) && (!$end || $end > $now)) {
1.1042    raeburn  8358:                                     $ownaccess = 1;
                   8359:                                     last;
                   8360:                                 }
1.1039    raeburn  8361:                             }
                   8362:                         }
                   8363:                     }
                   8364:                 }
                   8365:             }
                   8366:         }
                   8367:     }
                   8368: 
1.52      www      8369: # Course
                   8370: 
1.620     albertel 8371:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8372:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8373:             $thisallowed.=$1;
                   8374:         }
1.52      www      8375:     }
1.29      www      8376: 
1.52      www      8377: # Domain
                   8378: 
1.620     albertel 8379:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 8380:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  8381:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  8382:             $thisallowed.=$1;
                   8383:         }
1.12      www      8384:     }
1.52      www      8385: 
1.1141    raeburn  8386: # User who is not author or co-author might still be able to edit
                   8387: # resource of an author in the domain (e.g., if Domain Coordinator).
                   8388:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   8389:         (&allowed('mdc',$env{'request.course.id'}))) {
                   8390:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   8391:             $thisallowed.=$1;
                   8392:         }
                   8393:     }
                   8394: 
1.52      www      8395: # Course: uri itself is a course
1.66      www      8396:     my $courseuri=$uri;
                   8397:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      8398:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      8399: 
1.620     albertel 8400:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 8401:        =~/\Q$priv\E\&([^\:]*)/) {
1.1409    raeburn  8402:         if ($priv eq 'mip') {
                   8403:             my $rem = $1;
                   8404:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
                   8405:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
                   8406:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8407:                 if ($cdom ne '') {
1.1410    raeburn  8408:                     my %passwdconf = &get_passwdconf($cdom);
                   8409:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
                   8410:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
                   8411:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
                   8412:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
                   8413:                                 unless (@inststatuses) {
                   8414:                                     @inststatuses = ('default');
                   8415:                                 }
                   8416:                                 foreach my $status (@inststatuses) {
                   8417:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
                   8418:                                         $thisallowed.=$rem;
                   8419:                                     }
                   8420:                                 }
                   8421:                             }
                   8422:                         }
1.1409    raeburn  8423:                     }
                   8424:                 }
                   8425:             }
                   8426:         } else {
                   8427:             unless (($priv eq 'bro') && (!$ownaccess)) {
                   8428:                 $thisallowed.=$1;
                   8429:             }
1.1039    raeburn  8430:         }
1.12      www      8431:     }
1.29      www      8432: 
1.665     albertel 8433: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 8434: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 8435:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 8436: 	$thisallowed='';
1.671     raeburn  8437:         my ($match)=&is_on_map($uri);
                   8438:         if ($match) {
                   8439:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   8440:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  8441:                 my $value = $1;
1.1461    raeburn  8442:                 my $deeplinkblock;
                   8443:                 unless ($nodeeplinkcheck) {
                   8444:                     $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8445:                 }
1.1402    raeburn  8446:                 if ($deeplinkblock) {
                   8447:                     $thisallowed='D';
                   8448:                 } elsif ($noblockcheck) {
1.1281    raeburn  8449:                     $thisallowed.=$value;
1.1162    raeburn  8450:                 } else {
1.1424    raeburn  8451:                     my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281    raeburn  8452:                     if (@blockers > 0) {
                   8453:                         $thisallowed = 'B';
                   8454:                     } else {
                   8455:                         $thisallowed.=$value;
                   8456:                     }
1.1162    raeburn  8457:                 }
1.671     raeburn  8458:             }
                   8459:         } else {
1.705     albertel 8460:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  8461:             if ($refuri) {
                   8462:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  8463:                     $thisallowed='F';
1.671     raeburn  8464:                 } else {
                   8465:                     $refuri=&declutter($refuri);
                   8466:                     my ($match) = &is_on_map($refuri);
                   8467:                     if ($match) {
1.1461    raeburn  8468:                         my $deeplinkblock;
                   8469:                         unless ($nodeeplinkcheck) {
                   8470:                             $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8471:                         }
1.1402    raeburn  8472:                         if ($deeplinkblock) {
                   8473:                             $thisallowed='D';
                   8474:                         } elsif ($noblockcheck) {
1.1281    raeburn  8475:                             $thisallowed='F';
1.1162    raeburn  8476:                         } else {
1.1426    raeburn  8477:                             my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281    raeburn  8478:                             if (@blockers > 0) {
                   8479:                                 $thisallowed = 'B';
                   8480:                             } else {
                   8481:                                 $thisallowed='F';
                   8482:                             }
1.1162    raeburn  8483:                         }
1.671     raeburn  8484:                     }
1.669     raeburn  8485:                 }
1.671     raeburn  8486:             }
                   8487:         }
1.314     www      8488:     }
1.492     albertel 8489: 
1.766     albertel 8490:     if ($priv eq 'bre'
                   8491: 	&& $thisallowed ne 'F' 
                   8492: 	&& $thisallowed ne '2'
                   8493: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  8494: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 8495:     }
1.1250    raeburn  8496: 
1.52      www      8497: # Full access at system, domain or course-wide level? Exit.
1.29      www      8498:     if ($thisallowed=~/F/) {
                   8499: 	return 'F';
                   8500:     }
                   8501: 
1.52      www      8502: # If this is generating or modifying users, exit with special codes
1.29      www      8503: 
1.643     www      8504:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   8505: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 8506: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      8507: # no author name given, so this just checks on the general right to make a co-author in this domain
                   8508: 	    unless ($auname) { return $thisallowed; }
                   8509: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 8510: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   8511: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   8512: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   8513: 	}
1.52      www      8514: 	return $thisallowed;
                   8515:     }
                   8516: #
1.103     harris41 8517: # Gathered so far: system, domain and course wide privileges
1.52      www      8518: #
                   8519: # Course: See if uri or referer is an individual resource that is part of 
                   8520: # the course
                   8521: 
1.620     albertel 8522:     if ($env{'request.course.id'}) {
1.232     www      8523: 
1.1409    raeburn  8524: # If this is modifying password (internal auth) domains must match for user and user's role.
                   8525: 
                   8526:         if ($priv eq 'mip') {
                   8527:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
                   8528:                 return $thisallowed;
                   8529:             } else {
                   8530:                 return '';
                   8531:             }
                   8532:         }
                   8533: 
1.620     albertel 8534:        $courseprivid=$env{'request.course.id'};
                   8535:        if ($env{'request.course.sec'}) {
                   8536:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      8537:        }
                   8538:        $courseprivid=~s/\_/\//;
                   8539:        my $checkreferer=1;
1.232     www      8540:        my ($match,$cond)=&is_on_map($uri);
                   8541:        if ($match) {
                   8542:            $statecond=$cond;
1.620     albertel 8543:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8544:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8545:                my $value = $1;
                   8546:                if ($priv eq 'bre') {
1.1461    raeburn  8547:                    my $deeplinkblock;
                   8548:                    unless ($nodeeplinkcheck) {
                   8549:                        $deeplinkblock = &deeplink_check($priv,$symb,$uri);
                   8550:                    }
1.1458    raeburn  8551:                    if ($deeplinkblock) {
                   8552:                        $thisallowed = 'D';
                   8553:                    } elsif ($noblockcheck) {
1.1281    raeburn  8554:                        $thisallowed.=$value;
1.1162    raeburn  8555:                    } else {
1.1424    raeburn  8556:                        my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
1.1281    raeburn  8557:                        if (@blockers > 0) {
                   8558:                            $thisallowed = 'B';
                   8559:                        } else {
                   8560:                            $thisallowed.=$value;
                   8561:                        }
1.1162    raeburn  8562:                    }
                   8563:                } else {
                   8564:                    $thisallowed.=$value;
                   8565:                }
1.52      www      8566:                $checkreferer=0;
                   8567:            }
1.29      www      8568:        }
1.1424    raeburn  8569: 
1.148     www      8570:        if ($checkreferer) {
1.620     albertel 8571: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      8572:             unless ($refuri) {
1.800     albertel 8573:                 foreach my $key (keys(%env)) {
                   8574: 		    if ($key=~/^httpref\..*\*/) {
                   8575: 			my $pattern=$key;
1.156     www      8576:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      8577:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   8578:                         $pattern=~s/\//\\\//g;
1.152     www      8579:                         if ($orguri=~/$pattern/) {
1.800     albertel 8580: 			    $refuri=$env{$key};
1.148     www      8581:                         }
                   8582:                     }
1.191     harris41 8583:                 }
1.148     www      8584:             }
1.232     www      8585: 
1.148     www      8586:          if ($refuri) { 
1.152     www      8587: 	  $refuri=&declutter($refuri);
1.232     www      8588:           my ($match,$cond)=&is_on_map($refuri);
                   8589:             if ($match) {
                   8590:               my $refstatecond=$cond;
1.620     albertel 8591:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 8592:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  8593:                   my $value = $1;
                   8594:                   if ($priv eq 'bre') {
1.1461    raeburn  8595:                       my $deeplinkblock;
                   8596:                       unless ($nodeeplinkcheck) {
                   8597:                           $deeplinkblock = &deeplink_check($priv,$symb,$refuri);
                   8598:                       }
1.1402    raeburn  8599:                       if ($deeplinkblock) {
                   8600:                           $thisallowed = 'D';
                   8601:                       } elsif ($noblockcheck) {
1.1281    raeburn  8602:                           $thisallowed.=$value;
1.1162    raeburn  8603:                       } else {
1.1426    raeburn  8604:                           my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
1.1281    raeburn  8605:                           if (@blockers > 0) {
                   8606:                               $thisallowed = 'B';
                   8607:                           } else {
                   8608:                               $thisallowed.=$value;
                   8609:                           }
1.1162    raeburn  8610:                       }
                   8611:                   } else {
                   8612:                       $thisallowed.=$value;
                   8613:                   }
1.53      www      8614:                   $uri=$refuri;
                   8615:                   $statecond=$refstatecond;
1.52      www      8616:               }
                   8617:           }
1.148     www      8618:         }
1.29      www      8619:        }
1.52      www      8620:    }
1.29      www      8621: 
1.52      www      8622: #
1.103     harris41 8623: # Gathered now: all privileges that could apply, and condition number
1.52      www      8624: # 
                   8625: #
                   8626: # Full or no access?
                   8627: #
1.29      www      8628: 
1.52      www      8629:     if ($thisallowed=~/F/) {
                   8630: 	return 'F';
                   8631:     }
1.29      www      8632: 
1.52      www      8633:     unless ($thisallowed) {
                   8634:         return '';
                   8635:     }
1.29      www      8636: 
1.52      www      8637: # Restrictions exist, deal with them
                   8638: #
                   8639: #   C:according to course preferences
                   8640: #   R:according to resource settings
                   8641: #   L:unless locked
                   8642: #   X:according to user session state
                   8643: #
                   8644: 
                   8645: # Possibly locked functionality, check all courses
1.1454    raeburn  8646: # In roles.tab, L (unless locked) available for bre, pch, plc, pac and sma.
1.54      www      8647: # Locks might take effect only after 10 minutes cache expiration for other
1.1454    raeburn  8648: # courses, and 2 minutes for current course, in which user has st or ta role
                   8649: # which is neither expired nor a future role (unless current course).
1.52      www      8650: 
1.1454    raeburn  8651:     my ($needlockcheck,$now,$crsonly);
1.52      www      8652:     if ($thisallowed=~/L/) {
1.1454    raeburn  8653:         $now = time;
                   8654:         if ($priv eq 'bre') {
                   8655:             if ($uri ne '') {
                   8656:                 if ($orguri =~ m{^/+res/}) {
                   8657:                     if ($uri =~ m{^lib/templates/}) {
                   8658:                         if ($env{'request.course.id'}) {
                   8659:                             $crsonly = 1;
                   8660:                             $needlockcheck = 1;
                   8661:                         }
                   8662:                     } else {
                   8663:                         $needlockcheck = 1;
                   8664:                     }
                   8665:                 } elsif ($env{'request.course.id'}) {
                   8666:                     my ($crsdom,$crsnum) = split('_',$env{'request.course.id'});
                   8667:                     if (($uri =~ m{^(adm|uploaded|public)/$crsdom/$crsnum/}) ||
                   8668:                         ($uri =~ m{^adm/$match_domain/$match_username/\d+/(smppg|bulletinboard)$})) {
                   8669:                         $crsonly = 1;
                   8670:                     }
                   8671:                     $needlockcheck = 1;
                   8672:                 }
                   8673:             }
                   8674:         } elsif (($priv eq 'pch') || ($priv eq 'plc') || ($priv eq 'pac') || ($priv eq 'sma')) {
                   8675:             $needlockcheck = 1;
                   8676:         }
                   8677:     }
                   8678:     if ($needlockcheck) {
1.1453    raeburn  8679:         foreach my $envkey (keys(%env)) {
1.54      www      8680:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   8681:                my $courseid=$2;
                   8682:                my $roleid=$1.'.'.$2;
1.92      www      8683:                $courseid=~s/^\///;
1.1453    raeburn  8684:                unless ($env{'request.role'} eq $roleid) {
                   8685:                    my ($start,$end) = split(/\./,$env{$envkey});
                   8686:                    next unless (($now >= $start) && (!$end || $end > $now));
                   8687:                }
1.54      www      8688:                my $expiretime=600;
1.620     albertel 8689:                if ($env{'request.role'} eq $roleid) {
1.54      www      8690: 		  $expiretime=120;
                   8691:                }
                   8692: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   8693:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 8694:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 8695: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      8696:                }
1.620     albertel 8697:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8698:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   8699: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   8700:                        &log($env{'user.domain'},$env{'user.name'},
                   8701:                             $env{'user.home'},
1.57      www      8702:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      8703:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8704:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8705: 		       return '';
                   8706:                    }
                   8707:                }
1.620     albertel 8708:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   8709:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
1.1455    raeburn  8710: 		   if ($env{$prefix.'priv.'.$priv.'.lock.expire'}>time) {
1.620     albertel 8711:                        &log($env{'user.domain'},$env{'user.name'},
                   8712:                             $env{'user.home'},
1.57      www      8713:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      8714:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 8715:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      8716: 		       return '';
                   8717:                    }
                   8718:                }
                   8719: 	   }
1.29      www      8720:        }
1.52      www      8721:     }
1.1424    raeburn  8722: 
1.52      www      8723: #
                   8724: # Rest of the restrictions depend on selected course
                   8725: #
                   8726: 
1.620     albertel 8727:     unless ($env{'request.course.id'}) {
1.766     albertel 8728: 	if ($thisallowed eq 'A') {
                   8729: 	    return 'A';
1.814     raeburn  8730:         } elsif ($thisallowed eq 'B') {
                   8731:             return 'B';
1.766     albertel 8732: 	} else {
                   8733: 	    return '1';
                   8734: 	}
1.52      www      8735:     }
1.29      www      8736: 
1.52      www      8737: #
                   8738: # Now user is definitely in a course
                   8739: #
1.53      www      8740: 
                   8741: 
                   8742: # Course preferences
                   8743: 
                   8744:    if ($thisallowed=~/C/) {
1.620     albertel 8745:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   8746:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   8747:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 8748: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  8749: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8750: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8751: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   8752: 			$env{'request.course.id'});
                   8753: 	   }
1.237     www      8754:            return '';
                   8755:        }
                   8756: 
1.620     albertel 8757:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 8758: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  8759: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 8760: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   8761: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   8762: 			$env{'request.course.id'});
                   8763: 	   }
1.54      www      8764:            return '';
                   8765:        }
1.53      www      8766:    }
                   8767: 
                   8768: # Resource preferences
                   8769: 
                   8770:    if ($thisallowed=~/R/) {
1.620     albertel 8771:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 8772:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  8773: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 8774: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   8775: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   8776: 	   }
                   8777: 	   return '';
1.54      www      8778:        }
1.53      www      8779:    }
1.30      www      8780: 
1.1461    raeburn  8781: # Restricted for deeplinked session?
                   8782: 
                   8783:     if ($env{'request.deeplink.login'}) {
                   8784:         if ($env{'acc.deeplinkout'} && !$nodeeplinkout) {
                   8785:             if (!$symb) { $symb=&symbread($uri,1); }
                   8786:             if (($symb) && ($env{'acc.deeplinkout'}=~/\&\Q$symb\E\&/)) {
                   8787:                 return '';
                   8788:             }
                   8789:         }
                   8790:     }
                   8791: 
1.246     www      8792: # Restricted by state or randomout?
1.30      www      8793: 
1.52      www      8794:    if ($thisallowed=~/X/) {
1.620     albertel 8795:       if ($env{'acc.randomout'}) {
1.579     albertel 8796: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 8797:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      8798:             return ''; 
                   8799:          }
1.247     www      8800:       }
                   8801:       if (&condval($statecond)) {
1.52      www      8802: 	 return '2';
                   8803:       } else {
                   8804:          return '';
                   8805:       }
                   8806:    }
1.30      www      8807: 
1.766     albertel 8808:     if ($thisallowed eq 'A') {
                   8809: 	return 'A';
1.814     raeburn  8810:     } elsif ($thisallowed eq 'B') {
                   8811:         return 'B';
1.1402    raeburn  8812:     } elsif ($thisallowed eq 'D') {
                   8813:         return 'D';
1.766     albertel 8814:     }
1.52      www      8815:    return 'F';
1.232     www      8816: }
1.1162    raeburn  8817: 
1.1192    raeburn  8818: # ------------------------------------------- Check construction space access
                   8819: 
                   8820: sub constructaccess {
                   8821:     my ($url,$setpriv)=@_;
                   8822: 
                   8823: # We do not allow editing of previous versions of files
                   8824:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   8825: 
                   8826: # Get username and domain from URL
                   8827:     my ($ownername,$ownerdomain,$ownerhome);
                   8828: 
                   8829:     ($ownerdomain,$ownername) =
1.1325    raeburn  8830:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  8831: 
                   8832: # The URL does not really point to any authorspace, forget it
                   8833:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   8834: 
                   8835: # Now we need to see if the user has access to the authorspace of
                   8836: # $ownername at $ownerdomain
                   8837: 
                   8838:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   8839: # Real author for this?
                   8840:        $ownerhome = $env{'user.home'};
                   8841:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   8842:           return ($ownername,$ownerdomain,$ownerhome);
                   8843:        }
                   8844:     } else {
                   8845: # Co-author for this?
                   8846:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   8847:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   8848:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   8849:             return ($ownername,$ownerdomain,$ownerhome);
                   8850:         }
1.1312    raeburn  8851:         if ($env{'request.course.id'}) {
                   8852:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   8853:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   8854:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   8855:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   8856:                     return ($ownername,$ownerdomain,$ownerhome);
                   8857:                 }
                   8858:             }
                   8859:         }
1.1192    raeburn  8860:     }
                   8861: 
                   8862: # We don't have any access right now. If we are not possibly going to do anything about this,
                   8863: # we might as well leave
                   8864:    unless ($setpriv) { return ''; }
                   8865: 
                   8866: # Backdoor access?
                   8867:     my $allowed=&allowed('eco',$ownerdomain);
                   8868: # Nope
                   8869:     unless ($allowed) { return ''; }
                   8870: # Looks like we may have access, but could be locked by the owner of the construction space
                   8871:     if ($allowed eq 'U') {
                   8872:         my %blocked=&get('environment',['domcoord.author'],
                   8873:                          $ownerdomain,$ownername);
                   8874: # Is blocked by owner
                   8875:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8876:     }
                   8877:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8878: # Grant temporary access
                   8879:         my $then=$env{'user.login.time'};
1.1209    raeburn  8880:         my $update=$env{'user.update.time'};
1.1192    raeburn  8881:         if (!$update) { $update = $then; }
                   8882:         my $refresh=$env{'user.refresh.time'};
                   8883:         if (!$refresh) { $refresh = $update; }
                   8884:         my $now = time;
                   8885:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8886:                            $now,'ca','constructaccess');
                   8887:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8888:         return($ownername,$ownerdomain,$ownerhome);
                   8889:     }
                   8890: # No business here
                   8891:     return '';
                   8892: }
                   8893: 
1.1282    raeburn  8894: # ----------------------------------------------------------- Content Blocking
                   8895: 
                   8896: {
                   8897: # Caches for faster Course Contents display where content blocking
                   8898: # is in operation (i.e., interval param set) for timed quiz.
                   8899: #
                   8900: # User for whom data are being temporarily cached.
                   8901: my $cacheduser='';
1.1424    raeburn  8902: # Course for which data are being temporarily cached.
                   8903: my $cachedcid='';
1.1282    raeburn  8904: # Cached blockers for this user (a hash of blocking items). 
                   8905: my %cachedblockers=();
                   8906: # When the data were last cached.
                   8907: my $cachedlast='';
                   8908: 
                   8909: sub load_all_blockers {
1.1427    raeburn  8910:     my ($uname,$udom)=@_;
1.1282    raeburn  8911:     if (($uname ne '') && ($udom ne '')) { 
                   8912:         if (($cacheduser eq $uname.':'.$udom) &&
1.1424    raeburn  8913:             ($cachedcid eq $env{'request.course.id'}) &&
1.1427    raeburn  8914:             (abs($cachedlast-time)<5)) {
1.1282    raeburn  8915:             return;
                   8916:         }
                   8917:     }
                   8918:     $cachedlast=time;
                   8919:     $cacheduser=$uname.':'.$udom;
1.1424    raeburn  8920:     $cachedcid=$env{'request.course.id'};
1.1427    raeburn  8921:     %cachedblockers = &get_commblock_resources();
1.1424    raeburn  8922:     return;
1.1282    raeburn  8923: }
                   8924: 
1.1162    raeburn  8925: sub get_comm_blocks {
                   8926:     my ($cdom,$cnum) = @_;
                   8927:     if ($cdom eq '' || $cnum eq '') {
                   8928:         return unless ($env{'request.course.id'});
                   8929:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8930:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8931:     }
                   8932:     my %commblocks;
                   8933:     my $hashid=$cdom.'_'.$cnum;
                   8934:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8935:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8936:         %commblocks = %{$blocksref};
                   8937:     } else {
                   8938:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8939:         my $cachetime = 600;
                   8940:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8941:     }
                   8942:     return %commblocks;
                   8943: }
                   8944: 
1.1282    raeburn  8945: sub get_commblock_resources {
                   8946:     my ($blocks) = @_;
                   8947:     my %blockers = ();
                   8948:     return %blockers unless ($env{'request.course.id'});
1.1470    raeburn  8949:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   8950:     if ($env{'request.course.sec'}) {
                   8951:         $courseurl .= '/'.$env{'request.course.sec'};
                   8952:     }
                   8953:     return %blockers if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1162    raeburn  8954:     my %commblocks;
                   8955:     if (ref($blocks) eq 'HASH') {
                   8956:         %commblocks = %{$blocks};
                   8957:     } else {
                   8958:         %commblocks = &get_comm_blocks();
                   8959:     }
1.1282    raeburn  8960:     return %blockers unless (keys(%commblocks) > 0); 
                   8961:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8962:     return %blockers unless (ref($navmap));
1.1162    raeburn  8963:     my $now = time;
                   8964:     foreach my $block (keys(%commblocks)) {
                   8965:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8966:             my ($start,$end) = ($1,$2);
                   8967:             if ($start <= $now && $end >= $now) {
                   8968:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8969:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8970:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  8971:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8972:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  8973:                             }
                   8974:                         }
                   8975:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  8976:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8977:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8978:                             }
                   8979:                         }
                   8980:                     }
                   8981:                 }
                   8982:             }
                   8983:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8984:             my $item = $1;
                   8985:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8986:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1471    raeburn  8987:                     my (@interval,$mapname);
1.1282    raeburn  8988:                     my $type = 'map';
                   8989:                     if ($item eq 'course') {
                   8990:                         $type = 'course';
                   8991:                         @interval=&EXT("resource.0.interval");
                   8992:                     } else {
                   8993:                         if ($item =~ /___\d+___/) {
                   8994:                             $type = 'resource';
                   8995:                             @interval=&EXT("resource.0.interval",$item);
1.1162    raeburn  8996:                         } else {
1.1471    raeburn  8997:                             $mapname = &deversion($item);
                   8998:                             if (ref($navmap)) {
                   8999:                                 my $timelimit = $navmap->get_mapparam(undef,$mapname,'0.interval');
                   9000:                                 @interval = ($timelimit,'map');
1.1162    raeburn  9001:                             }
                   9002:                         }
1.1282    raeburn  9003:                     }
1.1310    raeburn  9004:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  9005:                         my $timelimit = $1; 
1.1282    raeburn  9006:                         my $first_access;
                   9007:                         if ($type eq 'resource') {
                   9008:                             $first_access=&get_first_access($interval[1],$item);
                   9009:                         } elsif ($type eq 'map') {
                   9010:                             $first_access=&get_first_access($interval[1],undef,$item);
                   9011:                         } else {
                   9012:                             $first_access=&get_first_access($interval[1]);
                   9013:                         }
                   9014:                         if ($first_access) {
1.1292    raeburn  9015:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  9016:                             if ($timesup > $now) {
                   9017:                                 my $activeblock;
1.1471    raeburn  9018:                                 if ($type eq 'resource') {
                   9019:                                     if (ref($navmap)) {
                   9020:                                         my $res = $navmap->getBySymb($item);
                   9021:                                         if ($res->answerable()) {
                   9022:                                             $activeblock = 1;
                   9023:                                         }
                   9024:                                     }
                   9025:                                 } elsif ($type eq 'map') {
                   9026:                                     my $mapsymb = &symbread($mapname,1);
                   9027:                                     if (($mapsymb) && (ref($navmap))) {
                   9028:                                         my $mapres = $navmap->getBySymb($mapsymb);
                   9029:                                         if (ref($mapres)) {
                   9030:                                             my $first = $mapres->map_start();
                   9031:                                             my $finish = $mapres->map_finish();
                   9032:                                             my $it = $navmap->getIterator($first,$finish,undef,0,0);
                   9033:                                             if (ref($it)) {
                   9034:                                                 my $res;
                   9035:                                                 while ($res = $it->next(undef,1)) {
                   9036:                                                     next unless (ref($res));
                   9037:                                                     my $symb = $res->symb();
                   9038:                                                     next if (($symb eq $mapsymb) || ($symb eq ''));
                   9039:                                                     @interval=&EXT("resource.0.interval",$symb);
                   9040:                                                     if ($interval[1] eq 'map') {
                   9041:                                                         if ($res->answerable()) {
                   9042:                                                             $activeblock = 1;
                   9043:                                                             last;
                   9044:                                                         }
                   9045:                                                     }
                   9046:                                                 }
                   9047:                                             }
                   9048:                                         }
1.1282    raeburn  9049:                                     }
                   9050:                                 }
                   9051:                                 if ($activeblock) {
                   9052:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   9053:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   9054:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   9055:                                          }
                   9056:                                     }
                   9057:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   9058:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   9059:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  9060:                                         }
1.1162    raeburn  9061:                                     }
                   9062:                                 }
                   9063:                             }
                   9064:                         }
                   9065:                     }
                   9066:                 }
                   9067:             }
                   9068:         }
                   9069:     }
1.1282    raeburn  9070:     return %blockers;
1.1162    raeburn  9071: }
                   9072: 
1.1282    raeburn  9073: sub has_comm_blocking {
1.1427    raeburn  9074:     my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
1.1282    raeburn  9075:     my @blockers;
                   9076:     return unless ($env{'request.course.id'});
                   9077:     return unless ($priv eq 'bre');
                   9078:     return if ($env{'request.state'} eq 'construct');
1.1470    raeburn  9079:     my $courseurl = &courseid_to_courseurl($env{'request.course.id'});
                   9080:     if ($env{'request.course.sec'}) {
                   9081:         $courseurl .= '/'.$env{'request.course.sec'};
                   9082:     }
                   9083:     return if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseurl} =~/evb\&([^\:]*)/);
1.1427    raeburn  9084:     my %blockinfo;
                   9085:     if (ref($blocks) eq 'HASH') {
                   9086:         %blockinfo = &get_commblock_resources($blocks);
                   9087:     } else {
                   9088:         &load_all_blockers($env{'user.name'},$env{'user.domain'});
                   9089:         %blockinfo = %cachedblockers;
                   9090:     }
                   9091:     return unless (keys(%blockinfo) > 0);
1.1282    raeburn  9092:     my (%possibles,@symbs);
                   9093:     if (!$symb) {
1.1427    raeburn  9094:         $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
1.1162    raeburn  9095:     }
1.1282    raeburn  9096:     if ($symb) {
                   9097:         @symbs = ($symb);
                   9098:     } elsif (keys(%possibles)) { 
                   9099:         @symbs = keys(%possibles);
                   9100:     }
                   9101:     my $noblock;
                   9102:     foreach my $symb (@symbs) {
                   9103:         last if ($noblock);
                   9104:         my ($map,$resid,$resurl)=&decode_symb($symb);
1.1427    raeburn  9105:         foreach my $block (keys(%blockinfo)) {
1.1282    raeburn  9106:             if ($block =~ /^firstaccess____(.+)$/) {
                   9107:                 my $item = $1;
1.1424    raeburn  9108:                 unless ($blocked) {
                   9109:                     if (($item eq $map) || ($item eq $symb)) {
                   9110:                         $noblock = 1;
                   9111:                         last;
                   9112:                     }
1.1282    raeburn  9113:                 }
                   9114:             }
1.1427    raeburn  9115:             if (ref($blockinfo{$block}) eq 'HASH') {
                   9116:                 if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
                   9117:                     if ($blockinfo{$block}{'resources'}{$symb}) {
1.1282    raeburn  9118:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   9119:                             push(@blockers,$block);
                   9120:                         }
                   9121:                     }
                   9122:                 }
1.1427    raeburn  9123:                 if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
                   9124:                     if ($blockinfo{$block}{'maps'}{$map}) {
1.1424    raeburn  9125:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   9126:                             push(@blockers,$block);
                   9127:                         }
1.1282    raeburn  9128:                     }
                   9129:                 }
1.1162    raeburn  9130:             }
                   9131:         }
                   9132:     }
1.1424    raeburn  9133:     unless ($noblock) { 
                   9134:         return @blockers;
                   9135:     }
                   9136:     return;
1.1282    raeburn  9137: }
1.1162    raeburn  9138: }
                   9139: 
1.1402    raeburn  9140: sub deeplink_check {
                   9141:     my ($priv,$symb,$uri) = @_;
                   9142:     return unless ($env{'request.course.id'});
                   9143:     return unless ($priv eq 'bre');
                   9144:     return if ($env{'request.state'} eq 'construct');
                   9145:     return if ($env{'request.role.adv'});
                   9146:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9147:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9148:     my (%possibles,@symbs);
                   9149:     if (!$symb) {
                   9150:         $symb = &symbread($uri,1,1,1,\%possibles);
                   9151:     }
                   9152:     if ($symb) {
                   9153:         @symbs = ($symb);
                   9154:     } elsif (keys(%possibles)) {
                   9155:         @symbs = keys(%possibles);
                   9156:     }
                   9157: 
1.1461    raeburn  9158:     my ($deeplink_symb,$allow);
                   9159:     if ($env{'request.deeplink.login'}) {
                   9160:         $deeplink_symb = &Apache::loncommon::deeplink_login_symb($cnum,$cdom);
1.1402    raeburn  9161:     }
                   9162:     foreach my $symb (@symbs) {
                   9163:         last if ($allow);
                   9164:         my $deeplink = &EXT("resource.0.deeplink",$symb);
                   9165:         if ($deeplink eq '') {
                   9166:             $allow = 1;
                   9167:         } else {
1.1463    raeburn  9168:             my ($state,$others,$listed,$scope,$protect) = split(/,/,$deeplink);
                   9169:             if ($state ne 'only') {
1.1402    raeburn  9170:                 $allow = 1;
1.1463    raeburn  9171:             } else {
                   9172:                 my $check_deeplink_entry;
                   9173:                 if ($protect ne 'none') {
                   9174:                     my ($acctype,$item) = split(/:/,$protect);
                   9175:                     if (($acctype eq 'ltic') && ($env{'user.linkprotector'})) {
                   9176:                         if (grep(/^\Q$item\Ec$/,split(/,/,$env{'user.linkprotector'}))) {
                   9177:                             $check_deeplink_entry = 1
                   9178:                         }
                   9179:                     } elsif (($acctype eq 'ltid') && ($env{'user.linkprotector'})) {
                   9180:                         if (grep(/^\Q$item\Ed$/,split(/,/,$env{'user.linkprotector'}))) {
                   9181:                             $check_deeplink_entry = 1;
                   9182:                         }
                   9183:                     } elsif (($acctype eq 'key') && ($env{'user.deeplinkkey'})) {
                   9184:                         if (grep(/^\Q$item\E$/,split(/,/,$env{'user.deeplinkkey'}))) {
                   9185:                             $check_deeplink_entry = 1;
                   9186:                         }
                   9187:                     }
                   9188:                 }
                   9189:                 if (($protect eq 'none') || ($check_deeplink_entry)) {
1.1402    raeburn  9190:                     if ($scope eq 'res') {
1.1461    raeburn  9191:                         if ($symb eq $deeplink_symb) {
1.1402    raeburn  9192:                             $allow = 1;
                   9193:                         }
1.1459    raeburn  9194:                     } elsif (($scope eq 'map') || ($scope eq 'rec')) {
1.1463    raeburn  9195:                         my ($map_from_symb,$map_from_login);
1.1461    raeburn  9196:                         $map_from_symb = &deversion((&decode_symb($symb))[0]);
                   9197:                         if ($deeplink_symb =~ /\.(page|sequence)$/) {
                   9198:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[2]);
                   9199:                         } else {
                   9200:                             $map_from_login = &deversion((&decode_symb($deeplink_symb))[0]);
                   9201:                         }
1.1459    raeburn  9202:                         if (($map_from_symb) && ($map_from_login)) {
                   9203:                             if ($map_from_symb eq $map_from_login) {
                   9204:                                 $allow = 1;
                   9205:                             } elsif ($scope eq 'rec') {
                   9206:                                 my @recurseup = &get_map_hierarchy($map_from_symb,$env{'request.course.id'});
                   9207:                                 if (grep(/^\Q$map_from_login\E$/,@recurseup)) {
                   9208:                                     $allow = 1;
                   9209:                                 }
                   9210:                             }
                   9211:                         }
1.1402    raeburn  9212:                     }
                   9213:                 }
                   9214:             }
                   9215:         }
                   9216:     }
                   9217:     return if ($allow);
                   9218:     return 1;
                   9219: }
                   9220: 
1.1282    raeburn  9221: # -------------------------------- Deversion and split uri into path an filename   
                   9222: 
1.1133    foxr     9223: #
1.1282    raeburn  9224: #   Removes the version from a URI and
1.1133    foxr     9225: #   splits it in to its filename and path to the filename.
                   9226: #   Seems like File::Basename could have done this more clearly.
                   9227: #   Parameters:
                   9228: #      $uri   - input URI
                   9229: #   Returns:
                   9230: #     Two element list consisting of 
                   9231: #     $pathname  - the URI up to and excluding the trailing /
                   9232: #     $filename  - The part of the URI following the last /
                   9233: #  NOTE:
                   9234: #    Another realization of this is simply:
                   9235: #    use File::Basename;
                   9236: #    ...
                   9237: #    $uri = shift;
                   9238: #    $filename = basename($uri);
                   9239: #    $path     = dirname($uri);
                   9240: #    return ($filename, $path);
                   9241: #
                   9242: #     The implementation below is probably faster however.
                   9243: #
1.710     albertel 9244: sub split_uri_for_cond {
                   9245:     my $uri=&deversion(&declutter(shift));
                   9246:     my @uriparts=split(/\//,$uri);
                   9247:     my $filename=pop(@uriparts);
                   9248:     my $pathname=join('/',@uriparts);
                   9249:     return ($pathname,$filename);
                   9250: }
1.232     www      9251: # --------------------------------------------------- Is a resource on the map?
                   9252: 
                   9253: sub is_on_map {
1.710     albertel 9254:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 9255:     #Trying to find the conditional for the file
1.620     albertel 9256:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 9257: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      9258:     if ($match) {
1.289     bowersj2 9259: 	return (1,$1);
                   9260:     } else {
1.434     www      9261: 	return (0,0);
1.289     bowersj2 9262:     }
1.12      www      9263: }
                   9264: 
1.427     www      9265: # --------------------------------------------------------- Get symb from alias
                   9266: 
                   9267: sub get_symb_from_alias {
                   9268:     my $symb=shift;
                   9269:     my ($map,$resid,$url)=&decode_symb($symb);
                   9270: # Already is a symb
                   9271:     if ($url) { return $symb; }
                   9272: # Must be an alias
                   9273:     my $aliassymb='';
                   9274:     my %bighash;
1.620     albertel 9275:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      9276:                             &GDBM_READER(),0640)) {
                   9277:         my $rid=$bighash{'mapalias_'.$symb};
                   9278: 	if ($rid) {
                   9279: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 9280: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   9281: 				    $resid,$bighash{'src_'.$rid});
1.427     www      9282: 	}
                   9283:         untie %bighash;
                   9284:     }
                   9285:     return $aliassymb;
                   9286: }
                   9287: 
1.12      www      9288: # ----------------------------------------------------------------- Define Role
                   9289: 
                   9290: sub definerole {
                   9291:   if (allowed('mcr','/')) {
1.1326    raeburn  9292:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 9293:     foreach my $role (split(':',$sysrole)) {
                   9294: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9295:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   9296:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   9297: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9298:                return "refused:s:$crole&$cqual"; 
                   9299:             }
                   9300:         }
1.191     harris41 9301:     }
1.800     albertel 9302:     foreach my $role (split(':',$domrole)) {
                   9303: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9304:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   9305:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   9306: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      9307:                return "refused:d:$crole&$cqual"; 
                   9308:             }
                   9309:         }
1.191     harris41 9310:     }
1.800     albertel 9311:     foreach my $role (split(':',$courole)) {
                   9312: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 9313:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   9314:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   9315: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      9316:                return "refused:c:$crole&$cqual"; 
                   9317:             }
                   9318:         }
1.191     harris41 9319:     }
1.1326    raeburn  9320:     my $uhome;
                   9321:     if (($uname ne '') && ($udom ne '')) {
                   9322:         $uhome = &homeserver($uname,$udom);
                   9323:         return $uhome if ($uhome eq 'no_host');
                   9324:     } else {
                   9325:         $uname = $env{'user.name'};
                   9326:         $udom = $env{'user.domain'};
                   9327:         $uhome = $env{'user.home'};
                   9328:     }
1.620     albertel 9329:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  9330:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      9331:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  9332:     return reply($command,$uhome);
1.12      www      9333:   } else {
                   9334:     return 'refused';
                   9335:   }
1.105     harris41 9336: }
                   9337: 
                   9338: # ---------------- Make a metadata query against the network of library servers
                   9339: 
                   9340: sub metadata_query {
1.1237    raeburn  9341:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 9342:     my %rhash;
1.845     albertel 9343:     my %libserv = &all_library();
1.244     matthew  9344:     my @server_list = (defined($server_array) ? @$server_array
                   9345:                                               : keys(%libserv) );
                   9346:     for my $server (@server_list) {
1.1237    raeburn  9347:         my $domains = ''; 
                   9348:         if (ref($domains_hash) eq 'HASH') {
                   9349:             $domains = $domains_hash->{$server}; 
                   9350:         }
1.118     harris41 9351: 	unless ($custom or $customshow) {
1.1237    raeburn  9352: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 9353: 	    $rhash{$server}=$reply;
                   9354: 	}
                   9355: 	else {
                   9356: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  9357: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 9358: 			     $server);
                   9359: 	    $rhash{$server}=$reply;
                   9360: 	}
1.112     harris41 9361:     }
1.118     harris41 9362:     return \%rhash;
1.240     www      9363: }
                   9364: 
                   9365: # ----------------------------------------- Send log queries and wait for reply
                   9366: 
                   9367: sub log_query {
                   9368:     my ($uname,$udom,$query,%filters)=@_;
                   9369:     my $uhome=&homeserver($uname,$udom);
                   9370:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 9371:     my $uhost=&hostname($uhome);
1.800     albertel 9372:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      9373:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   9374:                        $uhome);
1.479     albertel 9375:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      9376:     return get_query_reply($queryid);
                   9377: }
                   9378: 
1.818     raeburn  9379: # -------------------------- Update MySQL table for portfolio file
                   9380: 
                   9381: sub update_portfolio_table {
1.821     raeburn  9382:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  9383:     if ($group ne '') {
                   9384:         $file_name =~s /^\Q$group\E//;
                   9385:     }
1.818     raeburn  9386:     my $homeserver = &homeserver($uname,$udom);
                   9387:     my $queryid=
1.821     raeburn  9388:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   9389:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  9390:     my $reply = &get_query_reply($queryid);
                   9391:     return $reply;
                   9392: }
                   9393: 
1.899     raeburn  9394: # -------------------------- Update MySQL allusers table
                   9395: 
                   9396: sub update_allusers_table {
                   9397:     my ($uname,$udom,$names) = @_;
                   9398:     my $homeserver = &homeserver($uname,$udom);
                   9399:     my $queryid=
                   9400:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   9401:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   9402:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   9403:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   9404:                'generation='.&escape($names->{'generation'}).'%%'.
                   9405:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   9406:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  9407:     return;
1.899     raeburn  9408: }
                   9409: 
1.508     raeburn  9410: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  9411: 
                   9412: sub fetch_enrollment_query {
1.511     raeburn  9413:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  9414:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  9415:     my $maxtries = 1;
1.508     raeburn  9416:     if ($context eq 'automated') {
                   9417:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  9418:         $sleep = 2;
                   9419:         $loopmax = 100;
1.547     raeburn  9420:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  9421:     } else {
                   9422:         $homeserver = &homeserver($cnum,$dom);
                   9423:     }
1.838     albertel 9424:     my $host=&hostname($homeserver);
1.506     raeburn  9425:     my $cmd = '';
1.1000    raeburn  9426:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 9427:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  9428:     }
                   9429:     $cmd =~ s/%%$//;
                   9430:     $cmd = &escape($cmd);
                   9431:     my $query = 'fetchenrollment';
1.620     albertel 9432:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  9433:     unless ($queryid=~/^\Q$host\E\_/) { 
                   9434:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   9435:         return 'error: '.$queryid;
                   9436:     }
1.1317    raeburn  9437:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9438:     my $tries = 1;
                   9439:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  9440:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  9441:         $tries ++;
                   9442:     }
1.526     raeburn  9443:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 9444:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  9445:     } else {
1.901     albertel 9446:         my @responses = split(/:/,$reply);
1.1322    raeburn  9447:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 9448:             foreach my $line (@responses) {
                   9449:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  9450:                 $$replyref{$key} = $value;
                   9451:             }
                   9452:         } else {
1.1117    foxr     9453:             my $pathname = LONCAPA::tempdir();
1.800     albertel 9454:             foreach my $line (@responses) {
                   9455:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  9456:                 $$replyref{$key} = $value;
                   9457:                 if ($value > 0) {
1.800     albertel 9458:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   9459:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  9460:                         my $destname = $pathname.'/'.$filename;
                   9461:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  9462:                         if ($xml_classlist =~ /^error/) {
                   9463:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   9464:                         } else {
1.1359    raeburn  9465:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  9466:                                 print FILE &unescape($xml_classlist);
                   9467:                                 close(FILE);
1.526     raeburn  9468:                             } else {
                   9469:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  9470:                             }
                   9471:                         }
                   9472:                     }
                   9473:                 }
                   9474:             }
                   9475:         }
                   9476:         return 'ok';
                   9477:     }
                   9478:     return 'error';
                   9479: }
                   9480: 
1.242     www      9481: sub get_query_reply {
1.1471    raeburn  9482:     my ($queryid,$sleep,$loopmax) = @_;
1.1317    raeburn  9483:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   9484:         $sleep = 0.2;
                   9485:     }
                   9486:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   9487:         $loopmax = 100;
                   9488:     }
1.1117    foxr     9489:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      9490:     my $reply='';
1.1317    raeburn  9491:     for (1..$loopmax) {
                   9492: 	sleep($sleep);
1.240     www      9493:         if (-e $replyfile.'.end') {
1.1359    raeburn  9494: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 9495: 		$reply = join('',<$fh>);
                   9496: 		close($fh);
1.240     www      9497: 	   } else { return 'error: reply_file_error'; }
1.242     www      9498:            return &unescape($reply);
                   9499: 	}
1.240     www      9500:     }
1.242     www      9501:     return 'timeout:'.$queryid;
1.240     www      9502: }
                   9503: 
                   9504: sub courselog_query {
1.241     www      9505: #
                   9506: # possible filters:
                   9507: # url: url or symb
                   9508: # username
                   9509: # domain
                   9510: # action: view, submit, grade
                   9511: # start: timestamp
                   9512: # end: timestamp
                   9513: #
1.240     www      9514:     my (%filters)=@_;
1.620     albertel 9515:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      9516:     if ($filters{'url'}) {
                   9517: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   9518:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   9519:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   9520:     }
1.620     albertel 9521:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   9522:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      9523:     return &log_query($cname,$cdom,'courselog',%filters);
                   9524: }
                   9525: 
                   9526: sub userlog_query {
1.858     raeburn  9527: #
                   9528: # possible filters:
                   9529: # action: log check role
                   9530: # start: timestamp
                   9531: # end: timestamp
                   9532: #
1.240     www      9533:     my ($uname,$udom,%filters)=@_;
                   9534:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      9535: }
                   9536: 
1.506     raeburn  9537: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   9538: 
                   9539: sub auto_run {
1.508     raeburn  9540:     my ($cnum,$cdom) = @_;
1.876     raeburn  9541:     my $response = 0;
                   9542:     my $settings;
                   9543:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   9544:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   9545:         $settings = $domconfig{'autoenroll'};
                   9546:         if ($settings->{'run'} eq '1') {
                   9547:             $response = 1;
                   9548:         }
                   9549:     } else {
1.934     raeburn  9550:         my $homeserver;
                   9551:         if (&is_course($cdom,$cnum)) {
                   9552:             $homeserver = &homeserver($cnum,$cdom);
                   9553:         } else {
                   9554:             $homeserver = &domain($cdom,'primary');
                   9555:         }
                   9556:         if ($homeserver ne 'no_host') {
                   9557:             $response = &reply('autorun:'.$cdom,$homeserver);
                   9558:         }
1.876     raeburn  9559:     }
1.506     raeburn  9560:     return $response;
                   9561: }
1.776     albertel 9562: 
1.506     raeburn  9563: sub auto_get_sections {
1.508     raeburn  9564:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  9565:     my $homeserver;
                   9566:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   9567:         $homeserver = &homeserver($cnum,$cdom);
                   9568:     }
                   9569:     if (!defined($homeserver)) { 
                   9570:         if ($cdom =~ /^$match_domain$/) {
                   9571:             $homeserver = &domain($cdom,'primary');
                   9572:         }
                   9573:     }
                   9574:     my @secs;
                   9575:     if (defined($homeserver)) {
                   9576:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   9577:         unless ($response eq 'refused') {
                   9578:             @secs = split(/:/,$response);
                   9579:         }
1.506     raeburn  9580:     }
                   9581:     return @secs;
                   9582: }
1.776     albertel 9583: 
1.506     raeburn  9584: sub auto_new_course {
1.1099    raeburn  9585:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  9586:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  9587:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  9588:     return $response;
                   9589: }
1.776     albertel 9590: 
1.506     raeburn  9591: sub auto_validate_courseID {
1.508     raeburn  9592:     my ($cnum,$cdom,$inst_course_id) = @_;
                   9593:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  9594:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  9595:     return $response;
                   9596: }
1.776     albertel 9597: 
1.1007    raeburn  9598: sub auto_validate_instcode {
1.1020    raeburn  9599:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  9600:     my ($homeserver,$response);
                   9601:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9602:         $homeserver = &homeserver($cnum,$cdom);
                   9603:     }
                   9604:     if (!defined($homeserver)) {
                   9605:         if ($cdom =~ /^$match_domain$/) {
                   9606:             $homeserver = &domain($cdom,'primary');
                   9607:         }
                   9608:     }
1.1065    raeburn  9609:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   9610:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  9611:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   9612:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  9613: }
                   9614: 
1.1444    raeburn  9615: sub auto_validate_inst_crosslist {
                   9616:     my ($cnum,$cdom,$instcode,$inst_xlist,$coowner) = @_;
                   9617:     my ($homeserver,$response);
                   9618:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9619:         $homeserver = &homeserver($cnum,$cdom);
                   9620:     }
                   9621:     if (!defined($homeserver)) {
                   9622:         if ($cdom =~ /^$match_domain$/) {
                   9623:             $homeserver = &domain($cdom,'primary');
                   9624:         }
                   9625:     }
                   9626:     unless (($homeserver eq '') || ($homeserver eq 'no_host')) {
                   9627:         $response=&reply('autovalidateinstcrosslist:'.$cdom.':'.
                   9628:                          &escape($instcode).':'.&escape($inst_xlist).':'.
1.1445    raeburn  9629:                          &escape($coowner),$homeserver);
1.1444    raeburn  9630:     }
                   9631:     return $response;
                   9632: }
                   9633: 
1.506     raeburn  9634: sub auto_create_password {
1.873     raeburn  9635:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   9636:     my ($homeserver,$response);
1.506     raeburn  9637:     my $create_passwd = 0;
                   9638:     my $authchk = '';
1.873     raeburn  9639:     if ($udom =~ /^$match_domain$/) {
                   9640:         $homeserver = &domain($udom,'primary');
                   9641:     }
                   9642:     if ($homeserver eq '') {
                   9643:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   9644:             $homeserver = &homeserver($cnum,$cdom);
                   9645:         }
                   9646:     }
                   9647:     if ($homeserver eq '') {
                   9648:         $authchk = 'nodomain';
1.506     raeburn  9649:     } else {
1.873     raeburn  9650:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   9651:         if ($response eq 'refused') {
                   9652:             $authchk = 'refused';
                   9653:         } else {
1.901     albertel 9654:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  9655:         }
1.506     raeburn  9656:     }
                   9657:     return ($authparam,$create_passwd,$authchk);
                   9658: }
                   9659: 
1.706     raeburn  9660: sub auto_photo_permission {
                   9661:     my ($cnum,$cdom,$students) = @_;
                   9662:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 9663:     my ($outcome,$perm_reqd,$conditions) = 
                   9664: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 9665:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9666: 	return (undef,undef);
                   9667:     }
1.706     raeburn  9668:     return ($outcome,$perm_reqd,$conditions);
                   9669: }
                   9670: 
                   9671: sub auto_checkphotos {
                   9672:     my ($uname,$udom,$pid) = @_;
                   9673:     my $homeserver = &homeserver($uname,$udom);
                   9674:     my ($result,$resulttype);
                   9675:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 9676: 				   &escape($uname).':'.&escape($pid),
                   9677: 				   $homeserver));
1.709     albertel 9678:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9679: 	return (undef,undef);
                   9680:     }
1.706     raeburn  9681:     if ($outcome) {
                   9682:         ($result,$resulttype) = split(/:/,$outcome);
                   9683:     } 
                   9684:     return ($result,$resulttype);
                   9685: }
                   9686: 
                   9687: sub auto_photochoice {
                   9688:     my ($cnum,$cdom) = @_;
                   9689:     my $homeserver = &homeserver($cnum,$cdom);
                   9690:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 9691: 						       &escape($cdom),
                   9692: 						       $homeserver)));
1.709     albertel 9693:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   9694: 	return (undef,undef);
                   9695:     }
1.706     raeburn  9696:     return ($update,$comment);
                   9697: }
                   9698: 
                   9699: sub auto_photoupdate {
                   9700:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   9701:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 9702:     my $host=&hostname($homeserver);
1.706     raeburn  9703:     my $cmd = '';
                   9704:     my $maxtries = 1;
1.800     albertel 9705:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   9706:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  9707:     }
                   9708:     $cmd =~ s/%%$//;
                   9709:     $cmd = &escape($cmd);
                   9710:     my $query = 'institutionalphotos';
                   9711:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   9712:     unless ($queryid=~/^\Q$host\E\_/) {
                   9713:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   9714:         return 'error: '.$queryid;
                   9715:     }
                   9716:     my $reply = &get_query_reply($queryid);
                   9717:     my $tries = 1;
                   9718:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   9719:         $reply = &get_query_reply($queryid);
                   9720:         $tries ++;
                   9721:     }
                   9722:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   9723:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   9724:     } else {
                   9725:         my @responses = split(/:/,$reply);
                   9726:         my $outcome = shift(@responses); 
                   9727:         foreach my $item (@responses) {
                   9728:             my ($key,$value) = split(/=/,$item);
                   9729:             $$photo{$key} = $value;
                   9730:         }
                   9731:         return $outcome;
                   9732:     }
                   9733:     return 'error';
                   9734: }
                   9735: 
1.521     raeburn  9736: sub auto_instcode_format {
1.793     albertel 9737:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   9738: 	$cat_order) = @_;
1.521     raeburn  9739:     my $courses = '';
1.772     raeburn  9740:     my @homeservers;
1.521     raeburn  9741:     if ($caller eq 'global') {
1.841     albertel 9742: 	my %servers = &get_servers($codedom,'library');
                   9743: 	foreach my $tryserver (keys(%servers)) {
                   9744: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9745: 		push(@homeservers,$tryserver);
                   9746: 	    }
1.584     raeburn  9747:         }
1.1022    raeburn  9748:     } elsif ($caller eq 'requests') {
                   9749:         if ($codedom =~ /^$match_domain$/) {
                   9750:             my $chome = &domain($codedom,'primary');
                   9751:             unless ($chome eq 'no_host') {
                   9752:                 push(@homeservers,$chome);
                   9753:             }
                   9754:         }
1.521     raeburn  9755:     } else {
1.772     raeburn  9756:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  9757:     }
1.793     albertel 9758:     foreach my $code (keys(%{$instcodes})) {
                   9759:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  9760:     }
                   9761:     chop($courses);
1.772     raeburn  9762:     my $ok_response = 0;
                   9763:     my $response;
                   9764:     while (@homeservers > 0 && $ok_response == 0) {
                   9765:         my $server = shift(@homeservers); 
                   9766:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   9767:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   9768:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 9769: 		split(/:/,$response);
1.772     raeburn  9770:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   9771:             push(@{$codetitles},&str2array($codetitles_str));
                   9772:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   9773:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   9774:             $ok_response = 1;
                   9775:         }
                   9776:     }
                   9777:     if ($ok_response) {
1.521     raeburn  9778:         return 'ok';
1.772     raeburn  9779:     } else {
                   9780:         return $response;
1.521     raeburn  9781:     }
                   9782: }
                   9783: 
1.792     raeburn  9784: sub auto_instcode_defaults {
                   9785:     my ($domain,$returnhash,$code_order) = @_;
                   9786:     my @homeservers;
1.841     albertel 9787: 
                   9788:     my %servers = &get_servers($domain,'library');
                   9789:     foreach my $tryserver (keys(%servers)) {
                   9790: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9791: 	    push(@homeservers,$tryserver);
                   9792: 	}
1.792     raeburn  9793:     }
1.841     albertel 9794: 
1.792     raeburn  9795:     my $response;
1.841     albertel 9796:     foreach my $server (@homeservers) {
1.792     raeburn  9797:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 9798:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   9799: 	
                   9800: 	foreach my $pair (split(/\&/,$response)) {
                   9801: 	    my ($name,$value)=split(/\=/,$pair);
                   9802: 	    if ($name eq 'code_order') {
                   9803: 		@{$code_order} = split(/\&/,&unescape($value));
                   9804: 	    } else {
                   9805: 		$returnhash->{&unescape($name)}=&unescape($value);
                   9806: 	    }
                   9807: 	}
                   9808: 	return 'ok';
1.792     raeburn  9809:     }
1.841     albertel 9810: 
                   9811:     return $response;
1.1003    raeburn  9812: }
                   9813: 
                   9814: sub auto_possible_instcodes {
1.1007    raeburn  9815:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   9816:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   9817:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   9818:         return;
                   9819:     }
1.1003    raeburn  9820:     my (@homeservers,$uhome);
                   9821:     if (defined(&domain($domain,'primary'))) {
                   9822:         $uhome=&domain($domain,'primary');
                   9823:         push(@homeservers,&domain($domain,'primary'));
                   9824:     } else {
                   9825:         my %servers = &get_servers($domain,'library');
                   9826:         foreach my $tryserver (keys(%servers)) {
                   9827:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9828:                 push(@homeservers,$tryserver);
                   9829:             }
                   9830:         }
                   9831:     }
                   9832:     my $response;
                   9833:     foreach my $server (@homeservers) {
                   9834:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   9835:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  9836:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   9837:             split(':',$response);
                   9838:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   9839:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  9840:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  9841:             my ($name,$value)=split('=',$item);
                   9842:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9843:         }
                   9844:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  9845:             my ($name,$value)=split('=',$item);
                   9846:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  9847:         }
                   9848:         return 'ok';
                   9849:     }
                   9850:     return $response;
                   9851: }
1.792     raeburn  9852: 
1.1010    raeburn  9853: sub auto_courserequest_checks {
                   9854:     my ($dom) = @_;
1.1020    raeburn  9855:     my ($homeserver,%validations);
                   9856:     if ($dom =~ /^$match_domain$/) {
                   9857:         $homeserver = &domain($dom,'primary');
                   9858:     }
                   9859:     unless ($homeserver eq 'no_host') {
                   9860:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   9861:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9862:             my @items = split(/&/,$response);
                   9863:             foreach my $item (@items) {
                   9864:                 my ($key,$value) = split('=',$item);
                   9865:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   9866:             }
                   9867:         }
                   9868:     }
1.1010    raeburn  9869:     return %validations; 
                   9870: }
                   9871: 
1.1020    raeburn  9872: sub auto_courserequest_validation {
1.1255    raeburn  9873:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  9874:     my ($homeserver,$response);
                   9875:     if ($dom =~ /^$match_domain$/) {
                   9876:         $homeserver = &domain($dom,'primary');
                   9877:     }
1.1255    raeburn  9878:     unless ($homeserver eq 'no_host') {
                   9879:         my $customdata;
                   9880:         if (ref($custominfo) eq 'HASH') {
                   9881:             $customdata = &freeze_escape($custominfo);
                   9882:         }
1.1020    raeburn  9883:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  9884:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  9885:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   9886:                                     $customdata,$homeserver));
1.1020    raeburn  9887:     }
                   9888:     return $response;
                   9889: }
                   9890: 
1.777     albertel 9891: sub auto_validate_class_sec {
1.918     raeburn  9892:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  9893:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  9894:     my $ownerlist;
                   9895:     if (ref($owners) eq 'ARRAY') {
                   9896:         $ownerlist = join(',',@{$owners});
                   9897:     } else {
                   9898:         $ownerlist = $owners;
                   9899:     }
1.773     raeburn  9900:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  9901:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  9902:     return $response;
                   9903: }
                   9904: 
1.1460    raeburn  9905: sub auto_instsec_reformat {
                   9906:     my ($cdom,$action,$instsecref) = @_;
                   9907:     return unless(($action eq 'clutter') || ($action eq 'declutter'));
                   9908:     my @homeservers;
                   9909:     if (defined(&domain($cdom,'primary'))) {
                   9910:         push(@homeservers,&domain($cdom,'primary'));
                   9911:     } else {
                   9912:         my %servers = &get_servers($cdom,'library');
                   9913:         foreach my $tryserver (keys(%servers)) {
                   9914:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   9915:                 push(@homeservers,$tryserver);
                   9916:             }
                   9917:         }
                   9918:     }
                   9919:     my $response;
                   9920:     my %reformatted = %{$instsecref};
                   9921:     foreach my $server (@homeservers) {
                   9922:         if (ref($instsecref) eq 'HASH') {
                   9923:             my $info = &freeze_escape($instsecref);
                   9924:             my $response=&reply('autoinstsecreformat:'.$cdom.':'.
                   9925:                                 $action.':'.$info,$server);
                   9926:             next if ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/);
                   9927:             my @items = split(/&/,$response);
                   9928:             foreach my $item (@items) {
                   9929:                 my ($key,$value) = split(/=/,$item);
                   9930:                 $reformatted{&unescape($key)} = &thaw_unescape($value);
                   9931:             }
                   9932:         }
                   9933:     }
                   9934:     return %reformatted;
                   9935: }
                   9936: 
1.1367    raeburn  9937: sub auto_validate_instclasses {
                   9938:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   9939:     my ($homeserver,%validations);
                   9940:     $homeserver = &homeserver($cnum,$cdom);
                   9941:     unless ($homeserver eq 'no_host') {
                   9942:         my $ownerlist;
                   9943:         if (ref($owners) eq 'ARRAY') {
                   9944:             $ownerlist = join(',',@{$owners});
                   9945:         } else {
                   9946:             $ownerlist = $owners;
                   9947:         }
                   9948:         if (ref($classesref) eq 'HASH') {
                   9949:             my $classes = &freeze_escape($classesref);
                   9950:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   9951:                                 ':'.$cdom.':'.$classes,$homeserver);
                   9952:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9953:                 my @items = split(/&/,$response);
                   9954:                 foreach my $item (@items) {
                   9955:                     my ($key,$value) = split('=',$item);
                   9956:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   9957:                 }
                   9958:             }
                   9959:         }
                   9960:     }
                   9961:     return %validations;
                   9962: }
                   9963: 
1.1248    raeburn  9964: sub auto_crsreq_update {
                   9965:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  9966:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  9967:     my ($homeserver,%crsreqresponse);
                   9968:     if ($cdom =~ /^$match_domain$/) {
                   9969:         $homeserver = &domain($cdom,'primary');
                   9970:     }
                   9971:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   9972:         my $info;
                   9973:         if (ref($inbound) eq 'HASH') {
                   9974:             $info = &freeze_escape($inbound);
                   9975:         }
                   9976:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   9977:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   9978:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  9979:                             &escape($title).':'.&escape($code).':'.
                   9980:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   9981:                             $homeserver);
1.1248    raeburn  9982:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   9983:             my @items = split(/&/,$response);
                   9984:             foreach my $item (@items) {
                   9985:                 my ($key,$value) = split('=',$item);
                   9986:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   9987:             }
                   9988:         }
                   9989:     }
                   9990:     return \%crsreqresponse;
                   9991: }
                   9992: 
1.1305    raeburn  9993: sub auto_export_grades {
1.1309    raeburn  9994:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   9995:     my ($homeserver,%exportresponse);
                   9996:     if ($cdom =~ /^$match_domain$/) {
                   9997:         $homeserver = &domain($cdom,'primary');
                   9998:     }
                   9999:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   10000:         my $info;
                   10001:         if (ref($inforef) eq 'HASH') {
                   10002:             $info = &freeze_escape($inforef);
                   10003:         }
                   10004:         if (ref($gradesref) eq 'HASH') {
                   10005:             my $grades = &freeze_escape($gradesref);
                   10006:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   10007:                                 $info.':'.$grades,$homeserver);
                   10008:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   10009:                 my @items = split(/&/,$response);
                   10010:                 foreach my $item (@items) {
                   10011:                     my ($key,$value) = split('=',$item);
                   10012:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   10013:                 }
                   10014:             }
                   10015:         }
                   10016:     }
                   10017:     return \%exportresponse;
1.1305    raeburn  10018: }
                   10019: 
1.1287    raeburn  10020: sub check_instcode_cloning {
                   10021:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   10022:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   10023:         return;
                   10024:     }
                   10025:     my $canclone;
                   10026:     if (@{$code_order} > 0) {
                   10027:         my $instcoderegexp ='^';
                   10028:         my @clonecodes = split(/\&/,$cloner);
                   10029:         foreach my $item (@{$code_order}) {
                   10030:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   10031:                 foreach my $pair (@clonecodes) {
                   10032:                     my ($key,$val) = split(/\=/,$pair,2);
                   10033:                     $val = &unescape($val);
                   10034:                     if ($key eq $item) {
                   10035:                         $instcoderegexp .= '('.$val.')';
                   10036:                         last;
                   10037:                     }
                   10038:                 }
                   10039:             } else {
                   10040:                 $instcoderegexp .= $codedefaults->{$item};
                   10041:             }
                   10042:         }
                   10043:         $instcoderegexp .= '$';
                   10044:         my (@from,@to);
                   10045:         eval {
                   10046:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   10047:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   10048:         };
                   10049:         if ((@from > 0) && (@to > 0)) {
                   10050:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   10051:             if (!@diffs) {
                   10052:                 $canclone = 1;
                   10053:             }
                   10054:         }
                   10055:     }
                   10056:     return $canclone;
                   10057: }
                   10058: 
                   10059: sub default_instcode_cloning {
                   10060:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   10061:     my (%codedefaults,@code_order,$canclone);
                   10062:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   10063:         %codedefaults = %{$codedefaultsref};
                   10064:         @code_order = @{$codeorderref};
                   10065:     } elsif ($clonedom) {
                   10066:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   10067:     }
                   10068:     if (($domdefclone) && (@code_order)) {
                   10069:         my @clonecodes = split(/\+/,$domdefclone);
                   10070:         my $instcoderegexp ='^';
                   10071:         foreach my $item (@code_order) {
                   10072:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   10073:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   10074:             } else {
                   10075:                 $instcoderegexp .= $codedefaults{$item};
                   10076:             }
                   10077:         }
                   10078:         $instcoderegexp .= '$';
                   10079:         my (@from,@to);
                   10080:         eval {
                   10081:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   10082:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   10083:         };
                   10084:         if ((@from > 0) && (@to > 0)) {
                   10085:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   10086:             if (!@diffs) {
                   10087:                 $canclone = 1;
                   10088:             }
                   10089:         }
                   10090:     }
                   10091:     return $canclone;
                   10092: }
                   10093: 
1.679     raeburn  10094: # ------------------------------------------------------- Course Group routines
                   10095: 
                   10096: sub get_coursegroups {
1.809     raeburn  10097:     my ($cdom,$cnum,$group,$namespace) = @_;
                   10098:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  10099: }
                   10100: 
1.679     raeburn  10101: sub modify_coursegroup {
                   10102:     my ($cdom,$cnum,$groupsettings) = @_;
                   10103:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   10104: }
                   10105: 
1.809     raeburn  10106: sub toggle_coursegroup_status {
                   10107:     my ($cdom,$cnum,$group,$action) = @_;
                   10108:     my ($from_namespace,$to_namespace);
                   10109:     if ($action eq 'delete') {
                   10110:         $from_namespace = 'coursegroups';
                   10111:         $to_namespace = 'deleted_groups';
                   10112:     } else {
                   10113:         $from_namespace = 'deleted_groups';
                   10114:         $to_namespace = 'coursegroups';
                   10115:     }
                   10116:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  10117:     if (my $tmp = &error(%curr_group)) {
                   10118:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   10119:         return ('read error',$tmp);
                   10120:     } else {
                   10121:         my %savedsettings = %curr_group; 
1.809     raeburn  10122:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  10123:         my $deloutcome;
                   10124:         if ($result eq 'ok') {
1.809     raeburn  10125:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  10126:         } else {
                   10127:             return ('write error',$result);
                   10128:         }
                   10129:         if ($deloutcome eq 'ok') {
                   10130:             return 'ok';
                   10131:         } else {
                   10132:             return ('delete error',$deloutcome);
                   10133:         }
                   10134:     }
                   10135: }
                   10136: 
1.679     raeburn  10137: sub modify_group_roles {
1.957     raeburn  10138:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  10139:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   10140:     my $role = 'gr/'.&escape($userprivs);
                   10141:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  10142:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  10143:     if ($result eq 'ok') {
                   10144:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   10145:     }
1.679     raeburn  10146:     return $result;
                   10147: }
                   10148: 
                   10149: sub modify_coursegroup_membership {
                   10150:     my ($cdom,$cnum,$membership) = @_;
                   10151:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   10152:     return $result;
                   10153: }
                   10154: 
1.682     raeburn  10155: sub get_active_groups {
                   10156:     my ($udom,$uname,$cdom,$cnum) = @_;
                   10157:     my $now = time;
                   10158:     my %groups = ();
                   10159:     foreach my $key (keys(%env)) {
1.811     albertel 10160:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  10161:             my ($start,$end) = split(/\./,$env{$key});
                   10162:             if (($end!=0) && ($end<$now)) { next; }
                   10163:             if (($start!=0) && ($start>$now)) { next; }
                   10164:             if ($1 eq $cdom && $2 eq $cnum) {
                   10165:                 $groups{$3} = $env{$key} ;
                   10166:             }
                   10167:         }
                   10168:     }
                   10169:     return %groups;
                   10170: }
                   10171: 
1.683     raeburn  10172: sub get_group_membership {
                   10173:     my ($cdom,$cnum,$group) = @_;
                   10174:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   10175: }
                   10176: 
                   10177: sub get_users_groups {
                   10178:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  10179:     my @usersgroups;
1.683     raeburn  10180:     my $cachetime=1800;
                   10181: 
                   10182:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  10183:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   10184:     if (defined($cached)) {
1.734     albertel 10185:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  10186:     } else {  
                   10187:         $grouplist = '';
1.816     raeburn  10188:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  10189:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  10190:         my $access_end = $env{'course.'.$courseid.
                   10191:                               '.default_enrollment_end_date'};
                   10192:         my $now = time;
                   10193:         foreach my $key (keys(%roleshash)) {
                   10194:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   10195:                 my $group = $1;
                   10196:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   10197:                     my $start = $2;
                   10198:                     my $end = $1;
                   10199:                     if ($start == -1) { next; } # deleted from group
                   10200:                     if (($start!=0) && ($start>$now)) { next; }
                   10201:                     if (($end!=0) && ($end<$now)) {
                   10202:                         if ($access_end && $access_end < $now) {
                   10203:                             if ($access_end - $end < 86400) {
                   10204:                                 push(@usersgroups,$group);
1.733     raeburn  10205:                             }
                   10206:                         }
1.817     raeburn  10207:                         next;
1.733     raeburn  10208:                     }
1.817     raeburn  10209:                     push(@usersgroups,$group);
1.683     raeburn  10210:                 }
                   10211:             }
                   10212:         }
1.817     raeburn  10213:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   10214:         $grouplist = join(':',@usersgroups);
                   10215:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  10216:     }
1.733     raeburn  10217:     return @usersgroups;
1.683     raeburn  10218: }
                   10219: 
                   10220: sub devalidate_getgroups_cache {
                   10221:     my ($udom,$uname,$cdom,$cnum)=@_;
                   10222:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 10223: 
1.683     raeburn  10224:     my $hashid="$udom:$uname:$courseid";
                   10225:     &devalidate_cache_new('getgroups',$hashid);
                   10226: }
                   10227: 
1.12      www      10228: # ------------------------------------------------------------------ Plain Text
                   10229: 
                   10230: sub plaintext {
1.988     raeburn  10231:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  10232:     if ($short =~ m{^cr/}) {
1.758     albertel 10233: 	return (split('/',$short))[-1];
                   10234:     }
1.742     raeburn  10235:     if (!defined($cid)) {
                   10236:         $cid = $env{'request.course.id'};
                   10237:     }
                   10238:     my %rolenames = (
1.1008    raeburn  10239:                       Course    => 'std',
                   10240:                       Community => 'alt1',
1.1305    raeburn  10241:                       Placement => 'std',
1.742     raeburn  10242:                     );
1.1037    raeburn  10243:     if ($cid ne '') {
                   10244:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   10245:             unless ($forcedefault) {
                   10246:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   10247:                 &Apache::lonlocal::mt_escape(\$roletext);
                   10248:                 return &Apache::lonlocal::mt($roletext);
                   10249:             }
                   10250:         }
                   10251:     }
                   10252:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   10253:         (defined($rolenames{$type})) && 
                   10254:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  10255:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  10256:     } elsif ($cid ne '') {
                   10257:         my $crstype = $env{'course.'.$cid.'.type'};
                   10258:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   10259:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   10260:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   10261:         }
1.742     raeburn  10262:     }
1.1037    raeburn  10263:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      10264: }
                   10265: 
                   10266: # ----------------------------------------------------------------- Assign Role
                   10267: 
                   10268: sub assignrole {
1.957     raeburn  10269:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   10270:         $context)=@_;
1.21      www      10271:     my $mrole;
                   10272:     if ($role =~ /^cr\//) {
1.393     www      10273:         my $cwosec=$url;
1.811     albertel 10274:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      10275: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  10276:            my $refused = 1;
                   10277:            if ($context eq 'requestcourses') {
                   10278:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   10279:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   10280:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   10281:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   10282:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10283:                            if ($crsenv{'internal.courseowner'} eq
                   10284:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   10285:                                $refused = '';
                   10286:                            }
                   10287:                        }
                   10288:                    }
                   10289:                }
                   10290:            }
                   10291:            if ($refused) {
                   10292:                &logthis('Refused custom assignrole: '.
                   10293:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   10294:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   10295:                return 'refused';
                   10296:            }
1.104     www      10297:         }
1.21      www      10298:         $mrole='cr';
1.678     raeburn  10299:     } elsif ($role =~ /^gr\//) {
                   10300:         my $cwogrp=$url;
1.811     albertel 10301:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  10302:         unless (&allowed('mdg',$cwogrp)) {
                   10303:             &logthis('Refused group assignrole: '.
                   10304:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   10305:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   10306:             return 'refused';
                   10307:         }
                   10308:         $mrole='gr';
1.21      www      10309:     } else {
1.82      www      10310:         my $cwosec=$url;
1.811     albertel 10311:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  10312:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   10313:             my $refused;
                   10314:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   10315:                 if (!(&allowed('c'.$role,$url))) {
                   10316:                     $refused = 1;
                   10317:                 }
                   10318:             } else {
                   10319:                 $refused = 1;
                   10320:             }
1.947     raeburn  10321:             if ($refused) {
1.1045    raeburn  10322:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
1.1377    raeburn  10323:                 if (!$selfenroll && (($context eq 'course') || ($context eq 'ltienroll' && $env{'request.lti.login'}))) {
1.1045    raeburn  10324:                     my %crsenv;
                   10325:                     if ($role eq 'cc' || $role eq 'co') {
                   10326:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10327:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   10328:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   10329:                                 if ($crsenv{'internal.courseowner'} eq 
                   10330:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10331:                                     $refused = '';
                   10332:                                 }
                   10333:                             }
                   10334:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   10335:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   10336:                                 if ($crsenv{'internal.courseowner'} eq 
                   10337:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   10338:                                     $refused = '';
                   10339:                                 }
                   10340:                             }
                   10341:                         }
                   10342:                     }
1.1368    raeburn  10343:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   10344:                     if ($role eq 'st') {
                   10345:                         $refused = '';
1.1377    raeburn  10346:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti.login'})) {
1.1368    raeburn  10347:                         $refused = '';
                   10348:                     }
1.1017    raeburn  10349:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  10350:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  10351:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  10352:                         my $wrongcc;
                   10353:                         if ($cnum =~ /^$match_community$/) {
                   10354:                             $wrongcc = 1 if ($role eq 'cc');
                   10355:                         } else {
                   10356:                             $wrongcc = 1 if ($role eq 'co');
                   10357:                         }
                   10358:                         unless ($wrongcc) {
                   10359:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   10360:                             if ($crsenv{'internal.courseowner'} eq 
                   10361:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   10362:                                 $refused = '';
                   10363:                             }
1.1017    raeburn  10364:                         }
                   10365:                     }
1.1183    raeburn  10366:                 } elsif ($context eq 'requestauthor') {
                   10367:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   10368:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   10369:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   10370:                             $refused = '';
                   10371:                         } else {
                   10372:                             my %domdefaults = &get_domain_defaults($udom);
                   10373:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   10374:                                 my $checkbystatus;
                   10375:                                 if ($env{'user.adv'}) { 
                   10376:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   10377:                                     if ($disposition eq 'automatic') {
                   10378:                                         $refused = '';
                   10379:                                     } elsif ($disposition eq '') {
                   10380:                                         $checkbystatus = 1;
                   10381:                                     } 
                   10382:                                 } else {
                   10383:                                     $checkbystatus = 1;
                   10384:                                 }
                   10385:                                 if ($checkbystatus) {
                   10386:                                     if ($env{'environment.inststatus'}) {
                   10387:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   10388:                                         foreach my $type (@inststatuses) {
                   10389:                                             if (($type ne '') &&
                   10390:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   10391:                                                 $refused = '';
                   10392:                                             }
                   10393:                                         }
                   10394:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   10395:                                         $refused = '';
                   10396:                                     }
                   10397:                                 }
                   10398:                             }
                   10399:                         }
                   10400:                     }
1.1017    raeburn  10401:                 }
                   10402:                 if ($refused) {
1.947     raeburn  10403:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   10404:                              ' '.$role.' '.$end.' '.$start.' by '.
                   10405: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   10406:                     return 'refused';
                   10407:                 }
1.932     raeburn  10408:             }
1.1131    raeburn  10409:         } elsif ($role eq 'au') {
                   10410:             if ($url ne '/'.$udom.'/') {
                   10411:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   10412:                          ' to assign author role for '.$uname.':'.$udom.
                   10413:                          ' in domain: '.$url.' refused (wrong domain).');
                   10414:                 return 'refused';
                   10415:             }
1.104     www      10416:         }
1.21      www      10417:         $mrole=$role;
                   10418:     }
1.620     albertel 10419:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      10420:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      10421:     if ($end) { $command.='_'.$end; }
1.21      www      10422:     if ($start) {
                   10423: 	if ($end) { 
1.81      www      10424:            $command.='_'.$start; 
1.21      www      10425:         } else {
1.81      www      10426:            $command.='_0_'.$start;
1.21      www      10427:         }
                   10428:     }
1.739     raeburn  10429:     my $origstart = $start;
                   10430:     my $origend = $end;
1.957     raeburn  10431:     my $delflag;
1.357     www      10432: # actually delete
                   10433:     if ($deleteflag) {
1.373     www      10434: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      10435: # modify command to delete the role
1.620     albertel 10436:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      10437:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 10438: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      10439: # set start and finish to negative values for userrolelog
                   10440:            $start=-1;
                   10441:            $end=-1;
1.957     raeburn  10442:            $delflag = 1;
1.357     www      10443:         }
                   10444:     }
                   10445: # send command
1.349     www      10446:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      10447: # log new user role if status is ok
1.349     www      10448:     if ($answer eq 'ok') {
1.663     raeburn  10449: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  10450:         if (($role eq 'cc') || ($role eq 'in') ||
                   10451:             ($role eq 'ep') || ($role eq 'ad') ||
                   10452:             ($role eq 'ta') || ($role eq 'st') ||
                   10453:             ($role=~/^cr/) || ($role eq 'gr') ||
                   10454:             ($role eq 'co')) {
1.1200    raeburn  10455: # for course roles, perform group memberships changes triggered by role change.
                   10456:             unless ($role =~ /^gr/) {
                   10457:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   10458:                                                  $origstart,$selfenroll,$context);
                   10459:             }
1.1184    raeburn  10460:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10461:                            $selfenroll,$context);
                   10462:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  10463:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   10464:                  ($role eq 'da')) {
1.1184    raeburn  10465:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10466:                            $context);
                   10467:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   10468:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   10469:                              $context); 
                   10470:         }
1.1053    raeburn  10471:         if ($role eq 'cc') {
                   10472:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   10473:         }
1.349     www      10474:     }
                   10475:     return $answer;
1.169     harris41 10476: }
                   10477: 
1.1053    raeburn  10478: sub autoupdate_coowners {
                   10479:     my ($url,$end,$start,$uname,$udom) = @_;
                   10480:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   10481:     if (($cdom ne '') && ($cnum ne '')) {
                   10482:         my $now = time;
                   10483:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   10484:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   10485:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   10486:             my $instcode = $coursehash{'internal.coursecode'};
1.1444    raeburn  10487:             my $xlists = $coursehash{'internal.crosslistings'};
1.1053    raeburn  10488:             if ($instcode ne '') {
1.1056    raeburn  10489:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   10490:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  10491:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  10492:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
1.1444    raeburn  10493:                         unless ($result eq 'valid') {
                   10494:                             if ($xlists ne '') {
                   10495:                                 foreach my $xlist (split(',',$xlists)) {
                   10496:                                     my ($inst_crosslist,$lcsec) = split(':',$xlist);
                   10497:                                     $result =
1.1446    raeburn  10498:                                         &auto_validate_inst_crosslist($cnum,$cdom,$instcode,
                   10499:                                                                       $inst_crosslist,$uname.':'.$udom);
                   10500:                                     last if ($result eq 'valid');
1.1444    raeburn  10501:                                 }
                   10502:                             }
                   10503:                         }
1.1056    raeburn  10504:                         if ($result eq 'valid') {
                   10505:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  10506:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10507:                                     push(@newcoowners,$coowner);
                   10508:                                 }
                   10509:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   10510:                                     push(@newcoowners,$uname.':'.$udom);
                   10511:                                 }
                   10512:                                 @newcoowners = sort(@newcoowners);
                   10513:                             } else {
                   10514:                                 push(@newcoowners,$uname.':'.$udom);
                   10515:                             }
1.1444    raeburn  10516:                         } elsif ($coursehash{'internal.co-owners'}) {
                   10517:                             foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   10518:                                 unless ($coowner eq $uname.':'.$udom) {
                   10519:                                     push(@newcoowners,$coowner);
1.1053    raeburn  10520:                                 }
1.1444    raeburn  10521:                             }
                   10522:                             unless (@newcoowners > 0) {
                   10523:                                 $delcoowners = 1;
                   10524:                                 $coowners = '';
1.1053    raeburn  10525:                             }
                   10526:                         }
                   10527:                         if (@newcoowners || $delcoowners) {
                   10528:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   10529:                                             $delcoowners,@newcoowners);
                   10530:                         }
                   10531:                     }
                   10532:                 }
                   10533:             }
                   10534:         }
                   10535:     }
                   10536: }
                   10537: 
                   10538: sub store_coowners {
                   10539:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   10540:     my $cid = $cdom.'_'.$cnum;
                   10541:     my ($coowners,$delresult,$putresult);
                   10542:     if (@newcoowners) {
                   10543:         $coowners = join(',',@newcoowners);
                   10544:         my %coownershash = (
                   10545:                             'internal.co-owners' => $coowners,
                   10546:                            );
                   10547:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   10548:         if ($putresult eq 'ok') {
                   10549:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   10550:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   10551:             }
                   10552:         }
                   10553:     }
                   10554:     if ($delcoowners) {
                   10555:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   10556:         if ($delresult eq 'ok') {
                   10557:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   10558:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   10559:             }
                   10560:         }
                   10561:     }
                   10562:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   10563:         my %crsinfo =
                   10564:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   10565:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   10566:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   10567:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   10568:         }
                   10569:     }
                   10570: }
                   10571: 
1.169     harris41 10572: # -------------------------------------------------- Modify user authentication
1.197     www      10573: # Overrides without validation
                   10574: 
1.169     harris41 10575: sub modifyuserauth {
                   10576:     my ($udom,$uname,$umode,$upass)=@_;
                   10577:     my $uhome=&homeserver($uname,$udom);
1.1409    raeburn  10578:     my $allowed;
                   10579:     if (&allowed('mau',$udom)) {
                   10580:         $allowed = 1;
                   10581:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
                   10582:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
                   10583:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
                   10584:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10585:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   10586:         if (($cdom ne '') && ($cnum ne '')) {
                   10587:             my $is_owner = &is_course_owner($cdom,$cnum);
                   10588:             if ($is_owner) {
                   10589:                 $allowed = 1;
                   10590:             }
                   10591:         }
                   10592:     }
                   10593:     unless ($allowed) { return 'refused'; }
1.197     www      10594:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 10595:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10596:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 10597:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   10598: 		     &escape($upass),$uhome);
1.1434    raeburn  10599:     my $ip = &get_requestor_ip();
1.620     albertel 10600:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      10601:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
1.1434    raeburn  10602:          '(Remote '.$ip.'): '.$reply);
1.197     www      10603:     &log($udom,,$uname,$uhome,
1.620     albertel 10604:         'Authentication changed by '.$env{'user.domain'}.', '.
                   10605:                                      $env{'user.name'}.', '.$umode.
1.1435    raeburn  10606:          '(Remote '.$ip.'): '.$reply);
1.169     harris41 10607:     unless ($reply eq 'ok') {
1.197     www      10608:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 10609: 	return 'error: '.$reply;
                   10610:     }   
1.170     harris41 10611:     return 'ok';
1.80      www      10612: }
                   10613: 
1.81      www      10614: # --------------------------------------------------------------- Modify a user
1.80      www      10615: 
1.81      www      10616: sub modifyuser {
1.206     matthew  10617:     my ($udom,    $uname, $uid,
                   10618:         $umode,   $upass, $first,
                   10619:         $middle,  $last,  $gene,
1.1058    raeburn  10620:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 10621:     $udom= &LONCAPA::clean_domain($udom);
                   10622:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  10623:     my $showcandelete = 'none';
                   10624:     if (ref($candelete) eq 'ARRAY') {
                   10625:         if (@{$candelete} > 0) {
                   10626:             $showcandelete = join(', ',@{$candelete});
                   10627:         }
                   10628:     }
1.81      www      10629:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      10630:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  10631: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  10632:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   10633:                                      ' desiredhome not specified'). 
1.620     albertel 10634:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   10635:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 10636:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  10637:     my $newuser;
                   10638:     if ($uhome eq 'no_host') {
                   10639:         $newuser = 1;
1.1368    raeburn  10640:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   10641:                 ($umode eq 'lti')) {
                   10642:             return 'error: more information needed to create new user';
                   10643:         }
1.1075    raeburn  10644:     }
1.80      www      10645: # ----------------------------------------------------------------- Create User
1.406     albertel 10646:     if (($uhome eq 'no_host') && 
1.1368    raeburn  10647: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      10648:         my $unhome='';
1.844     albertel 10649:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  10650:             $unhome = $desiredhome;
1.620     albertel 10651: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   10652: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  10653:         } else { # load balancing routine for determining $unhome
1.81      www      10654:             my $loadm=10000000;
1.841     albertel 10655: 	    my %servers = &get_servers($udom,'library');
                   10656: 	    foreach my $tryserver (keys(%servers)) {
                   10657: 		my $answer=reply('load',$tryserver);
                   10658: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   10659: 		    $loadm=$answer;
                   10660: 		    $unhome=$tryserver;
                   10661: 		}
1.80      www      10662: 	    }
                   10663:         }
                   10664:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  10665: 	    return 'error: unable to find a home server for '.$uname.
                   10666:                    ' in domain '.$udom;
1.80      www      10667:         }
                   10668:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   10669:                          &escape($upass),$unhome);
                   10670: 	unless ($reply eq 'ok') {
                   10671:             return 'error: '.$reply;
                   10672:         }   
1.230     stredwic 10673:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      10674:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  10675: 	    return 'error: unable verify users home machine.';
1.80      www      10676:         }
1.209     matthew  10677:     }   # End of creation of new user
1.80      www      10678: # ---------------------------------------------------------------------- Add ID
                   10679:     if ($uid) {
                   10680:        $uid=~tr/A-Z/a-z/;
                   10681:        my %uidhash=&idrget($udom,$uname);
1.196     www      10682:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   10683:          && (!$forceid)) {
1.80      www      10684: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  10685: 	      return 'error: user id "'.$uid.'" does not match '.
                   10686:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      10687:           }
                   10688:        } else {
1.1300    raeburn  10689: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      10690:        }
                   10691:     }
                   10692: # -------------------------------------------------------------- Add names, etc
1.313     matthew  10693:     my @tmp=&get('environment',
1.899     raeburn  10694: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  10695:                     'permanentemail','inststatus'],
1.134     albertel 10696: 		   $udom,$uname);
1.1075    raeburn  10697:     my (%names,%oldnames);
1.313     matthew  10698:     if ($tmp[0] =~ m/^error:.*/) { 
                   10699:         %names=(); 
                   10700:     } else {
                   10701:         %names = @tmp;
1.1075    raeburn  10702:         %oldnames = %names;
1.313     matthew  10703:     }
1.388     www      10704: #
1.1058    raeburn  10705: # If name, email and/or uid are blank (e.g., because an uploaded file
                   10706: # of users did not contain them), do not overwrite existing values
                   10707: # unless field is in $candelete array ref.  
                   10708: #
                   10709: 
                   10710:     my @fields = ('firstname','middlename','lastname','generation',
                   10711:                   'permanentemail','id');
                   10712:     my %newvalues;
                   10713:     if (ref($candelete) eq 'ARRAY') {
                   10714:         foreach my $field (@fields) {
                   10715:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   10716:                 if ($field eq 'firstname') {
                   10717:                     $names{$field} = $first;
                   10718:                 } elsif ($field eq 'middlename') {
                   10719:                     $names{$field} = $middle;
                   10720:                 } elsif ($field eq 'lastname') {
                   10721:                     $names{$field} = $last;
                   10722:                 } elsif ($field eq 'generation') { 
                   10723:                     $names{$field} = $gene;
                   10724:                 } elsif ($field eq 'permanentemail') {
                   10725:                     $names{$field} = $email;
                   10726:                 } elsif ($field eq 'id') {
                   10727:                     $names{$field}  = $uid;
                   10728:                 }
                   10729:             }
                   10730:         }
                   10731:     }
1.388     www      10732:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  10733:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      10734:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  10735:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      10736:     if ($email) {
                   10737:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  10738:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      10739:     }
1.899     raeburn  10740:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  10741:     if (defined($inststatus)) {
                   10742:         $names{'inststatus'} = '';
                   10743:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   10744:         if (ref($usertypes) eq 'HASH') {
                   10745:             my @okstatuses; 
                   10746:             foreach my $item (split(/:/,$inststatus)) {
                   10747:                 if (defined($usertypes->{$item})) {
                   10748:                     push(@okstatuses,$item);  
                   10749:                 }
                   10750:             }
                   10751:             if (@okstatuses) {
                   10752:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   10753:             }
                   10754:         }
                   10755:     }
1.1075    raeburn  10756:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  10757:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  10758:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  10759:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   10760:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   10761:     } else {
                   10762:         $logmsg .= ' during self creation';
                   10763:     }
1.1075    raeburn  10764:     my $changed;
                   10765:     if ($newuser) {
                   10766:         $changed = 1;
                   10767:     } else {
                   10768:         foreach my $field (@fields) {
                   10769:             if ($names{$field} ne $oldnames{$field}) {
                   10770:                 $changed = 1;
                   10771:                 last;
                   10772:             }
                   10773:         }
                   10774:     }
                   10775:     unless ($changed) {
                   10776:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   10777:         &logthis($logmsg);
                   10778:         return 'ok';
                   10779:     }
                   10780:     my $reply = &put('environment', \%names, $udom,$uname);
                   10781:     if ($reply ne 'ok') { 
                   10782:         return 'error: '.$reply;
                   10783:     }
1.1087    raeburn  10784:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   10785:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   10786:     }
1.1075    raeburn  10787:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   10788:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   10789:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  10790:     &logthis($logmsg);
1.134     albertel 10791:     return 'ok';
1.80      www      10792: }
                   10793: 
1.81      www      10794: # -------------------------------------------------------------- Modify student
1.80      www      10795: 
1.81      www      10796: sub modifystudent {
                   10797:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  10798:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  10799:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 10800:     if (!$cid) {
1.620     albertel 10801: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10802: 	    return 'not_in_class';
                   10803: 	}
1.80      www      10804:     }
                   10805: # --------------------------------------------------------------- Make the user
1.81      www      10806:     my $reply=&modifyuser
1.209     matthew  10807: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  10808:          $desiredhome,$email,$inststatus);
1.80      www      10809:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  10810:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  10811:     # student's environment
1.297     matthew  10812:     $uid = undef if (!$forceid);
1.455     albertel 10813:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  10814:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  10815:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  10816:     return $reply;
                   10817: }
                   10818: 
                   10819: sub modify_student_enrollment {
1.1216    raeburn  10820:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  10821:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 10822:     my ($cdom,$cnum,$chome);
                   10823:     if (!$cid) {
1.620     albertel 10824: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 10825: 	    return 'not_in_class';
                   10826: 	}
1.620     albertel 10827: 	$cdom=$env{'course.'.$cid.'.domain'};
                   10828: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 10829:     } else {
                   10830: 	($cdom,$cnum)=split(/_/,$cid);
                   10831:     }
1.620     albertel 10832:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 10833:     if (!$chome) {
1.457     raeburn  10834: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  10835:     }
1.455     albertel 10836:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  10837:     # Make sure the user exists
1.81      www      10838:     my $uhome=&homeserver($uname,$udom);
                   10839:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   10840: 	return 'error: no such user';
                   10841:     }
1.297     matthew  10842:     # Get student data if we were not given enough information
                   10843:     if (!defined($first)  || $first  eq '' || 
                   10844:         !defined($last)   || $last   eq '' || 
                   10845:         !defined($uid)    || $uid    eq '' || 
                   10846:         !defined($middle) || $middle eq '' || 
                   10847:         !defined($gene)   || $gene   eq '') {
1.294     matthew  10848:         # They did not supply us with enough data to enroll the student, so
                   10849:         # we need to pick up more information.
1.297     matthew  10850:         my %tmp = &get('environment',
1.294     matthew  10851:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  10852:                        ,$udom,$uname);
                   10853: 
1.800     albertel 10854:         #foreach my $key (keys(%tmp)) {
                   10855:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 10856:         #}
1.294     matthew  10857:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   10858:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   10859:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  10860:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  10861:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   10862:     }
1.556     albertel 10863:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  10864:     my $user = "$uname:$udom";
                   10865:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 10866:     my $reply=cput('classlist',
1.1148    raeburn  10867: 		   {$user => 
1.1314    raeburn  10868: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 10869: 		   $cdom,$cnum);
1.1148    raeburn  10870:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   10871:         &devalidate_getsection_cache($udom,$uname,$cid);
                   10872:     } else { 
1.81      www      10873: 	return 'error: '.$reply;
                   10874:     }
1.297     matthew  10875:     # Add student role to user
1.83      www      10876:     my $uurl='/'.$cid;
1.81      www      10877:     $uurl=~s/\_/\//g;
                   10878:     if ($usec) {
                   10879: 	$uurl.='/'.$usec;
                   10880:     }
1.1148    raeburn  10881:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   10882:                              $selfenroll,$context);
                   10883:     if ($result ne 'ok') {
                   10884:         if ($old_entry{$user} ne '') {
                   10885:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   10886:         } else {
                   10887:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   10888:         }
                   10889:     }
                   10890:     return $result; 
1.21      www      10891: }
                   10892: 
1.556     albertel 10893: sub format_name {
                   10894:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   10895:     my $name;
                   10896:     if ($first ne 'lastname') {
                   10897: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   10898:     } else {
                   10899: 	if ($lastname=~/\S/) {
                   10900: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   10901: 	    $name=~s/\s+,/,/;
                   10902: 	} else {
                   10903: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   10904: 	}
                   10905:     }
                   10906:     $name=~s/^\s+//;
                   10907:     $name=~s/\s+$//;
                   10908:     $name=~s/\s+/ /g;
                   10909:     return $name;
                   10910: }
                   10911: 
1.84      www      10912: # ------------------------------------------------- Write to course preferences
                   10913: 
                   10914: sub writecoursepref {
                   10915:     my ($courseid,%prefs)=@_;
                   10916:     $courseid=~s/^\///;
                   10917:     $courseid=~s/\_/\//g;
                   10918:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   10919:     my $chome=homeserver($cnum,$cdomain);
                   10920:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   10921: 	return 'error: no such course';
                   10922:     }
                   10923:     my $cstring='';
1.800     albertel 10924:     foreach my $pref (keys(%prefs)) {
                   10925: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 10926:     }
1.84      www      10927:     $cstring=~s/\&$//;
                   10928:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   10929: }
                   10930: 
                   10931: # ---------------------------------------------------------- Make/modify course
                   10932: 
                   10933: sub createcourse {
1.741     raeburn  10934:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1423    raeburn  10935:         $course_owner,$crstype,$cnum,$context,$category,$callercontext)=@_;
1.84      www      10936:     $url=&declutter($url);
                   10937:     my $cid='';
1.1028    raeburn  10938:     if ($context eq 'requestcourses') {
                   10939:         my $can_create = 0;
                   10940:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   10941:         if ($udom eq $ownerdom) {
1.1423    raeburn  10942:             my $reload;
                   10943:             if (($callercontext eq 'auto') &&
                   10944:                ($ownerdom eq $env{'user.domain'}) && ($ownername eq $env{'user.name'})) {
                   10945:                 $reload = 'reload';
                   10946:             }
                   10947:             if (&usertools_access($ownername,$ownerdom,$category,$reload,
1.1028    raeburn  10948:                                   $context)) {
                   10949:                 $can_create = 1;
                   10950:             }
                   10951:         } else {
                   10952:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   10953:                                            $category);
                   10954:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   10955:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   10956:                 if (@curr > 0) {
                   10957:                     my @options = qw(approval validate autolimit);
                   10958:                     my $optregex = join('|',@options);
                   10959:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   10960:                         $can_create = 1;
                   10961:                     }
                   10962:                 }
                   10963:             }
                   10964:         }
                   10965:         if ($can_create) {
                   10966:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   10967:                 unless (&allowed('ccc',$udom)) {
                   10968:                     return 'refused'; 
                   10969:                 }
1.1017    raeburn  10970:             }
                   10971:         } else {
                   10972:             return 'refused';
                   10973:         }
1.1028    raeburn  10974:     } elsif (!&allowed('ccc',$udom)) {
                   10975:         return 'refused';
1.84      www      10976:     }
1.1011    raeburn  10977: # --------------------------------------------------------------- Get Unique ID
                   10978:     my $uname;
                   10979:     if ($cnum =~ /^$match_courseid$/) {
                   10980:         my $chome=&homeserver($cnum,$udom,'true');
                   10981:         if (($chome eq '') || ($chome eq 'no_host')) {
                   10982:             $uname = $cnum;
                   10983:         } else {
1.1038    raeburn  10984:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10985:         }
                   10986:     } else {
1.1038    raeburn  10987:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  10988:     }
                   10989:     return $uname if ($uname =~ /^error/);
                   10990: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  10991:     if (!defined($course_server)) {
                   10992:         if (defined(&domain($udom,'primary'))) {
                   10993:             $course_server = &domain($udom,'primary');
                   10994:         } else {
                   10995:             $course_server = $env{'user.home'}; 
                   10996:         }
                   10997:     }
                   10998:     my %host_servers =
                   10999:         &Apache::lonnet::get_servers($udom,'library');
                   11000:     unless ($host_servers{$course_server}) {
                   11001:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  11002:     }
1.84      www      11003: # ------------------------------------------------------------- Make the course
                   11004:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  11005:                       $course_server);
1.84      www      11006:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  11007:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      11008:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   11009: 	return 'error: no such course';
                   11010:     }
1.271     www      11011: # ----------------------------------------------------------------- Course made
1.516     raeburn  11012: # log existence
1.1029    raeburn  11013:     my $now = time;
1.918     raeburn  11014:     my $newcourse = {
                   11015:                     $udom.'_'.$uname => {
1.921     raeburn  11016:                                      description => $description,
                   11017:                                      inst_code   => $inst_code,
                   11018:                                      owner       => $course_owner,
                   11019:                                      type        => $crstype,
1.1029    raeburn  11020:                                      creator     => $env{'user.name'}.':'.
                   11021:                                                     $env{'user.domain'},
                   11022:                                      created     => $now,
                   11023:                                      context     => $context,
1.918     raeburn  11024:                                                 },
                   11025:                     };
1.921     raeburn  11026:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      11027: # set toplevel url
1.271     www      11028:     my $topurl=$url;
                   11029:     unless ($nonstandard) {
                   11030: # ------------------------------------------ For standard courses, make top url
                   11031:         my $mapurl=&clutter($url);
1.278     www      11032:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 11033:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      11034: <map>
                   11035: <resource id="1" type="start"></resource>
                   11036: <resource id="2" src="$mapurl"></resource>
                   11037: <resource id="3" type="finish"></resource>
                   11038: <link index="1" from="1" to="2"></link>
                   11039: <link index="2" from="2" to="3"></link>
                   11040: </map>
                   11041: ENDINITMAP
                   11042:         $topurl=&declutter(
1.638     albertel 11043:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      11044:                           );
                   11045:     }
                   11046: # ----------------------------------------------------------- Write preferences
1.84      www      11047:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  11048:                      ('description'              => $description,
                   11049:                       'url'                      => $topurl,
                   11050:                       'internal.creator'         => $env{'user.name'}.':'.
                   11051:                                                     $env{'user.domain'},
                   11052:                       'internal.created'         => $now,
                   11053:                       'internal.creationcontext' => $context)
                   11054:                     );
1.84      www      11055:     return '/'.$udom.'/'.$uname;
                   11056: }
                   11057: 
1.1011    raeburn  11058: # ------------------------------------------------------------------- Create ID
                   11059: sub generate_coursenum {
1.1038    raeburn  11060:     my ($udom,$crstype) = @_;
1.1011    raeburn  11061:     my $domdesc = &domain($udom);
                   11062:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  11063:     my $first;
                   11064:     if ($crstype eq 'Community') {
                   11065:         $first = '0';
                   11066:     } else {
                   11067:         $first = int(1+rand(9)); 
                   11068:     } 
                   11069:     my $uname=$first.
1.1011    raeburn  11070:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   11071:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   11072:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   11073: # ----------------------------------------------- Make sure that does not exist
                   11074:     my $uhome=&homeserver($uname,$udom,'true');
                   11075:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  11076:         if ($crstype eq 'Community') {
                   11077:             $first = '0';
                   11078:         } else {
                   11079:             $first = int(1+rand(9));
                   11080:         }
                   11081:         $uname=$first.
1.1011    raeburn  11082:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   11083:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   11084:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   11085:         $uhome=&homeserver($uname,$udom,'true');
                   11086:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   11087:             return 'error: unable to generate unique course-ID';
                   11088:         }
                   11089:     }
                   11090:     return $uname;
                   11091: }
                   11092: 
1.813     albertel 11093: sub is_course {
1.1167    droeschl 11094:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   11095:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   11096: 
1.1381    raeburn  11097:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
                   11098:     my $uhome=&homeserver($cnum,$cdom);
                   11099:     my $iscourse;
                   11100:     if (grep { $_ eq $uhome } current_machine_ids()) {
1.1382    raeburn  11101:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
1.1381    raeburn  11102:     } else {
                   11103:         my $hashid = $cdom.':'.$cnum;
                   11104:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
                   11105:         unless (defined($cached)) {
                   11106:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
                   11107:                                         $cnum,undef,undef,'.');
                   11108:             $iscourse = 0;
                   11109:             if (exists($courses{$cdom.'_'.$cnum})) {
                   11110:                 $iscourse = 1;
                   11111:             }
                   11112:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
                   11113:         }
                   11114:     }
                   11115:     return unless ($iscourse);
1.1167    droeschl 11116:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 11117: }
                   11118: 
1.1015    raeburn  11119: sub store_userdata {
                   11120:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  11121:     my $result;
1.1016    raeburn  11122:     if ($datakey ne '') {
1.1013    raeburn  11123:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  11124:             if ($udom eq '' || $uname eq '') {
                   11125:                 $udom = $env{'user.domain'};
                   11126:                 $uname = $env{'user.name'};
                   11127:             }
                   11128:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  11129:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   11130:                 $result = 'error: no_host';
                   11131:             } else {
1.1434    raeburn  11132:                 $storehash->{'ip'} = &get_requestor_ip();
1.1013    raeburn  11133:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   11134: 
                   11135:                 my $namevalue='';
                   11136:                 foreach my $key (keys(%{$storehash})) {
                   11137:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   11138:                 }
                   11139:                 $namevalue=~s/\&$//;
1.1224    raeburn  11140:                 unless ($namespace eq 'courserequests') {
                   11141:                     $datakey = &escape($datakey);
                   11142:                 }
1.1105    raeburn  11143:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   11144:                                   $namevalue,$uhome);
1.1013    raeburn  11145:             }
                   11146:         } else {
                   11147:             $result = 'error: data to store was not a hash reference'; 
                   11148:         }
                   11149:     } else {
                   11150:         $result= 'error: invalid requestkey'; 
                   11151:     }
                   11152:     return $result;
                   11153: }
                   11154: 
1.21      www      11155: # ---------------------------------------------------------- Assign Custom Role
                   11156: 
                   11157: sub assigncustomrole {
1.957     raeburn  11158:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11159:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  11160:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      11161: }
                   11162: 
                   11163: # ----------------------------------------------------------------- Revoke Role
                   11164: 
                   11165: sub revokerole {
1.957     raeburn  11166:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11167:     my $now=time;
1.965     raeburn  11168:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      11169: }
                   11170: 
                   11171: # ---------------------------------------------------------- Revoke Custom Role
                   11172: 
                   11173: sub revokecustomrole {
1.957     raeburn  11174:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      11175:     my $now=time;
1.357     www      11176:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  11177:            $deleteflag,$selfenroll,$context);
1.17      www      11178: }
                   11179: 
1.533     banghart 11180: # ------------------------------------------------------------ Disk usage
1.535     albertel 11181: sub diskusage {
1.955     raeburn  11182:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   11183:     $directorypath =~ s/\/$//;
                   11184:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   11185:                        .&escape($getpropath).':'.&escape($uname).':'
                   11186:                        .&escape($udom),homeserver($uname,$udom));
                   11187:     if ($listing eq 'unknown_cmd') {
                   11188:         if ($getpropath) {
                   11189:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   11190:         }
                   11191:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   11192:     }
1.514     albertel 11193:     return $listing;
1.512     banghart 11194: }
                   11195: 
1.566     banghart 11196: sub is_locked {
1.1096    raeburn  11197:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 11198:     my @check;
                   11199:     my $is_locked;
1.1093    raeburn  11200:     push (@check,$file_name);
1.613     albertel 11201:     my %locked = &get('file_permissions',\@check,
1.620     albertel 11202: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 11203:     my ($tmp)=keys(%locked);
                   11204:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  11205:     
1.566     banghart 11206:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  11207:         $is_locked = 'false';
                   11208:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  11209:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  11210:                $is_locked = 'true';
1.1096    raeburn  11211:                if (ref($which) eq 'ARRAY') {
                   11212:                    push(@{$which},$entry);
                   11213:                } else {
                   11214:                    last;
                   11215:                }
1.745     raeburn  11216:            }
                   11217:        }
1.566     banghart 11218:     } else {
                   11219:         $is_locked = 'false';
                   11220:     }
1.1093    raeburn  11221:     return $is_locked;
1.566     banghart 11222: }
                   11223: 
1.759     albertel 11224: sub declutter_portfile {
                   11225:     my ($file) = @_;
1.833     albertel 11226:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 11227:     return $file;
                   11228: }
                   11229: 
1.559     banghart 11230: # ------------------------------------------------------------- Mark as Read Only
                   11231: 
                   11232: sub mark_as_readonly {
                   11233:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 11234:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11235:     my ($tmp)=keys(%current_permissions);
                   11236:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 11237:     foreach my $file (@{$files}) {
1.759     albertel 11238: 	$file = &declutter_portfile($file);
1.561     banghart 11239:         push(@{$current_permissions{$file}},$what);
1.559     banghart 11240:     }
1.613     albertel 11241:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11242:     return;
                   11243: }
                   11244: 
1.572     banghart 11245: # ------------------------------------------------------------Save Selected Files
                   11246: 
                   11247: sub save_selected_files {
                   11248:     my ($user, $path, @files) = @_;
                   11249:     my $filename = $user."savedfiles";
1.573     banghart 11250:     my @other_files = &files_not_in_path($user, $path);
1.1359    raeburn  11251:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 11252:     foreach my $file (@files) {
1.620     albertel 11253:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 11254:     }
                   11255:     foreach my $file (@other_files) {
1.574     banghart 11256:         print (OUT $file."\n");
1.572     banghart 11257:     }
1.574     banghart 11258:     close (OUT);
1.572     banghart 11259:     return 'ok';
                   11260: }
                   11261: 
1.574     banghart 11262: sub clear_selected_files {
                   11263:     my ($user) = @_;
                   11264:     my $filename = $user."savedfiles";
1.1359    raeburn  11265:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 11266:     print (OUT undef);
                   11267:     close (OUT);
                   11268:     return ("ok");    
                   11269: }
                   11270: 
1.572     banghart 11271: sub files_in_path {
                   11272:     my ($user, $path) = @_;
                   11273:     my $filename = $user."savedfiles";
                   11274:     my %return_files;
1.1359    raeburn  11275:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 11276:     while (my $line_in = <IN>) {
1.574     banghart 11277:         chomp ($line_in);
                   11278:         my @paths_and_file = split (m!/!, $line_in);
                   11279:         my $file_part = pop (@paths_and_file);
                   11280:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 11281:         $path_part.='/';
                   11282:         my $path_and_file = $path_part.$file_part;
                   11283:         if ($path_part eq $path) {
                   11284:             $return_files{$file_part}= 'selected';
                   11285:         }
                   11286:     }
1.574     banghart 11287:     close (IN);
                   11288:     return (\%return_files);
1.572     banghart 11289: }
                   11290: 
                   11291: # called in portfolio select mode, to show files selected NOT in current directory
                   11292: sub files_not_in_path {
                   11293:     my ($user, $path) = @_;
                   11294:     my $filename = $user."savedfiles";
                   11295:     my @return_files;
                   11296:     my $path_part;
1.1359    raeburn  11297:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 11298:     while (my $line = <IN>) {
1.572     banghart 11299:         #ok, I know it's clunky, but I want it to work
1.800     albertel 11300:         my @paths_and_file = split(m|/|, $line);
                   11301:         my $file_part = pop(@paths_and_file);
                   11302:         chomp($file_part);
                   11303:         my $path_part = join('/', @paths_and_file);
1.572     banghart 11304:         $path_part .= '/';
                   11305:         my $path_and_file = $path_part.$file_part;
                   11306:         if ($path_part ne $path) {
1.800     albertel 11307:             push(@return_files, ($path_and_file));
1.572     banghart 11308:         }
                   11309:     }
1.800     albertel 11310:     close(OUT);
1.574     banghart 11311:     return (@return_files);
1.572     banghart 11312: }
                   11313: 
1.1273    raeburn  11314: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   11315:  
                   11316: sub portfiles_versioning {
                   11317:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   11318:     my $portfolio_root = '/userfiles/portfolio';
                   11319:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   11320:     foreach my $file (@{$portfiles}) {
                   11321:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   11322:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   11323:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   11324:         my $getpropath = 1;
                   11325:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   11326:                                              $stu_name,$getpropath);
                   11327:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   11328:         my $new_answer = 
                   11329:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   11330:         if ($new_answer ne 'problem getting file') {
                   11331:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   11332:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   11333:                               [$symb,$env{'request.course.id'},'graded']);
                   11334:         }
                   11335:     }
                   11336: }
                   11337: 
                   11338: sub get_next_version {
                   11339:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   11340:     my $version;
                   11341:     if (ref($dir_list) eq 'ARRAY') {
                   11342:         foreach my $row (@{$dir_list}) {
                   11343:             my ($file) = split(/\&/,$row,2);
                   11344:             my ($file_name,$file_version,$file_ext) =
                   11345:                 &file_name_version_ext($file);
                   11346:             if (($file_name eq $answer_name) &&
                   11347:                 ($file_ext eq $answer_ext)) {
                   11348:                      # gets here if filename and extension match,
                   11349:                      # regardless of version
                   11350:                 if ($file_version ne '') {
                   11351:                     # a versioned file is found  so save it for later
                   11352:                     if ($file_version > $version) {
                   11353:                         $version = $file_version;
                   11354:                     }
                   11355:                 }
                   11356:             }
                   11357:         }
                   11358:     }
                   11359:     $version ++;
                   11360:     return($version);
                   11361: }
                   11362: 
                   11363: sub version_selected_portfile {
                   11364:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   11365:     my ($answer_name,$answer_ver,$answer_ext) =
                   11366:         &file_name_version_ext($file_name);
                   11367:     my $new_answer;
                   11368:     $env{'form.copy'} =
                   11369:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   11370:     if($env{'form.copy'} eq '-1') {
                   11371:         $new_answer = 'problem getting file';
                   11372:     } else {
                   11373:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   11374:         my $copy_result = 
                   11375:             &finishuserfileupload($stu_name,$domain,'copy',
                   11376:                                   '/portfolio'.$directory.$new_answer);
                   11377:     }
                   11378:     undef($env{'form.copy'});
                   11379:     return ($new_answer);
                   11380: }
                   11381: 
                   11382: sub file_name_version_ext {
                   11383:     my ($file)=@_;
                   11384:     my @file_parts = split(/\./, $file);
                   11385:     my ($name,$version,$ext);
                   11386:     if (@file_parts > 1) {
                   11387:         $ext=pop(@file_parts);
                   11388:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   11389:             $version=pop(@file_parts);
                   11390:         }
                   11391:         $name=join('.',@file_parts);
                   11392:     } else {
                   11393:         $name=join('.',@file_parts);
                   11394:     }
                   11395:     return($name,$version,$ext);
                   11396: }
                   11397: 
1.745     raeburn  11398: #----------------------------------------------Get portfolio file permissions
1.629     banghart 11399: 
1.745     raeburn  11400: sub get_portfile_permissions {
                   11401:     my ($domain,$user) = @_;
1.613     albertel 11402:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 11403:     my ($tmp)=keys(%current_permissions);
                   11404:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11405:     return \%current_permissions;
                   11406: }
                   11407: 
                   11408: #---------------------------------------------Get portfolio file access controls
                   11409: 
1.749     raeburn  11410: sub get_access_controls {
1.745     raeburn  11411:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 11412:     my %access;
                   11413:     my $real_file = $file;
                   11414:     $file =~ s/\.meta$//;
1.745     raeburn  11415:     if (defined($file)) {
1.749     raeburn  11416:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   11417:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 11418:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  11419:             }
                   11420:         }
1.745     raeburn  11421:     } else {
1.749     raeburn  11422:         foreach my $key (keys(%{$current_permissions})) {
                   11423:             if ($key =~ /\0accesscontrol$/) {
                   11424:                 if (defined($group)) {
                   11425:                     if ($key !~ m-^\Q$group\E/-) {
                   11426:                         next;
                   11427:                     }
                   11428:                 }
                   11429:                 my ($fullpath) = split(/\0/,$key);
                   11430:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   11431:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   11432:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   11433:                     }
                   11434:                 }
                   11435:             }
                   11436:         }
                   11437:     }
                   11438:     return %access;
                   11439: }
                   11440: 
                   11441: sub modify_access_controls {
                   11442:     my ($file_name,$changes,$domain,$user)=@_;
                   11443:     my ($outcome,$deloutcome);
                   11444:     my %store_permissions;
                   11445:     my %new_values;
                   11446:     my %new_control;
                   11447:     my %translation;
                   11448:     my @deletions = ();
                   11449:     my $now = time;
                   11450:     if (exists($$changes{'activate'})) {
                   11451:         if (ref($$changes{'activate'}) eq 'HASH') {
                   11452:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   11453:             my $numnew = scalar(@newitems);
                   11454:             for (my $i=0; $i<$numnew; $i++) {
                   11455:                 my $newkey = $newitems[$i];
                   11456:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  11457:                 if ($newkey =~ /^\d+:/) { 
                   11458:                     $newkey =~ s/^(\d+)/$newid/;
                   11459:                     $translation{$1} = $newid;
                   11460:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   11461:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   11462:                     $translation{$1} = $newid;
                   11463:                 }
1.749     raeburn  11464:                 $new_values{$file_name."\0".$newkey} = 
                   11465:                                           $$changes{'activate'}{$newitems[$i]};
                   11466:                 $new_control{$newkey} = $now;
                   11467:             }
                   11468:         }
                   11469:     }
                   11470:     my %todelete;
                   11471:     my %changed_items;
                   11472:     foreach my $action ('delete','update') {
                   11473:         if (exists($$changes{$action})) {
                   11474:             if (ref($$changes{$action}) eq 'HASH') {
                   11475:                 foreach my $key (keys(%{$$changes{$action}})) {
                   11476:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   11477:                     if ($action eq 'delete') { 
                   11478:                         $todelete{$itemnum} = 1;
                   11479:                     } else {
                   11480:                         $changed_items{$itemnum} = $key;
                   11481:                     }
                   11482:                 }
1.745     raeburn  11483:             }
                   11484:         }
1.749     raeburn  11485:     }
                   11486:     # get lock on access controls for file.
                   11487:     my $lockhash = {
                   11488:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   11489:                                                        ':'.$env{'user.domain'},
                   11490:                    }; 
                   11491:     my $tries = 0;
                   11492:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11493:    
1.1288    damieng  11494:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  11495:         $tries ++;
1.1289    damieng  11496:         sleep(0.1);
1.749     raeburn  11497:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   11498:     }
                   11499:     if ($gotlock eq 'ok') {
                   11500:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   11501:         my ($tmp)=keys(%curr_permissions);
                   11502:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   11503:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   11504:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   11505:             if (ref($curr_controls) eq 'HASH') {
                   11506:                 foreach my $control_item (keys(%{$curr_controls})) {
                   11507:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   11508:                     if (defined($todelete{$itemnum})) {
                   11509:                         push(@deletions,$file_name."\0".$control_item);
                   11510:                     } else {
                   11511:                         if (defined($changed_items{$itemnum})) {
                   11512:                             $new_control{$changed_items{$itemnum}} = $now;
                   11513:                             push(@deletions,$file_name."\0".$control_item);
                   11514:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   11515:                         } else {
                   11516:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   11517:                         }
                   11518:                     }
1.745     raeburn  11519:                 }
                   11520:             }
                   11521:         }
1.970     raeburn  11522:         my ($group);
                   11523:         if (&is_course($domain,$user)) {
                   11524:             ($group,my $file) = split(/\//,$file_name,2);
                   11525:         }
1.749     raeburn  11526:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   11527:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   11528:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   11529:         #  remove lock
                   11530:         my @del_lock = ($file_name."\0".'locked_access_records');
                   11531:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  11532:         my $sqlresult =
1.970     raeburn  11533:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  11534:                                     $group);
1.749     raeburn  11535:     } else {
                   11536:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  11537:     }
1.749     raeburn  11538:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  11539: }
                   11540: 
1.827     raeburn  11541: sub make_public_indefinitely {
1.1271    raeburn  11542:     my (@requrl) = @_;
                   11543:     return &automated_portfile_access('public',\@requrl);
                   11544: }
                   11545: 
                   11546: sub automated_portfile_access {
                   11547:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  11548:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   11549:         return 'invalid';
                   11550:     }
1.1271    raeburn  11551:     my %urls;
                   11552:     if (ref($addsref) eq 'ARRAY') {
                   11553:         foreach my $requrl (@{$addsref}) {
                   11554:             if (&is_portfolio_url($requrl)) {
                   11555:                 unless (exists($urls{$requrl})) {
                   11556:                     $urls{$requrl} = 'add';
                   11557:                 }
                   11558:             }
                   11559:         }
                   11560:     }
                   11561:     if (ref($delsref) eq 'ARRAY') {
                   11562:         foreach my $requrl (@{$delsref}) { 
                   11563:             if (&is_portfolio_url($requrl)) {
                   11564:                 unless (exists($urls{$requrl})) {
                   11565:                     $urls{$requrl} = 'delete'; 
                   11566:                 }
                   11567:             }
                   11568:         }
                   11569:     }
                   11570:     unless (keys(%urls)) {
                   11571:         return 'invalid';
                   11572:     }
                   11573:     my $ip;
                   11574:     if ($accesstype eq 'ip') {
                   11575:         if (ref($info) eq 'HASH') {
                   11576:             if ($info->{'ip'} ne '') {
                   11577:                 $ip = $info->{'ip'};
                   11578:             }
                   11579:         }
                   11580:         if ($ip eq '') {
                   11581:             return 'invalid';
                   11582:         }
                   11583:     }
                   11584:     my $errors;
1.827     raeburn  11585:     my $now = time;
1.1271    raeburn  11586:     my %current_perms;
                   11587:     foreach my $requrl (sort(keys(%urls))) {
                   11588:         my $action;
                   11589:         if ($urls{$requrl} eq 'add') {
                   11590:             $action = 'activate';
                   11591:         } else {
                   11592:             $action = 'none';
                   11593:         }
                   11594:         my $aclnum = 0;
1.827     raeburn  11595:         my (undef,$udom,$unum,$file_name,$group) =
                   11596:             &parse_portfolio_url($requrl);
1.1271    raeburn  11597:         unless (exists($current_perms{$unum.':'.$udom})) {
                   11598:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   11599:         }
                   11600:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  11601:                                                    $group,$file_name);
                   11602:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   11603:             my ($num,$scope,$end,$start) = 
                   11604:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  11605:             if ($scope eq $accesstype) {
                   11606:                 if (($start <= $now) && ($end == 0)) {
                   11607:                     if ($accesstype eq 'ip') {
                   11608:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   11609:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   11610:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   11611:                                     if ($urls{$requrl} eq 'add') {
                   11612:                                         $action = 'none';
                   11613:                                         last;
                   11614:                                     } else {
                   11615:                                         $action = 'delete';
                   11616:                                         $aclnum = $num;
                   11617:                                         last;
                   11618:                                     }
                   11619:                                 }
                   11620:                             }
                   11621:                         }
                   11622:                     } elsif ($accesstype eq 'public') {
                   11623:                         if ($urls{$requrl} eq 'add') {
                   11624:                             $action = 'none';
                   11625:                             last;
                   11626:                         } else {
                   11627:                             $action = 'delete';
                   11628:                             $aclnum = $num;
                   11629:                             last;
                   11630:                         }
                   11631:                     }
                   11632:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  11633:                     $action = 'update';
                   11634:                     $aclnum = $num;
1.1271    raeburn  11635:                     last;
1.827     raeburn  11636:                 }
                   11637:             }
                   11638:         }
                   11639:         if ($action eq 'none') {
1.1271    raeburn  11640:             next;
1.827     raeburn  11641:         } else {
                   11642:             my %changes;
                   11643:             my $newend = 0;
                   11644:             my $newstart = $now;
1.1271    raeburn  11645:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  11646:             $changes{$action}{$newkey} = {
1.1271    raeburn  11647:                 type => $accesstype,
1.827     raeburn  11648:                 time => {
                   11649:                     start => $newstart,
                   11650:                     end   => $newend,
                   11651:                 },
                   11652:             };
1.1271    raeburn  11653:             if ($accesstype eq 'ip') {
                   11654:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   11655:             }
1.827     raeburn  11656:             my ($outcome,$deloutcome,$new_values,$translation) =
                   11657:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  11658:             unless ($outcome eq 'ok') {
                   11659:                 $errors .= $outcome.' ';
                   11660:             }
1.827     raeburn  11661:         }
1.1271    raeburn  11662:     }
                   11663:     if ($errors) {
                   11664:         $errors =~ s/\s$//;
                   11665:         return $errors;
1.827     raeburn  11666:     } else {
1.1271    raeburn  11667:         return 'ok';
1.827     raeburn  11668:     }
                   11669: }
                   11670: 
1.745     raeburn  11671: #------------------------------------------------------Get Marked as Read Only
                   11672: 
                   11673: sub get_marked_as_readonly {
                   11674:     my ($domain,$user,$what,$group) = @_;
                   11675:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 11676:     my @readonly_files;
1.629     banghart 11677:     my $cmp1=$what;
                   11678:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  11679:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11680:         if (defined($group)) {
                   11681:             if ($file_name !~ m-^\Q$group\E/-) {
                   11682:                 next;
                   11683:             }
                   11684:         }
1.561     banghart 11685:         if (ref($value) eq "ARRAY"){
                   11686:             foreach my $stored_what (@{$value}) {
1.629     banghart 11687:                 my $cmp2=$stored_what;
1.759     albertel 11688:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  11689:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  11690:                 }
1.629     banghart 11691:                 if ($cmp1 eq $cmp2) {
1.561     banghart 11692:                     push(@readonly_files, $file_name);
1.745     raeburn  11693:                     last;
1.563     banghart 11694:                 } elsif (!defined($what)) {
                   11695:                     push(@readonly_files, $file_name);
1.745     raeburn  11696:                     last;
1.561     banghart 11697:                 }
                   11698:             }
1.745     raeburn  11699:         }
1.561     banghart 11700:     }
                   11701:     return @readonly_files;
                   11702: }
1.577     banghart 11703: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 11704: 
1.577     banghart 11705: sub get_marked_as_readonly_hash {
1.745     raeburn  11706:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 11707:     my %readonly_files;
1.745     raeburn  11708:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   11709:         if (defined($group)) {
                   11710:             if ($file_name !~ m-^\Q$group\E/-) {
                   11711:                 next;
                   11712:             }
                   11713:         }
1.577     banghart 11714:         if (ref($value) eq "ARRAY"){
                   11715:             foreach my $stored_what (@{$value}) {
1.745     raeburn  11716:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 11717:                     foreach my $lock_descriptor(@{$stored_what}) {
                   11718:                         if ($lock_descriptor eq 'graded') {
                   11719:                             $readonly_files{$file_name} = 'graded';
                   11720:                         } elsif ($lock_descriptor eq 'handback') {
                   11721:                             $readonly_files{$file_name} = 'handback';
                   11722:                         } else {
                   11723:                             if (!exists($readonly_files{$file_name})) {
                   11724:                                 $readonly_files{$file_name} = 'locked';
                   11725:                             }
                   11726:                         }
1.745     raeburn  11727:                     }
1.750     banghart 11728:                 } 
1.577     banghart 11729:             }
                   11730:         } 
                   11731:     }
                   11732:     return %readonly_files;
                   11733: }
1.559     banghart 11734: # ------------------------------------------------------------ Unmark as Read Only
                   11735: 
                   11736: sub unmark_as_readonly {
1.629     banghart 11737:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   11738:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  11739:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 11740:     $file_name = &declutter_portfile($file_name);
1.634     albertel 11741:     my $symb_crs = $what;
                   11742:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  11743:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 11744:     my ($tmp)=keys(%current_permissions);
                   11745:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  11746:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 11747:     foreach my $file (@readonly_files) {
1.759     albertel 11748: 	my $clean_file = &declutter_portfile($file);
                   11749: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 11750: 	my $current_locks = $current_permissions{$file};
1.563     banghart 11751:         my @new_locks;
                   11752:         my @del_keys;
                   11753:         if (ref($current_locks) eq "ARRAY"){
                   11754:             foreach my $locker (@{$current_locks}) {
1.632     albertel 11755:                 my $compare=$locker;
1.749     raeburn  11756:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  11757:                     $compare=join('',@{$locker});
1.746     raeburn  11758:                     if ($compare ne $symb_crs) {
                   11759:                         push(@new_locks, $locker);
                   11760:                     }
1.563     banghart 11761:                 }
                   11762:             }
1.650     albertel 11763:             if (scalar(@new_locks) > 0) {
1.563     banghart 11764:                 $current_permissions{$file} = \@new_locks;
                   11765:             } else {
                   11766:                 push(@del_keys, $file);
1.613     albertel 11767:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 11768:                 delete($current_permissions{$file});
1.563     banghart 11769:             }
                   11770:         }
1.561     banghart 11771:     }
1.613     albertel 11772:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 11773:     return;
                   11774: }
1.512     banghart 11775: 
1.17      www      11776: # ------------------------------------------------------------ Directory lister
                   11777: 
                   11778: sub dirlist {
1.955     raeburn  11779:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      11780:     $uri=~s/^\///;
                   11781:     $uri=~s/\/$//;
1.253     stredwic 11782:     my ($udom, $uname);
1.955     raeburn  11783:     if ($getuserdir) {
1.253     stredwic 11784:         $udom = $userdomain;
                   11785:         $uname = $username;
1.955     raeburn  11786:     } else {
                   11787:         (undef,$udom,$uname)=split(/\//,$uri);
                   11788:         if(defined($userdomain)) {
                   11789:             $udom = $userdomain;
                   11790:         }
                   11791:         if(defined($username)) {
                   11792:             $uname = $username;
                   11793:         }
1.253     stredwic 11794:     }
1.955     raeburn  11795:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 11796: 
1.955     raeburn  11797:     $dirRoot = $perlvar{'lonDocRoot'};
                   11798:     if (defined($getpropath)) {
                   11799:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 11800:         $dirRoot =~ s/\/$//;
1.955     raeburn  11801:     } elsif (defined($getuserdir)) {
                   11802:         my $subdir=$uname.'__';
                   11803:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   11804:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   11805:                    ."/$udom/$subdir/$uname";
                   11806:     } elsif (defined($alternateRoot)) {
                   11807:         $dirRoot = $alternateRoot;
1.751     banghart 11808:     }
1.253     stredwic 11809: 
                   11810:     if($udom) {
                   11811:         if($uname) {
1.1135    raeburn  11812:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  11813:             if ($uhome eq 'no_host') {
                   11814:                 return ([],'no_host');
                   11815:             }
1.955     raeburn  11816:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  11817:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  11818:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  11819:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11820:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  11821:             } else {
                   11822:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11823:             }
1.605     matthew  11824:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  11825:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  11826:                 @listing_results = split(/:/,$listing);
                   11827:             } else {
                   11828:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11829:             }
1.1135    raeburn  11830:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  11831:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11832:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11833:                 return ([],$listing);
                   11834:             } else {
                   11835:                 return (\@listing_results);
1.1135    raeburn  11836:             }
1.955     raeburn  11837:         } elsif(!$alternateRoot) {
1.1136    raeburn  11838:             my (%allusers,%listerror);
1.841     albertel 11839: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  11840:  	    foreach my $tryserver (keys(%servers)) {
                   11841:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   11842:                                   &escape($udom),$tryserver);
                   11843:                 if ($listing eq 'unknown_cmd') {
                   11844: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11845: 				      $udom, $tryserver);
                   11846:                 } else {
                   11847:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   11848:                 }
1.841     albertel 11849: 		if ($listing eq 'unknown_cmd') {
                   11850: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   11851: 				      $udom, $tryserver);
                   11852: 		    @listing_results = split(/:/,$listing);
                   11853: 		} else {
                   11854: 		    @listing_results =
                   11855: 			map { &unescape($_); } split(/:/,$listing);
                   11856: 		}
1.1136    raeburn  11857:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   11858:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   11859:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   11860:                     $listerror{$tryserver} = $listing;
                   11861:                 } else {
1.841     albertel 11862: 		    foreach my $line (@listing_results) {
                   11863: 			my ($entry) = split(/&/,$line,2);
                   11864: 			$allusers{$entry} = 1;
                   11865: 		    }
                   11866: 		}
1.253     stredwic 11867:             }
1.1136    raeburn  11868:             my @alluserslist=();
1.800     albertel 11869:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  11870:                 push(@alluserslist,$user.'&user');
1.253     stredwic 11871:             }
1.1318    droeschl 11872: 
                   11873:             if (!%listerror) {
                   11874:                 # no errors
                   11875:                 return (\@alluserslist);
                   11876:             } elsif (scalar(keys(%servers)) == 1) {
                   11877:                 # one library server, one error 
                   11878:                 my ($key) = keys(%listerror);
                   11879:                 return (\@alluserslist, $listerror{$key});
                   11880:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   11881:                 # con_lost indicates that we might miss data from at least one
                   11882:                 # library server
                   11883:                 return (\@alluserslist, 'con_lost');
                   11884:             } else {
                   11885:                 # multiple library servers and no con_lost -> data should be
                   11886:                 # complete. 
                   11887:                 return (\@alluserslist);
                   11888:             }
                   11889: 
1.253     stredwic 11890:         } else {
1.1136    raeburn  11891:             return ([],'missing username');
1.253     stredwic 11892:         }
1.955     raeburn  11893:     } elsif(!defined($getpropath)) {
1.1136    raeburn  11894:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   11895:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   11896:         return (\@all_domains);
1.955     raeburn  11897:     } else {
1.1136    raeburn  11898:         return ([],'missing domain');
1.275     stredwic 11899:     }
                   11900: }
                   11901: 
                   11902: # --------------------------------------------- GetFileTimestamp
                   11903: # This function utilizes dirlist and returns the date stamp for
                   11904: # when it was last modified.  It will also return an error of -1
                   11905: # if an error occurs
                   11906: 
                   11907: sub GetFileTimestamp {
1.955     raeburn  11908:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 11909:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   11910:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  11911:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   11912:                                     undef,$getuserdir);
                   11913:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11914:         return -1;
                   11915:     }
                   11916:     if (ref($fileref) eq 'ARRAY') {
                   11917:         my @stats = split('&',$fileref->[0]);
1.375     matthew  11918:         # @stats contains first the filename, then the stat output
                   11919:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 11920:     } else {
                   11921:         return -1;
1.253     stredwic 11922:     }
1.26      www      11923: }
                   11924: 
1.712     albertel 11925: sub stat_file {
                   11926:     my ($uri) = @_;
1.787     albertel 11927:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 11928: 
1.955     raeburn  11929:     my ($udom,$uname,$file);
1.712     albertel 11930:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   11931: 	($udom,$uname,$file) =
1.811     albertel 11932: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 11933: 	$file = 'userfiles/'.$file;
                   11934:     }
                   11935:     if ($uri =~ m-^/res/-) {
                   11936: 	($udom,$uname) = 
1.807     albertel 11937: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 11938: 	$file = $uri;
                   11939:     }
                   11940: 
                   11941:     if (!$udom || !$uname || !$file) {
                   11942: 	# unable to handle the uri
                   11943: 	return ();
                   11944:     }
1.956     raeburn  11945:     my $getpropath;
                   11946:     if ($file =~ /^userfiles\//) {
                   11947:         $getpropath = 1;
                   11948:     }
1.1136    raeburn  11949:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   11950:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   11951:         return ();
                   11952:     } else {
                   11953:         if (ref($listref) eq 'ARRAY') {
                   11954:             my @stats = split('&',$listref->[0]);
                   11955: 	    shift(@stats); #filename is first
                   11956: 	    return @stats;
                   11957:         }
1.712     albertel 11958:     }
                   11959:     return ();
                   11960: }
                   11961: 
1.1313    raeburn  11962: # --------------------------------------------------------- recursedirs
                   11963: # Recursive function to traverse either a specific user's Authoring Space
                   11964: # or corresponding Published Resource Space, and populate the hash ref:
                   11965: # $dirhashref with URLs of all directories, and if $filehashref hash
                   11966: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   11967: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   11968: # files in Authoring Space.
                   11969: #
                   11970: # Inputs:
                   11971: #
                   11972: # $is_home - true if current server is home server for user's space
                   11973: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   11974: # $docroot - Document root (i.e., /home/httpd/html
                   11975: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   11976: # $relpath - Current path (relative to top level).
                   11977: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   11978: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   11979: #
                   11980: # Returns: nothing
                   11981: #
                   11982: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   11983: #
                   11984: # Currently used by interface/londocs.pm to create linked select boxes for
                   11985: # directory and filename to import a Course "Author" resource into a course, and
                   11986: # also to create linked select boxes for Authoring Space and Directory to choose
                   11987: # save location for creation of a new "standard" problem from the Course Editor.
                   11988: #
                   11989: 
                   11990: sub recursedirs {
                   11991:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   11992:     return unless (ref($dirhashref) eq 'HASH');
                   11993:     my $currpath = $docroot.$toppath;
                   11994:     if ($relpath) {
                   11995:         $currpath .= "/$relpath";
                   11996:     }
                   11997:     my $savefile;
                   11998:     if (ref($filehashref)) {
                   11999:         $savefile = 1;
                   12000:     }
                   12001:     if ($is_home) {
                   12002:         if (opendir(my $dirh,$currpath)) {
                   12003:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   12004:                 next if ($item eq '');
                   12005:                 if (-d "$currpath/$item") {
                   12006:                     my $newpath;
                   12007:                     if ($relpath) {
                   12008:                         $newpath = "$relpath/$item";
                   12009:                     } else {
                   12010:                         $newpath = $item;
                   12011:                     }
                   12012:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   12013:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   12014:                 } elsif ($savefile) {
                   12015:                     if ($context eq 'priv') {
                   12016:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   12017:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   12018:                         }
                   12019:                     } else {
                   12020:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   12021:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   12022:                         }
                   12023:                     }
                   12024:                 }
                   12025:             }
                   12026:             closedir($dirh);
                   12027:         }
                   12028:     } else {
                   12029:         my ($dirlistref,$listerror) =
                   12030:             &dirlist($toppath.$relpath);
                   12031:         my @dir_lines;
                   12032:         my $dirptr=16384;
                   12033:         if (ref($dirlistref) eq 'ARRAY') {
                   12034:             foreach my $dir_line (sort
                   12035:                               {
                   12036:                                   my ($afile)=split('&',$a,2);
                   12037:                                   my ($bfile)=split('&',$b,2);
                   12038:                                   return (lc($afile) cmp lc($bfile));
                   12039:                               } (@{$dirlistref})) {
                   12040:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   12041:                     split(/\&/,$dir_line,16);
                   12042:                 $item =~ s/\s+$//;
                   12043:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   12044:                 if ($dirptr&$testdir) {
                   12045:                     my $newpath;
                   12046:                     if ($relpath) {
                   12047:                         $newpath = "$relpath/$item";
                   12048:                     } else {
                   12049:                         $relpath = '/';
                   12050:                         $newpath = $item;
                   12051:                     }
                   12052:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   12053:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   12054:                 } elsif ($savefile) {
                   12055:                     if ($context eq 'priv') {
                   12056:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   12057:                             $filehashref->{$relpath}{$item} = 1;
                   12058:                         }
                   12059:                     } else {
                   12060:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   12061:                             $filehashref->{$relpath}{$item} = 1;
                   12062:                         }
                   12063:                     }
                   12064:                 }
                   12065:             }
                   12066:         }
                   12067:     }
                   12068:     return;
                   12069: }
                   12070: 
1.26      www      12071: # -------------------------------------------------------- Value of a Condition
                   12072: 
1.713     albertel 12073: # gets the value of a specific preevaluated condition
                   12074: #    stored in the string  $env{user.state.<cid>}
                   12075: # or looks up a condition reference in the bighash and if if hasn't
                   12076: # already been evaluated recurses into docondval to get the value of
                   12077: # the condition, then memoizing it to 
                   12078: #   $env{user.state.<cid>.<condition>}
1.40      www      12079: sub directcondval {
                   12080:     my $number=shift;
1.620     albertel 12081:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 12082: 	&Apache::lonuserstate::evalstate();
                   12083:     }
1.713     albertel 12084:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   12085: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   12086:     } elsif ($number =~ /^_/) {
                   12087: 	my $sub_condition;
                   12088: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12089: 		&GDBM_READER(),0640)) {
                   12090: 	    $sub_condition=$bighash{'conditions'.$number};
                   12091: 	    untie(%bighash);
                   12092: 	}
                   12093: 	my $value = &docondval($sub_condition);
1.949     raeburn  12094: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 12095: 	return $value;
                   12096:     }
1.620     albertel 12097:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   12098:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      12099:     } else {
                   12100:        return 2;
                   12101:     }
                   12102: }
                   12103: 
1.713     albertel 12104: # get the collection of conditions for this resource
1.26      www      12105: sub condval {
                   12106:     my $condidx=shift;
1.54      www      12107:     my $allpathcond='';
1.713     albertel 12108:     foreach my $cond (split(/\|/,$condidx)) {
                   12109: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   12110: 	    $allpathcond.=
                   12111: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   12112: 	}
1.191     harris41 12113:     }
1.54      www      12114:     $allpathcond=~s/\|$//;
1.713     albertel 12115:     return &docondval($allpathcond);
                   12116: }
                   12117: 
                   12118: #evaluates an expression of conditions
                   12119: sub docondval {
                   12120:     my ($allpathcond) = @_;
                   12121:     my $result=0;
                   12122:     if ($env{'request.course.id'}
                   12123: 	&& defined($allpathcond)) {
                   12124: 	my $operand='|';
                   12125: 	my @stack;
                   12126: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   12127: 	    if ($chunk eq '(') {
                   12128: 		push @stack,($operand,$result);
                   12129: 	    } elsif ($chunk eq ')') {
                   12130: 		my $before=pop @stack;
                   12131: 		if (pop @stack eq '&') {
                   12132: 		    $result=$result>$before?$before:$result;
                   12133: 		} else {
                   12134: 		    $result=$result>$before?$result:$before;
                   12135: 		}
                   12136: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   12137: 		$operand=$chunk;
                   12138: 	    } else {
                   12139: 		my $new=directcondval($chunk);
                   12140: 		if ($operand eq '&') {
                   12141: 		    $result=$result>$new?$new:$result;
                   12142: 		} else {
                   12143: 		    $result=$result>$new?$result:$new;
                   12144: 		}
                   12145: 	    }
                   12146: 	}
1.26      www      12147:     }
                   12148:     return $result;
1.421     albertel 12149: }
                   12150: 
                   12151: # ---------------------------------------------------- Devalidate courseresdata
                   12152: 
                   12153: sub devalidatecourseresdata {
                   12154:     my ($coursenum,$coursedomain)=@_;
                   12155:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 12156:     &devalidate_cache_new('courseres',$hashid);
1.28      www      12157: }
                   12158: 
1.763     www      12159: 
1.200     www      12160: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     12161: #
                   12162: #  Parameters:
                   12163: #      $coursenum    - Number of the course.
                   12164: #      $coursedomain - Domain at which the course was created.
                   12165: #  Returns:
                   12166: #     A hash of the course parameters along (I think) with timestamps
                   12167: #     and version info.
1.877     foxr     12168: 
1.624     albertel 12169: sub get_courseresdata {
                   12170:     my ($coursenum,$coursedomain)=@_;
1.200     www      12171:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   12172:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 12173:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 12174:     my %dumpreply;
1.417     albertel 12175:     unless (defined($cached)) {
1.624     albertel 12176: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 12177: 	$result=\%dumpreply;
1.251     albertel 12178: 	my ($tmp) = keys(%dumpreply);
                   12179: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 12180: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 12181: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   12182: 	    return $tmp;
1.416     albertel 12183: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 12184: 	    $result=undef;
1.599     albertel 12185: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 12186: 	}
                   12187:     }
1.624     albertel 12188:     return $result;
                   12189: }
                   12190: 
1.633     albertel 12191: sub devalidateuserresdata {
                   12192:     my ($uname,$udom)=@_;
                   12193:     my $hashid="$udom:$uname";
                   12194:     &devalidate_cache_new('userres',$hashid);
                   12195: }
                   12196: 
1.624     albertel 12197: sub get_userresdata {
                   12198:     my ($uname,$udom)=@_;
                   12199:     #most student don\'t have any data set, check if there is some data
                   12200:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   12201: 
                   12202:     my $hashid="$udom:$uname";
                   12203:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   12204:     if (!defined($cached)) {
                   12205: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   12206: 	$result=\%resourcedata;
                   12207: 	&do_cache_new('userres',$hashid,$result,600);
                   12208:     }
                   12209:     my ($tmp)=keys(%$result);
                   12210:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   12211: 	return $result;
                   12212:     }
                   12213:     #error 2 occurs when the .db doesn't exist
                   12214:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  12215:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   12216: 	    &logthis("<font color=\"blue\">WARNING:".
                   12217: 		     " Trying to get resource data for ".
                   12218: 		     $uname." at ".$udom.": ".
                   12219: 		     $tmp."</font>");
                   12220:         }
1.624     albertel 12221:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 12222: 	#&EXT_cache_set($udom,$uname);
                   12223: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 12224: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 12225:     }
                   12226:     return $tmp;
                   12227: }
1.879     foxr     12228: #----------------------------------------------- resdata - return resource data
                   12229: #  Purpose:
                   12230: #    Return resource data for either users or for a course.
                   12231: #  Parameters:
                   12232: #     $name      - Course/user name.
                   12233: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  12234: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  12235: #     $mapp      - decluttered URL of enclosing map  
                   12236: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   12237: #     $recurseup - Ref to array of map URLs, starting with map containing
                   12238: #                  $mapp up through hierarchy of nested maps to top level map.  
                   12239: #     $courseid  - CourseID (first part of param identifier).
                   12240: #     $modifier  - Middle part of param identifier.
                   12241: #     $what      - Last part of param identifier.
1.879     foxr     12242: #     @which     - Array of names of resources desired.
                   12243: #  Returns:
                   12244: #     The value of the first reasource in @which that is found in the
                   12245: #     resource hash.
                   12246: #  Exceptional Conditions:
                   12247: #     If the $type passed in is not valid (not the string 'course' or 
                   12248: #     'user', an undefined  reference is returned.
                   12249: #     If none of the resources are found, an undef is returned
1.624     albertel 12250: sub resdata {
1.1301    raeburn  12251:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   12252:         $modifier,$what,@which)=@_;
1.624     albertel 12253:     my $result;
                   12254:     if ($type eq 'course') {
                   12255: 	$result=&get_courseresdata($name,$domain);
                   12256:     } elsif ($type eq 'user') {
                   12257: 	$result=&get_userresdata($name,$domain);
                   12258:     }
                   12259:     if (!ref($result)) { return $result; }    
1.251     albertel 12260:     foreach my $item (@which) {
1.1301    raeburn  12261:         if ($item->[1] eq 'course') {
                   12262:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   12263:                 unless ($$recursed) {
1.1302    raeburn  12264:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  12265:                     $$recursed = 1;
                   12266:                 }
                   12267:                 foreach my $item (@${recurseup}) {
                   12268:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   12269:                     last if (defined($result->{$norecursechk}));
                   12270:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   12271:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   12272:                 }
                   12273:             }
                   12274:         }
                   12275:         if (defined($result->{$item->[0]})) {
1.927     albertel 12276: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 12277: 	}
1.250     albertel 12278:     }
1.291     albertel 12279:     return undef;
1.200     www      12280: }
                   12281: 
1.1360    raeburn  12282: sub get_domain_lti {
                   12283:     my ($cdom,$context) = @_;
                   12284:     my ($name,%lti);
                   12285:     if ($context eq 'consumer') {
                   12286:         $name = 'ltitools';
                   12287:     } elsif ($context eq 'provider') {
                   12288:         $name = 'lti';
                   12289:     } else {
                   12290:         return %lti;
                   12291:     }
                   12292:     my ($result,$cached)=&is_cached_new($name,$cdom);
1.1298    raeburn  12293:     if (defined($cached)) {
                   12294:         if (ref($result) eq 'HASH') {
1.1360    raeburn  12295:             %lti = %{$result};
1.1298    raeburn  12296:         }
                   12297:     } else {
1.1360    raeburn  12298:         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   12299:         if (ref($domconfig{$name}) eq 'HASH') {
                   12300:             %lti = %{$domconfig{$name}};
1.1462    raeburn  12301:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom,undef,1);
1.1360    raeburn  12302:             if (ref($encdomconfig{$name}) eq 'HASH') {
                   12303:                 foreach my $id (keys(%lti)) {
                   12304:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
1.1344    raeburn  12305:                         foreach my $item ('key','secret') {
1.1360    raeburn  12306:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
1.1344    raeburn  12307:                         }
                   12308:                     }
                   12309:                 }
                   12310:             }
1.1298    raeburn  12311:         }
                   12312:         my $cachetime = 24*60*60;
1.1360    raeburn  12313:         &do_cache_new($name,$cdom,\%lti,$cachetime);
1.1298    raeburn  12314:     }
1.1360    raeburn  12315:     return %lti;
1.1298    raeburn  12316: }
                   12317: 
1.1463    raeburn  12318: sub get_course_lti {
                   12319:     my ($cnum,$cdom) = @_;
                   12320:     my $hashid=$cdom.'_'.$cnum;
                   12321:     my %courselti;
                   12322:     my ($result,$cached)=&is_cached_new('courselti',$hashid);
                   12323:     if (defined($cached)) {
                   12324:         if (ref($result) eq 'HASH') {
                   12325:             %courselti = %{$result};
                   12326:         }
                   12327:     } else {
                   12328:         %courselti = &dump('lti',$cdom,$cnum,undef,undef,undef,1);
                   12329:         my $cachetime = 24*60*60;
                   12330:         &do_cache_new('courselti',$hashid,\%courselti,$cachetime);
                   12331:     }
                   12332:     return %courselti;
                   12333: }
                   12334: 
1.1479    raeburn  12335: sub courselti_itemid {
                   12336:     my ($cnum,$cdom,$url,$method,$params,$context) = @_;
                   12337:     my ($chome,$itemid);
                   12338:     $chome = &homeserver($cnum,$cdom);
                   12339:     return if ($chome eq 'no_host');
                   12340:     if (ref($params) eq 'HASH') {
                   12341:         my $items = &freeze_escape($params);
                   12342:         my $rep;
                   12343:         if (grep { $_ eq $chome } current_machine_ids()) {
                   12344:             $rep = LONCAPA::Lond::crslti_itemid($cdom,$cnum,$url,$method,$params,$perlvar{'lonVersion'});
                   12345:         } else {
                   12346:             my $escurl = &escape($url);
                   12347:             my $escmethod = &escape($method);
                   12348:             my $items = &freeze_escape($params);
                   12349:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$chome);
                   12350:         }
                   12351:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   12352:                 ($rep eq 'unknown_cmd')) {
                   12353:             $itemid = $rep;
                   12354:         }
                   12355:     }
                   12356:     return $itemid;
                   12357: }
                   12358: 
                   12359: sub domainlti_itemid {
                   12360:     my ($cdom,$url,$method,$params,$context) = @_;
                   12361:     my ($primary_id,$itemid);
                   12362:     $primary_id = &domain($cdom,'primary');
                   12363:     return if ($primary_id eq '');
                   12364:     if (ref($params) eq 'HASH') {
                   12365:         my $items = &freeze_escape($params);
                   12366:         my $rep;
                   12367:         if (grep { $_ eq $primary_id } current_machine_ids()) {
                   12368:             $rep = LONCAPA::Lond::domlti_itemid($cdom,$context,$url,$method,$params,$perlvar{'lonVersion'});
                   12369:         } else {
                   12370:             my $cnum = '';
                   12371:             my $escurl = &escape($url);
                   12372:             my $escmethod = &escape($method);
                   12373:             my $items = &freeze_escape($params);
                   12374:             $rep = &reply("encrypt:lti:$cdom:$cnum:$context:$escurl:$escmethod:$items",$primary_id);
                   12375:         }
                   12376:         unless (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                   12377:                 ($rep eq 'unknown_cmd')) {
                   12378:             $itemid = $rep;
                   12379:         }
                   12380:     }
                   12381:     return $itemid;
                   12382: }
                   12383: 
1.1236    raeburn  12384: sub get_numsuppfiles {
                   12385:     my ($cnum,$cdom,$ignorecache)=@_;
                   12386:     my $hashid=$cnum.':'.$cdom;
                   12387:     my ($suppcount,$cached);
                   12388:     unless ($ignorecache) {
                   12389:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   12390:     }
                   12391:     unless (defined($cached)) {
                   12392:         my $chome=&homeserver($cnum,$cdom);
                   12393:         unless ($chome eq 'no_host') {
1.1366    raeburn  12394:             ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236    raeburn  12395:             my $suppmap = 'supplemental.sequence';
1.1366    raeburn  12396:             ($suppcount,$supptools,$errors) =
                   12397:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
                   12398:                                                          $supptools,$errors);
1.1236    raeburn  12399:         }
                   12400:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   12401:     }
                   12402:     return $suppcount;
                   12403: }
                   12404: 
1.379     matthew  12405: #
                   12406: # EXT resource caching routines
                   12407: #
                   12408: 
1.1302    raeburn  12409: {
                   12410: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   12411: #
                   12412: # The course for which we cache
                   12413: my $cachedmapkey='';
                   12414: # The cached recursive maps for this course
                   12415: my %cachedmaps=();
                   12416: # When this was last done
                   12417: my $cachedmaptime='';
                   12418: 
1.379     matthew  12419: sub clear_EXT_cache_status {
1.383     albertel 12420:     &delenv('cache.EXT.');
1.379     matthew  12421: }
                   12422: 
                   12423: sub EXT_cache_status {
                   12424:     my ($target_domain,$target_user) = @_;
1.383     albertel 12425:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 12426:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  12427:         # We know already the user has no data
                   12428:         return 1;
                   12429:     } else {
                   12430:         return 0;
                   12431:     }
                   12432: }
                   12433: 
                   12434: sub EXT_cache_set {
                   12435:     my ($target_domain,$target_user) = @_;
1.383     albertel 12436:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  12437:     #&appenv({$cachename => time});
1.379     matthew  12438: }
                   12439: 
1.28      www      12440: # --------------------------------------------------------- Value of a Variable
1.58      www      12441: sub EXT {
1.715     albertel 12442: 
1.1461    raeburn  12443:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid,$recurseupref)=@_;
1.68      www      12444:     unless ($varname) { return ''; }
1.218     albertel 12445:     #get real user name/domain, courseid and symb
                   12446:     my $courseid;
1.359     albertel 12447:     my $publicuser;
1.427     www      12448:     if ($symbparm) {
                   12449: 	$symbparm=&get_symb_from_alias($symbparm);
                   12450:     }
1.218     albertel 12451:     if (!($uname && $udom)) {
1.790     albertel 12452:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 12453:       if (!$symbparm) {	$symbparm=$cursymb; }
                   12454:     } else {
1.620     albertel 12455: 	$courseid=$env{'request.course.id'};
1.218     albertel 12456:     }
1.48      www      12457:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   12458:     my $rest;
1.320     albertel 12459:     if (defined($therest[0])) {
1.48      www      12460:        $rest=join('.',@therest);
                   12461:     } else {
                   12462:        $rest='';
                   12463:     }
1.320     albertel 12464: 
1.57      www      12465:     my $qualifierrest=$qualifier;
                   12466:     if ($rest) { $qualifierrest.='.'.$rest; }
                   12467:     my $spacequalifierrest=$space;
                   12468:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      12469:     if ($realm eq 'user') {
1.48      www      12470: # --------------------------------------------------------------- user.resource
                   12471: 	if ($space eq 'resource') {
1.651     albertel 12472: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   12473: 		  || defined($Apache::lonhomework::parsing_a_task))
                   12474: 		 &&
1.1469    raeburn  12475: 		 ($symbparm eq &symbread()) ) {
1.744     albertel 12476: 		# if we are in the middle of processing the resource the
                   12477: 		# get the value we are planning on committing
                   12478:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   12479:                     return $Apache::lonhomework::results{$qualifierrest};
                   12480:                 } else {
                   12481:                     return $Apache::lonhomework::history{$qualifierrest};
                   12482:                 }
1.335     albertel 12483: 	    } else {
1.359     albertel 12484: 		my %restored;
1.620     albertel 12485: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 12486: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   12487: 		} else {
                   12488: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   12489: 		}
1.335     albertel 12490: 		return $restored{$qualifierrest};
                   12491: 	    }
1.48      www      12492: # ----------------------------------------------------------------- user.access
                   12493:         } elsif ($space eq 'access') {
1.218     albertel 12494: 	    # FIXME - not supporting calls for a specific user
1.48      www      12495:             return &allowed($qualifier,$rest);
                   12496: # ------------------------------------------ user.preferences, user.environment
                   12497:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 12498: 	    if (($uname eq $env{'user.name'}) &&
                   12499: 		($udom eq $env{'user.domain'})) {
                   12500: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 12501: 	    } else {
1.359     albertel 12502: 		my %returnhash;
                   12503: 		if (!$publicuser) {
                   12504: 		    %returnhash=&userenvironment($udom,$uname,
                   12505: 						 $qualifierrest);
                   12506: 		}
1.218     albertel 12507: 		return $returnhash{$qualifierrest};
                   12508: 	    }
1.48      www      12509: # ----------------------------------------------------------------- user.course
                   12510:         } elsif ($space eq 'course') {
1.218     albertel 12511: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12512:             return $env{join('.',('request.course',$qualifier))};
1.48      www      12513: # ------------------------------------------------------------------- user.role
                   12514:         } elsif ($space eq 'role') {
1.218     albertel 12515: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 12516:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      12517:             if ($qualifier eq 'value') {
                   12518: 		return $role;
                   12519:             } elsif ($qualifier eq 'extent') {
                   12520:                 return $where;
                   12521:             }
                   12522: # ----------------------------------------------------------------- user.domain
                   12523:         } elsif ($space eq 'domain') {
1.218     albertel 12524:             return $udom;
1.48      www      12525: # ------------------------------------------------------------------- user.name
                   12526:         } elsif ($space eq 'name') {
1.218     albertel 12527:             return $uname;
1.48      www      12528: # ---------------------------------------------------- Any other user namespace
1.29      www      12529:         } else {
1.359     albertel 12530: 	    my %reply;
                   12531: 	    if (!$publicuser) {
                   12532: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   12533: 	    }
                   12534: 	    return $reply{$qualifierrest};
1.48      www      12535:         }
1.236     www      12536:     } elsif ($realm eq 'query') {
                   12537: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 12538:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   12539: 						[$spacequalifierrest]);
1.620     albertel 12540: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      12541:    } elsif ($realm eq 'request') {
1.48      www      12542: # ------------------------------------------------------------- request.browser
                   12543:         if ($space eq 'browser') {
1.1145    bisitz   12544:             return $env{'browser.'.$qualifier};
1.57      www      12545: # ------------------------------------------------------------ request.filename
                   12546:         } else {
1.620     albertel 12547:             return $env{'request.'.$spacequalifierrest};
1.29      www      12548:         }
1.28      www      12549:     } elsif ($realm eq 'course') {
1.48      www      12550: # ---------------------------------------------------------- course.description
1.620     albertel 12551:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      12552:     } elsif ($realm eq 'resource') {
1.165     www      12553: 
1.620     albertel 12554: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 12555: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   12556: 	}
1.693     albertel 12557: 
1.1232    raeburn  12558:         if ($qualifier eq '') {
                   12559: 	    if ($space eq 'title') {
                   12560: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   12561: 	        return &gettitle($symbparm);
                   12562: 	    }
1.693     albertel 12563: 	
1.1232    raeburn  12564: 	    if ($space eq 'map') {
                   12565: 	        my ($map) = &decode_symb($symbparm);
                   12566: 	        return &symbread($map);
                   12567: 	    }
                   12568:             if ($space eq 'maptitle') {
                   12569:                 my ($map) = &decode_symb($symbparm);
                   12570:                 return &gettitle($map);
                   12571:             }
                   12572: 	    if ($space eq 'filename') {
                   12573: 	        if ($symbparm) {
                   12574: 		    return &clutter((&decode_symb($symbparm))[2]);
                   12575: 	        }
                   12576: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 12577: 	    }
1.1232    raeburn  12578: 
1.1233    raeburn  12579:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   12580:                 if ($space eq 'visibleparts') {
                   12581:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   12582:                     my $item;
                   12583:                     if (ref($navmap)) {
                   12584:                         my $res = $navmap->getBySymb($symbparm);
                   12585:                         my $parts = $res->parts();
                   12586:                         if (ref($parts) eq 'ARRAY') {
                   12587:                             $item = join(',',@{$parts});
                   12588:                         }
                   12589:                         undef($navmap);
1.1232    raeburn  12590:                     }
1.1233    raeburn  12591:                     return $item;
1.1232    raeburn  12592:                 }
                   12593:             }
                   12594:         }
1.693     albertel 12595: 
1.1301    raeburn  12596: 	my ($section, $group, @groups, @recurseup, $recursed);
1.1461    raeburn  12597:         if (ref($recurseupref) eq 'ARRAY') {
                   12598:             @recurseup = @{$recurseupref};
                   12599:             $recursed = 1;
                   12600:         }
1.1301    raeburn  12601: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  12602:         if (($courseid eq '') && ($cid)) {
                   12603:             $courseid = $cid;
                   12604:         }
                   12605: 	if (($symbparm && $courseid) && 
                   12606: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      12607: 
1.218     albertel 12608: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      12609: 
1.60      www      12610: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 12611: 	    my $symbp=$symbparm;
1.1301    raeburn  12612: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 12613: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  12614:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 12615: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 12616: 	    if (($env{'user.name'} eq $uname) &&
                   12617: 		($env{'user.domain'} eq $udom)) {
                   12618: 		$section=$env{'request.course.sec'};
1.733     raeburn  12619:                 @groups = split(/:/,$env{'request.course.groups'});  
                   12620:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 12621: 	    } else {
1.539     albertel 12622: 		if (! defined($usection)) {
1.551     albertel 12623: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 12624: 		} else {
                   12625: 		    $section = $usection;
                   12626: 		}
1.733     raeburn  12627:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 12628: 	    }
                   12629: 
                   12630: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   12631: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  12632:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 12633: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   12634: 
1.593     albertel 12635: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 12636: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  12637:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 12638: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      12639: 
1.60      www      12640: # ----------------------------------------------------------- first, check user
1.624     albertel 12641: 
1.1301    raeburn  12642: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   12643:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 12644: 				       ([$courselevelr,'resource'],
                   12645: 					[$courselevelm,'map'     ],
1.1301    raeburn  12646:                                         [$courseleveli,'map'     ],
1.927     albertel 12647: 					[$courselevel, 'course'  ]));
1.931     albertel 12648: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      12649: 
1.594     albertel 12650: # ------------------------------------------------ second, check some of course
1.684     raeburn  12651:             my $coursereply;
1.691     raeburn  12652:             if (@groups > 0) {
                   12653:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  12654:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   12655:                                        $mapp,\$recursed,\@recurseup);
                   12656:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  12657:             }
1.96      www      12658: 
1.684     raeburn  12659: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 12660: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  12661: 				  'course',$mapp,\$recursed,\@recurseup,
                   12662:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 12663: 				  ([$seclevelr,   'resource'],
                   12664: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  12665:                                    [$secleveli,   'map'     ],
1.927     albertel 12666: 				   [$seclevel,    'course'  ],
                   12667: 				   [$courselevelr,'resource']));
                   12668: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      12669: 
1.60      www      12670: # ------------------------------------------------------ third, check map parms
1.218     albertel 12671: 	    my %parmhash=();
                   12672: 	    my $thisparm='';
                   12673: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 12674: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 12675: 		    &GDBM_READER(),0640)) {
1.218     albertel 12676: 		$thisparm=$parmhash{$symbparm};
                   12677: 		untie(%parmhash);
                   12678: 	    }
1.927     albertel 12679: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 12680: 	}
1.594     albertel 12681: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  12682:  
                   12683:         my $what = $spacequalifierrest;
                   12684: 	$what=~s/\./\_/;
1.282     albertel 12685: 	my $filename;
                   12686: 	if (!$symbparm) { $symbparm=&symbread(); }
                   12687: 	if ($symbparm) {
1.409     www      12688: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 12689: 	} else {
1.620     albertel 12690: 	    $filename=$env{'request.filename'};
1.282     albertel 12691: 	}
1.1362    raeburn  12692:         my $toolsymb;
                   12693:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   12694:             $toolsymb = $symbparm;
                   12695:         }
                   12696: 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 12697: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362    raeburn  12698: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 12699: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      12700: 
1.1301    raeburn  12701: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 12702: 	if ($symbparm && defined($courseid) && 
1.620     albertel 12703: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 12704: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   12705: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  12706: 				     'course',$mapp,\$recursed,\@recurseup,
                   12707:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 12708: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  12709:                                       [$courseleveli,'map'   ],
1.927     albertel 12710: 				      [$courselevel, 'course']));
                   12711: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 12712: 	}
1.145     www      12713: # ------------------------------------------------------------------ Cascade up
1.218     albertel 12714: 	unless ($space eq '0') {
1.336     albertel 12715: 	    my @parts=split(/_/,$space);
                   12716: 	    my $id=pop(@parts);
                   12717: 	    my $part=join('_',@parts);
                   12718: 	    if ($part eq '') { $part='0'; }
1.927     albertel 12719: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 12720: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  12721: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 12722: 	}
1.395     albertel 12723: 	if ($recurse) { return undef; }
1.1362    raeburn  12724: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 12725: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      12726: # ---------------------------------------------------- Any other user namespace
                   12727:     } elsif ($realm eq 'environment') {
                   12728: # ----------------------------------------------------------------- environment
1.620     albertel 12729: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   12730: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 12731: 	} else {
1.770     albertel 12732: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   12733: 		return '';
                   12734: 	    }
1.219     albertel 12735: 	    my %returnhash=&userenvironment($udom,$uname,
                   12736: 					    $spacequalifierrest);
                   12737: 	    return $returnhash{$spacequalifierrest};
                   12738: 	}
1.28      www      12739:     } elsif ($realm eq 'system') {
1.48      www      12740: # ----------------------------------------------------------------- system.time
                   12741: 	if ($space eq 'time') {
                   12742: 	    return time;
                   12743:         }
1.696     albertel 12744:     } elsif ($realm eq 'server') {
                   12745: # ----------------------------------------------------------------- system.time
                   12746: 	if ($space eq 'name') {
                   12747: 	    return $ENV{'SERVER_NAME'};
                   12748:         }
1.1415    raeburn  12749:     } elsif ($realm eq 'client') {
                   12750:         if ($space eq 'remote_addr') {
1.1441    raeburn  12751:             return &get_requestor_ip();
1.1415    raeburn  12752:         }
1.28      www      12753:     }
1.48      www      12754:     return '';
1.61      www      12755: }
                   12756: 
1.927     albertel 12757: sub get_reply {
                   12758:     my ($reply_value) = @_;
1.940     raeburn  12759:     if (ref($reply_value) eq 'ARRAY') {
                   12760:         if (wantarray) {
                   12761: 	    return @$reply_value;
                   12762:         }
                   12763:         return $reply_value->[0];
                   12764:     } else {
                   12765:         return $reply_value;
1.927     albertel 12766:     }
                   12767: }
                   12768: 
1.691     raeburn  12769: sub check_group_parms {
1.1301    raeburn  12770:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   12771:         $recursed,$recurseupref) = @_;
                   12772:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   12773:                   [$what,'course']);
                   12774:     my $coursereply;
1.691     raeburn  12775:     foreach my $group (@{$groups}) {
1.1301    raeburn  12776:         my @groupitems = ();
1.691     raeburn  12777:         foreach my $level (@levels) {
1.927     albertel 12778:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   12779:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  12780:         }
1.1301    raeburn  12781:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   12782:                                    $env{'course.'.$courseid.'.domain'},
                   12783:                                    'course',$mapp,$recursed,$recurseupref,
                   12784:                                    $courseid,'.['.$group.'].',$what,
                   12785:                                    @groupitems);
                   12786:         last if (defined($coursereply));
1.691     raeburn  12787:     }
                   12788:     return $coursereply;
                   12789: }
                   12790: 
1.1301    raeburn  12791: sub get_map_hierarchy {
1.1302    raeburn  12792:     my ($mapname,$courseid) = @_;
                   12793:     my @recurseup = ();
1.1301    raeburn  12794:     if ($mapname) {
1.1302    raeburn  12795:         if (($cachedmapkey eq $courseid) &&
                   12796:             (abs($cachedmaptime-time)<5)) {
                   12797:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   12798:                 return @{$cachedmaps{$mapname}};
                   12799:             }
                   12800:         }
1.1301    raeburn  12801:         my $navmap = Apache::lonnavmaps::navmap->new();
                   12802:         if (ref($navmap)) {
                   12803:             @recurseup = $navmap->recurseup_maps($mapname);
                   12804:             undef($navmap);
1.1302    raeburn  12805:             $cachedmaps{$mapname} = \@recurseup;
                   12806:             $cachedmaptime=time;
                   12807:             $cachedmapkey=$courseid;
1.1301    raeburn  12808:         }
                   12809:     }
                   12810:     return @recurseup;
                   12811: }
                   12812: 
1.1302    raeburn  12813: }
                   12814: 
1.691     raeburn  12815: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  12816:     my ($courseid,@groups) = @_;
                   12817:     @groups = sort(@groups);
1.691     raeburn  12818:     return @groups;
                   12819: }
                   12820: 
1.395     albertel 12821: sub packages_tab_default {
1.1362    raeburn  12822:     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 12823:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 12824: 
                   12825:     my (@extension,@specifics,$do_default);
1.1362    raeburn  12826:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 12827: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 12828: 	if ($pack_type eq 'default') {
                   12829: 	    $do_default=1;
                   12830: 	} elsif ($pack_type eq 'extension') {
                   12831: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 12832: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 12833: 	    # only look at packages defaults for packages that this id is
1.738     albertel 12834: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   12835: 	}
                   12836:     }
                   12837:     # first look for a package that matches the requested part id
                   12838:     foreach my $package (@specifics) {
                   12839: 	my (undef,$pack_type,$pack_part)=@{$package};
                   12840: 	next if ($pack_part ne $part);
                   12841: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12842: 	    return $packagetab{"$pack_type&$name&default"};
                   12843: 	}
                   12844:     }
                   12845:     # look for any possible matching non extension_ package
                   12846:     foreach my $package (@specifics) {
                   12847: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 12848: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12849: 	    return $packagetab{"$pack_type&$name&default"};
                   12850: 	}
1.585     albertel 12851: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 12852: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   12853: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 12854: 	}
                   12855:     }
1.738     albertel 12856:     # look for any posible extension_ match
                   12857:     foreach my $package (@extension) {
                   12858: 	my ($package,$pack_type)=@{$package};
                   12859: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   12860: 	    return $packagetab{"$pack_type&$name&default"};
                   12861: 	}
                   12862: 	if (defined($packagetab{$package."&$name&default"})) {
                   12863: 	    return $packagetab{$package."&$name&default"};
                   12864: 	}
                   12865:     }
                   12866:     # look for a global default setting
                   12867:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   12868: 	return $packagetab{"default&$name&default"};
                   12869:     }
1.395     albertel 12870:     return undef;
                   12871: }
                   12872: 
1.334     albertel 12873: sub add_prefix_and_part {
                   12874:     my ($prefix,$part)=@_;
                   12875:     my $keyroot;
                   12876:     if (defined($prefix) && $prefix !~ /^__/) {
                   12877: 	# prefix that has a part already
                   12878: 	$keyroot=$prefix;
                   12879:     } elsif (defined($prefix)) {
                   12880: 	# prefix that is missing a part
                   12881: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   12882:     } else {
                   12883: 	# no prefix at all
                   12884: 	if (defined($part)) { $keyroot='_'.$part; }
                   12885:     }
                   12886:     return $keyroot;
                   12887: }
                   12888: 
1.71      www      12889: # ---------------------------------------------------------------- Get metadata
                   12890: 
1.599     albertel 12891: my %metaentry;
1.1070    www      12892: my %importedpartids;
1.1369    raeburn  12893: my %importedrespids;
1.71      www      12894: sub metadata {
1.1362    raeburn  12895:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      12896:     $uri=&declutter($uri);
1.288     albertel 12897:     # if it is a non metadata possible uri return quickly
1.529     albertel 12898:     if (($uri eq '') || 
                   12899: 	(($uri =~ m|^/*adm/|) && 
1.1343    raeburn  12900: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  12901:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 12902: 	return undef;
                   12903:     }
1.1261    raeburn  12904:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 12905: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 12906: 	return undef;
1.288     albertel 12907:     }
1.73      www      12908:     my $filename=$uri;
                   12909:     $uri=~s/\.meta$//;
1.172     www      12910: #
                   12911: # Is the metadata already cached?
1.177     www      12912: # Look at timestamp of caching
1.172     www      12913: # Everything is cached by the main uri, libraries are never directly cached
                   12914: #
1.428     albertel 12915:     if (!defined($liburi)) {
1.599     albertel 12916: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 12917: 	if (defined($cached)) { return $result->{':'.$what}; }
                   12918:     }
1.1362    raeburn  12919: 
                   12920: #
                   12921: # If the uri is for an external tool the file from
                   12922: # which metadata should be retrieved depends on whether
                   12923: # the tool had been configured to be gradable (set in the Course
                   12924: # Editor or Resource Editor).
                   12925: #
                   12926: # If a valid symb has been included as the third arg in the call
                   12927: # to &metadata() that can be used to retrieve the value of
                   12928: # parameter_0_gradable set for the resource, and included in the
                   12929: # uploaded map containing the tool. The value is retrieved via
                   12930: # &EXT(), if a valid symb is available.  Otherwise the value of
                   12931: # gradable in the exttool_$marker.db file for the tool instance
1.1364    raeburn  12932: # is retrieved via &get().
                   12933: #
                   12934: # When lonuserstate::traceroute() calls lonnet::EXT() for 
                   12935: # hiddenresource and encrypturl (during course initialization)
                   12936: # the map-level parameter for resource.0.gradable included in the 
                   12937: # uploaded map containing the tool will not yet have been stored
                   12938: # in the user_course_parms.db file for the user's session, so in 
                   12939: # this case fall back to retrieving gradable status from the
                   12940: # exttool_$marker.db file.
1.1362    raeburn  12941: #
                   12942: # In order to avoid an infinite loop, &metadata() will return
                   12943: # before a call to &EXT(), if the uri is for an external tool
                   12944: # and the $what for which metadata is being requested is
                   12945: # parameter_0_gradable or 0_gradable.
                   12946: #
                   12947: 
                   12948:     if ($uri =~ /ext\.tool$/) {
                   12949:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   12950:             return;
                   12951:         } else {
                   12952:             my ($checked,$use_passback);
                   12953:             if ($toolsymb ne '') {
                   12954:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364    raeburn  12955:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362    raeburn  12956:                     $checked = 1;
                   12957:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   12958:                         $use_passback = 1;
                   12959:                     }
                   12960:                 }
                   12961:             }
                   12962:             unless ($checked) {
                   12963:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   12964:                 $marker=~s/\D//g;
1.1363    raeburn  12965:                 if ($marker) {
1.1362    raeburn  12966:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   12967:                     $use_passback = $toolsettings{'gradable'};
                   12968:                 }
                   12969:             }
                   12970:             if ($use_passback) {
                   12971:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   12972:             } else {
                   12973:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   12974:             }
                   12975:         }
                   12976:     }
                   12977: 
1.428     albertel 12978:     {
1.1069    www      12979: # Imported parts would go here
1.1369    raeburn  12980:         my @origfiletagids=();
1.1069    www      12981:         my $importedparts=0;
1.1369    raeburn  12982: 
                   12983: # Imported responseids would go here
                   12984:         my $importedresponses=0;
1.172     www      12985: #
                   12986: # Is this a recursive call for a library?
                   12987: #
1.599     albertel 12988: #	if (! exists($metacache{$uri})) {
                   12989: #	    $metacache{$uri}={};
                   12990: #	}
1.924     albertel 12991: 	my $cachetime = 60*60;
1.171     www      12992:         if ($liburi) {
                   12993: 	    $liburi=&declutter($liburi);
                   12994:             $filename=$liburi;
1.401     bowersj2 12995:         } else {
1.599     albertel 12996: 	    &devalidate_cache_new('meta',$uri);
                   12997: 	    undef(%metaentry);
1.401     bowersj2 12998: 	}
1.140     www      12999:         my %metathesekeys=();
1.73      www      13000:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 13001: 	my $metastring;
1.1140    www      13002: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 13003: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 13004: 	    $metastring = 
1.929     albertel 13005: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 13006: 					  ('grade_target' => 'meta'));
                   13007: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  13008: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   13009:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 13010: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 13011: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 13012: 	    $metastring=&getfile($file);
1.489     albertel 13013: 	}
1.208     albertel 13014:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      13015:         my $token;
1.140     www      13016:         undef %metathesekeys;
1.71      www      13017:         while ($token=$parser->get_token) {
1.339     albertel 13018: 	    if ($token->[0] eq 'S') {
                   13019: 		if (defined($token->[2]->{'package'})) {
1.172     www      13020: #
                   13021: # This is a package - get package info
                   13022: #
1.339     albertel 13023: 		    my $package=$token->[2]->{'package'};
                   13024: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   13025: 		    if (defined($token->[2]->{'id'})) { 
                   13026: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   13027: 		    }
1.599     albertel 13028: 		    if ($metaentry{':packages'}) {
                   13029: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 13030: 		    } else {
1.599     albertel 13031: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 13032: 		    }
1.736     albertel 13033: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 13034: 			my $part=$keyroot;
                   13035: 			$part=~s/^\_//;
1.736     albertel 13036: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   13037: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   13038: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 13039: 			    # ignore package.tab specified default values
                   13040:                             # here &package_tab_default() will fetch those
                   13041: 			    if ($subp eq 'default') { next; }
1.736     albertel 13042: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 13043: 			    my $unikey;
                   13044: 			    if ($pack =~ /_0$/) {
                   13045: 				$unikey='parameter_0_'.$name;
                   13046: 				$part=0;
                   13047: 			    } else {
                   13048: 				$unikey='parameter'.$keyroot.'_'.$name;
                   13049: 			    }
1.339     albertel 13050: 			    if ($subp eq 'display') {
                   13051: 				$value.=' [Part: '.$part.']';
                   13052: 			    }
1.599     albertel 13053: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 13054: 			    $metathesekeys{$unikey}=1;
1.599     albertel 13055: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   13056: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 13057: 			    }
1.599     albertel 13058: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   13059: 				$metaentry{':'.$unikey}=
                   13060: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 13061: 			    }
1.339     albertel 13062: 			}
                   13063: 		    }
                   13064: 		} else {
1.172     www      13065: #
                   13066: # This is not a package - some other kind of start tag
1.339     albertel 13067: #
                   13068: 		    my $entry=$token->[1];
1.1068    www      13069: 		    my $unikey='';
1.175     www      13070: 
1.339     albertel 13071: 		    if ($entry eq 'import') {
1.175     www      13072: #
                   13073: # Importing a library here
1.339     albertel 13074: #
1.1067    www      13075:                         my $location=$parser->get_text('/import');
                   13076:                         my $dir=$filename;
                   13077:                         $dir=~s|[^/]*$||;
                   13078:                         $location=&filelocation($dir,$location);
1.1369    raeburn  13079: 
                   13080:                         my $importid=$token->[2]->{'id'};
1.1068    www      13081:                         my $importmode=$token->[2]->{'importmode'};
1.1369    raeburn  13082: #
                   13083: # Check metadata for imported file to
                   13084: # see if it contained response items
                   13085: #
1.1372    raeburn  13086:                         my ($origfile,@libfilekeys);
1.1370    raeburn  13087:                         my %currmetaentry = %metaentry;
1.1372    raeburn  13088:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
                   13089:                                                            $depthcount+1));
                   13090:                         if (grep(/^responseorder$/,@libfilekeys)) {
                   13091:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
                   13092:                                                              undef,$depthcount+1);
                   13093:                             if ($libresponseorder ne '') {
                   13094:                                 if ($#origfiletagids<0) {
                   13095:                                     undef(%importedrespids);
                   13096:                                     undef(%importedpartids);
                   13097:                                 }
1.1373    raeburn  13098:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
                   13099:                                 if (@respids) {
                   13100:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
                   13101:                                 }
                   13102:                                 if ($importedrespids{$importid} ne '') {
1.1372    raeburn  13103:                                     $importedresponses = 1;
1.1369    raeburn  13104: # We need to get the original file and the imported file to get the response order correct
                   13105: # Load and inspect original file
1.1372    raeburn  13106:                                     if ($#origfiletagids<0) {
                   13107:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   13108:                                         $origfile=&getfile($origfilelocation);
                   13109:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   13110:                                     }
1.1369    raeburn  13111:                                 }
                   13112:                             }
                   13113:                         }
1.1370    raeburn  13114: # Do not overwrite contents of %metaentry hash for resource itself with 
                   13115: # hash populated for imported library file
                   13116:                         %metaentry = %currmetaentry;
                   13117:                         undef(%currmetaentry);
1.1374    raeburn  13118:                         if ($importmode eq 'part') {
1.1068    www      13119: # Import as part(s)
1.1069    www      13120:                            $importedparts=1;
                   13121: # We need to get the original file and the imported file to get the part order correct
                   13122: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369    raeburn  13123: # Load and inspect original file if we didn't do that already
                   13124:                            if ($#origfiletagids<0) {
                   13125:                                undef(%importedrespids);
                   13126:                                undef(%importedpartids);
                   13127:                                if ($origfile eq '') {
                   13128:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   13129:                                    $origfile=&getfile($origfilelocation);
                   13130:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   13131:                                }
1.1070    www      13132:                            }
1.1372    raeburn  13133:                            my @impfilepartids;
                   13134: # If <partorder> tag is included in metadata for the imported file
                   13135: # get the parts in the imported file from that.
                   13136:                            if (grep(/^partorder$/,@libfilekeys)) {
                   13137:                                %currmetaentry = %metaentry;
                   13138:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   13139:                                                             $depthcount+1);
                   13140:                                %metaentry = %currmetaentry;
                   13141:                                undef(%currmetaentry);
                   13142:                                if ($libpartorder ne '') {
                   13143:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
                   13144:                                }
                   13145:                            } else {
                   13146: # If no <partorder> tag available, load and inspect imported file
                   13147:                                my $impfile=&getfile($location);
                   13148:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   13149:                            }
1.1069    www      13150:                            if ($#impfilepartids>=0) {
                   13151: # This problem had parts
1.1070    www      13152:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      13153:                            } else {
                   13154: # Importing by turning a single problem into a problem part
                   13155: # It gets the import-tags ID as part-ID
                   13156:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      13157:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      13158:                            }
1.1068    www      13159:                         } else {
1.1374    raeburn  13160: # Import as problem or as normal import
                   13161:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   13162:                             unless ($importmode eq 'problem') {
1.1068    www      13163: # Normal import
1.1374    raeburn  13164:                                 if (defined($token->[2]->{'id'})) {
                   13165:                                     $unikey.='_'.$token->[2]->{'id'};
                   13166:                                 }
                   13167:                             }
                   13168: # Check metadata for imported file to
                   13169: # see if it contained parts
                   13170:                             if (grep(/^partorder$/,@libfilekeys)) {
                   13171:                                 %currmetaentry = %metaentry;
                   13172:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   13173:                                                              $depthcount+1);
                   13174:                                 %metaentry = %currmetaentry;
                   13175:                                 undef(%currmetaentry);
                   13176:                                 if ($libpartorder ne '') {
                   13177:                                     $importedparts = 1;
                   13178:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
                   13179:                                 }
                   13180:                             }
1.1067    www      13181:                         }
1.339     albertel 13182: 			if ($depthcount<20) {
1.736     albertel 13183: 			    my $metadata = 
1.1362    raeburn  13184: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 13185: 					  $depthcount+1);
                   13186: 			    foreach my $meta (split(',',$metadata)) {
                   13187: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   13188: 				$metathesekeys{$meta}=1;
1.339     albertel 13189: 			    }
1.1068    www      13190:                         }
1.1067    www      13191: 		    } else {
                   13192: #
                   13193: # Not importing, some other kind of non-package, non-library start tag
                   13194: # 
                   13195:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   13196:                         if (defined($token->[2]->{'id'})) {
                   13197:                             $unikey.='_'.$token->[2]->{'id'};
                   13198:                         }
1.339     albertel 13199: 			if (defined($token->[2]->{'name'})) { 
                   13200: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   13201: 			}
                   13202: 			$metathesekeys{$unikey}=1;
1.736     albertel 13203: 			foreach my $param (@{$token->[3]}) {
                   13204: 			    $metaentry{':'.$unikey.'.'.$param} =
                   13205: 				$token->[2]->{$param};
1.339     albertel 13206: 			}
                   13207: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 13208: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 13209: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   13210: 		 # only ws inside the tag, and not in default, so use default
                   13211: 		 # as value
1.599     albertel 13212: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 13213: 			} elsif ( $internaltext =~ /\S/ ) {
                   13214: 		  # something interesting inside the tag
                   13215: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 13216: 			} else {
1.908     albertel 13217: 		  # no interesting values, don't set a default
1.339     albertel 13218: 			}
1.172     www      13219: # end of not-a-package not-a-library import
1.339     albertel 13220: 		    }
1.172     www      13221: # end of not-a-package start tag
1.339     albertel 13222: 		}
1.172     www      13223: # the next is the end of "start tag"
1.339     albertel 13224: 	    }
                   13225: 	}
1.483     albertel 13226: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 13227: 	$extension = lc($extension);
                   13228: 	if ($extension eq 'htm') { $extension='html'; }
                   13229: 
1.737     albertel 13230: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 13231: 	    #no specific packages #how's our extension
                   13232: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 13233: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 13234: 					 \%metathesekeys);
                   13235: 	}
1.883     albertel 13236: 
                   13237: 	if (!exists($metaentry{':packages'})
                   13238: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 13239: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 13240: 		#no specific packages well let's get default then
                   13241: 		if ($key!~/^default&/) { next; }
1.488     albertel 13242: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 13243: 					     \%metathesekeys);
                   13244: 	    }
                   13245: 	}
1.338     www      13246: # are there custom rights to evaluate
1.599     albertel 13247: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 13248: 
1.338     www      13249:     #
                   13250:     # Importing a rights file here
1.339     albertel 13251:     #
                   13252: 	    unless ($depthcount) {
1.599     albertel 13253: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 13254: 		my $dir=$filename;
                   13255: 		$dir=~s|[^/]*$||;
                   13256: 		$location=&filelocation($dir,$location);
1.736     albertel 13257: 		my $rights_metadata =
1.1362    raeburn  13258: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 13259: 			      $depthcount+1);
                   13260: 		foreach my $rights (split(',',$rights_metadata)) {
                   13261: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   13262: 		    $metathesekeys{$rights}=1;
1.339     albertel 13263: 		}
                   13264: 	    }
                   13265: 	}
1.737     albertel 13266: 	# uniqifiy package listing
                   13267: 	my %seen;
                   13268: 	my @uniq_packages =
                   13269: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   13270: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   13271: 
1.1369    raeburn  13272:         if (($importedresponses) || ($importedparts)) {
                   13273:             if ($importedparts) {
1.1070    www      13274: # We had imported parts and need to rebuild partorder
1.1369    raeburn  13275:                 $metaentry{':partorder'}='';
                   13276:                 $metathesekeys{'partorder'}=1;
                   13277:             }
                   13278:             if ($importedresponses) {
                   13279: # We had imported responses and need to rebuil responseorder
                   13280:                 $metaentry{':responseorder'}='';
                   13281:                 $metathesekeys{'responseorder'}=1;
                   13282:             }
                   13283:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   13284:                 my $origid = $origfiletagids[$index+1];
                   13285:                 if ($origfiletagids[$index] eq 'part') {
                   13286: # Original part, part of the problem
                   13287:                     if ($importedparts) {
                   13288:                         $metaentry{':partorder'}.=','.$origid;
                   13289:                     }
                   13290:                 } elsif ($origfiletagids[$index] eq 'import') {
                   13291:                     if ($importedparts) {
                   13292: # We have imported parts at this position
1.1373    raeburn  13293:                         if ($importedpartids{$origid} ne '') {
                   13294:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   13295:                         }
1.1369    raeburn  13296:                     }
                   13297:                     if ($importedresponses) {
                   13298: # We have imported responses at this position
1.1373    raeburn  13299:                         if ($importedrespids{$origid} ne '') {
                   13300:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369    raeburn  13301:                         }
                   13302:                     }
                   13303:                 } else {
                   13304: # Original response item, part of the problem
                   13305:                     if ($importedresponses) {
                   13306:                         $metaentry{':responseorder'}.=','.$origid;
                   13307:                     }
                   13308:                 }
                   13309:             }
                   13310:             if ($importedparts) {
                   13311:                 $metaentry{':partorder'}=~s/^\,//;
                   13312:             }
                   13313:             if ($importedresponses) {
                   13314:                 $metaentry{':responseorder'}=~s/^\,//;
                   13315:             }
1.1070    www      13316:         }
1.737     albertel 13317: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 13318: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  13319: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371    raeburn  13320:         unless ($liburi) {
                   13321: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
                   13322:         }
1.177     www      13323: # this is the end of "was not already recently cached
1.71      www      13324:     }
1.599     albertel 13325:     return $metaentry{':'.$what};
1.261     albertel 13326: }
                   13327: 
1.488     albertel 13328: sub metadata_create_package_def {
1.483     albertel 13329:     my ($uri,$key,$package,$metathesekeys)=@_;
                   13330:     my ($pack,$name,$subp)=split(/\&/,$key);
                   13331:     if ($subp eq 'default') { next; }
                   13332:     
1.599     albertel 13333:     if (defined($metaentry{':packages'})) {
                   13334: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 13335:     } else {
1.599     albertel 13336: 	$metaentry{':packages'}=$package;
1.483     albertel 13337:     }
                   13338:     my $value=$packagetab{$key};
                   13339:     my $unikey;
                   13340:     $unikey='parameter_0_'.$name;
1.599     albertel 13341:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 13342:     $$metathesekeys{$unikey}=1;
1.599     albertel 13343:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   13344: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 13345:     }
1.599     albertel 13346:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   13347: 	$metaentry{':'.$unikey}=
                   13348: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 13349:     }
                   13350: }
                   13351: 
1.261     albertel 13352: sub metadata_generate_part0 {
                   13353:     my ($metadata,$metacache,$uri) = @_;
                   13354:     my %allnames;
1.737     albertel 13355:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 13356: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 13357: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   13358: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 13359: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 13360: 	    $allnames{$name}=$part;
                   13361: 	  }
                   13362: 	}
                   13363:     }
                   13364:     foreach my $name (keys(%allnames)) {
                   13365:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 13366:       my $key=":parameter_0_$name";
1.261     albertel 13367:       $$metacache{"$key.part"}='0';
                   13368:       $$metacache{"$key.name"}=$name;
1.428     albertel 13369:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 13370: 					   $allnames{$name}.'_'.$name.
                   13371: 					   '.type'};
1.428     albertel 13372:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 13373: 			     '.display'};
1.644     www      13374:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 13375:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 13376:       $$metacache{"$key.display"}=$olddis;
                   13377:     }
1.71      www      13378: }
                   13379: 
1.764     albertel 13380: # ------------------------------------------------------ Devalidate title cache
                   13381: 
                   13382: sub devalidate_title_cache {
                   13383:     my ($url)=@_;
                   13384:     if (!$env{'request.course.id'}) { return; }
                   13385:     my $symb=&symbread($url);
                   13386:     if (!$symb) { return; }
                   13387:     my $key=$env{'request.course.id'}."\0".$symb;
                   13388:     &devalidate_cache_new('title',$key);
                   13389: }
                   13390: 
1.1014    droeschl 13391: # ------------------------------------------------- Get the title of a course
                   13392: 
                   13393: sub current_course_title {
                   13394:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   13395: }
1.301     www      13396: # ------------------------------------------------- Get the title of a resource
                   13397: 
                   13398: sub gettitle {
                   13399:     my $urlsymb=shift;
                   13400:     my $symb=&symbread($urlsymb);
1.534     albertel 13401:     if ($symb) {
1.620     albertel 13402: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 13403: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 13404: 	if (defined($cached)) { 
                   13405: 	    return $result;
                   13406: 	}
1.534     albertel 13407: 	my ($map,$resid,$url)=&decode_symb($symb);
                   13408: 	my $title='';
1.907     albertel 13409: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   13410: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   13411: 	} else {
                   13412: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   13413: 		    &GDBM_READER(),0640)) {
                   13414: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   13415: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   13416: 		untie(%bighash);
                   13417: 	    }
1.534     albertel 13418: 	}
                   13419: 	$title=~s/\&colon\;/\:/gs;
                   13420: 	if ($title) {
1.1159    www      13421: # Remember both $symb and $title for dynamic metadata
                   13422:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      13423:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      13424: # Cache this title and then return it
1.599     albertel 13425: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 13426: 	}
                   13427: 	$urlsymb=$url;
                   13428:     }
                   13429:     my $title=&metadata($urlsymb,'title');
                   13430:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   13431:     return $title;
1.301     www      13432: }
1.613     albertel 13433: 
1.614     albertel 13434: sub get_slot {
                   13435:     my ($which,$cnum,$cdom)=@_;
                   13436:     if (!$cnum || !$cdom) {
1.790     albertel 13437: 	(undef,my $courseid)=&whichuser();
1.620     albertel 13438: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   13439: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 13440:     }
1.703     albertel 13441:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   13442:     my %slotinfo;
                   13443:     if (exists($remembered{$key})) {
                   13444: 	$slotinfo{$which} = $remembered{$key};
                   13445:     } else {
                   13446: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   13447: 	&Apache::lonhomework::showhash(%slotinfo);
                   13448: 	my ($tmp)=keys(%slotinfo);
                   13449: 	if ($tmp=~/^error:/) { return (); }
                   13450: 	$remembered{$key} = $slotinfo{$which};
                   13451:     }
1.616     albertel 13452:     if (ref($slotinfo{$which}) eq 'HASH') {
                   13453: 	return %{$slotinfo{$which}};
                   13454:     }
                   13455:     return $slotinfo{$which};
1.614     albertel 13456: }
1.1150    raeburn  13457: 
                   13458: sub get_reservable_slots {
                   13459:     my ($cnum,$cdom,$uname,$udom) = @_;
                   13460:     my $now = time;
                   13461:     my $reservable_info;
                   13462:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   13463:     if (exists($remembered{$key})) {
                   13464:         $reservable_info = $remembered{$key};
                   13465:     } else {
                   13466:         my %resv;
                   13467:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   13468:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   13469:         $reservable_info = \%resv;
                   13470:         $remembered{$key} = $reservable_info;
                   13471:     }
                   13472:     return $reservable_info;
                   13473: }
                   13474: 
                   13475: sub get_course_slots {
                   13476:     my ($cnum,$cdom) = @_;
                   13477:     my $hashid=$cnum.':'.$cdom;
                   13478:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   13479:     if (defined($cached)) {
                   13480:         if (ref($result) eq 'HASH') {
                   13481:             return %{$result};
                   13482:         }
                   13483:     } else {
                   13484:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   13485:         my ($tmp) = keys(%slots);
                   13486:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  13487:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  13488:             return %slots;
                   13489:         }
                   13490:     }
                   13491:     return;
                   13492: }
                   13493: 
                   13494: sub devalidate_slots_cache {
                   13495:     my ($cnum,$cdom)=@_;
                   13496:     my $hashid=$cnum.':'.$cdom;
                   13497:     &devalidate_cache_new('allslots',$hashid);
                   13498: }
                   13499: 
1.1181    raeburn  13500: sub get_coursechange {
                   13501:     my ($cdom,$cnum) = @_;
                   13502:     if ($cdom eq '' || $cnum eq '') {
                   13503:         return unless ($env{'request.course.id'});
                   13504:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   13505:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   13506:     }
                   13507:     my $hashid=$cdom.'_'.$cnum;
                   13508:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   13509:     if ((defined($cached)) && ($change ne '')) {
                   13510:         return $change;
                   13511:     } else {
                   13512:         my %crshash;
                   13513:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   13514:         if ($crshash{'internal.contentchange'} eq '') {
                   13515:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   13516:             if ($change eq '') {
                   13517:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   13518:                 $change = $crshash{'internal.created'};
                   13519:             }
                   13520:         } else {
                   13521:             $change = $crshash{'internal.contentchange'};
                   13522:         }
                   13523:         my $cachetime = 600;
                   13524:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   13525:     }
                   13526:     return $change;
                   13527: }
                   13528: 
                   13529: sub devalidate_coursechange_cache {
                   13530:     my ($cnum,$cdom)=@_;
                   13531:     my $hashid=$cnum.':'.$cdom;
                   13532:     &devalidate_cache_new('crschange',$hashid);
                   13533: }
                   13534: 
1.31      www      13535: # ------------------------------------------------- Update symbolic store links
                   13536: 
                   13537: sub symblist {
                   13538:     my ($mapname,%newhash)=@_;
1.438     www      13539:     $mapname=&deversion(&declutter($mapname));
1.31      www      13540:     my %hash;
1.620     albertel 13541:     if (($env{'request.course.fn'}) && (%newhash)) {
                   13542:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 13543:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  13544: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 13545: 		next if ($url eq 'last_known'
                   13546: 			 && $env{'form.no_update_last_known'});
                   13547: 		$hash{declutter($url)}=&encode_symb($mapname,
                   13548: 						    $newhash{$url}->[1],
                   13549: 						    $newhash{$url}->[0]);
1.191     harris41 13550:             }
1.31      www      13551:             if (untie(%hash)) {
                   13552: 		return 'ok';
                   13553:             }
                   13554:         }
                   13555:     }
                   13556:     return 'error';
1.212     www      13557: }
                   13558: 
                   13559: # --------------------------------------------------------------- Verify a symb
                   13560: 
                   13561: sub symbverify {
1.1190    raeburn  13562:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      13563:     my $thisfn=$thisurl;
1.439     www      13564:     $thisfn=&declutter($thisfn);
1.215     www      13565: # direct jump to resource in page or to a sequence - will construct own symbs
                   13566:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   13567: # check URL part
1.409     www      13568:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      13569: 
1.431     www      13570:     unless ($url eq $thisfn) { return 0; }
1.213     www      13571: 
1.216     www      13572:     $symb=&symbclean($symb);
1.510     www      13573:     $thisurl=&deversion($thisurl);
1.439     www      13574:     $thisfn=&deversion($thisfn);
1.213     www      13575: 
                   13576:     my %bighash;
                   13577:     my $okay=0;
1.431     www      13578: 
1.620     albertel 13579:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13580:                             &GDBM_READER(),0640)) {
1.1032    raeburn  13581:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   13582:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  13583:             if ($map =~ m{^uploaded/.+\.page$}) {
                   13584:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   13585:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   13586:             }
                   13587:         }
                   13588:         my $ids;
1.1419    raeburn  13589:         if ($map =~ m{^uploaded/.+\.page$}) {
                   13590:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
1.1204    raeburn  13591:         } else {
                   13592:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  13593:         }
1.1102    raeburn  13594:         unless ($ids) {
                   13595:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   13596:             $ids=$bighash{$idkey};
1.216     www      13597:         }
                   13598:         if ($ids) {
                   13599: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  13600:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  13601:                 $symb =~ s/\?.+$//;
1.1202    raeburn  13602:             }
1.800     albertel 13603: 	    foreach my $id (split(/\,/,$ids)) {
                   13604: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      13605:                if (
                   13606:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  13607:    eq $symb) {
                   13608:                    if (ref($encstate)) {
                   13609:                        $$encstate = $bighash{'encrypted_'.$id};
                   13610:                    }
1.620     albertel 13611: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  13612: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   13613:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  13614: 		       $okay=1;
1.1202    raeburn  13615:                        last;
1.582     albertel 13616: 		   }
                   13617: 	       }
1.216     www      13618: 	   }
                   13619:         }
1.213     www      13620: 	untie(%bighash);
                   13621:     }
                   13622:     return $okay;
1.31      www      13623: }
                   13624: 
1.210     www      13625: # --------------------------------------------------------------- Clean-up symb
                   13626: 
                   13627: sub symbclean {
                   13628:     my $symb=shift;
1.568     albertel 13629:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      13630: # remove version from map
                   13631:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      13632: 
1.210     www      13633: # remove version from URL
                   13634:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      13635: 
1.507     www      13636: # remove wrapper
                   13637: 
1.510     www      13638:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 13639:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      13640:     return $symb;
1.409     www      13641: }
                   13642: 
                   13643: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 13644: 
                   13645: sub encode_symb {
                   13646:     my ($map,$resid,$url)=@_;
                   13647:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   13648: }
1.409     www      13649: 
                   13650: sub decode_symb {
1.568     albertel 13651:     my $symb=shift;
                   13652:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   13653:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      13654:     return (&fixversion($map),$resid,&fixversion($url));
                   13655: }
                   13656: 
                   13657: sub fixversion {
                   13658:     my $fn=shift;
1.609     banghart 13659:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      13660:     my %bighash;
                   13661:     my $uri=&clutter($fn);
1.620     albertel 13662:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      13663: # is this cached?
1.599     albertel 13664:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      13665:     if (defined($cached)) { return $result; }
                   13666: # unfortunately not cached, or expired
1.620     albertel 13667:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      13668: 	    &GDBM_READER(),0640)) {
                   13669:  	if ($bighash{'version_'.$uri}) {
                   13670:  	    my $version=$bighash{'version_'.$uri};
1.444     www      13671:  	    unless (($version eq 'mostrecent') || 
                   13672: 		    ($version==&getversion($uri))) {
1.440     www      13673:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   13674:  	    }
                   13675:  	}
                   13676:  	untie %bighash;
1.413     www      13677:     }
1.599     albertel 13678:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      13679: }
                   13680: 
                   13681: sub deversion {
                   13682:     my $url=shift;
                   13683:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   13684:     return $url;
1.210     www      13685: }
                   13686: 
1.31      www      13687: # ------------------------------------------------------ Return symb list entry
                   13688: 
                   13689: sub symbread {
1.1424    raeburn  13690:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
1.1427    raeburn  13691:         $ignoresymbdb,$noenccheck)=@_;
1.1265    raeburn  13692:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1427    raeburn  13693:     if (defined($env{$cache_str})) {
1.1424    raeburn  13694:         unless (ref($possibles) eq 'HASH') {
                   13695:             if ($ignorecachednull) {
                   13696:                 return $env{$cache_str} unless ($env{$cache_str} eq '');
                   13697:             } else {
                   13698:                 return $env{$cache_str};
                   13699:             }
1.1282    raeburn  13700:         }
                   13701:     }
1.242     www      13702: # no filename provided? try from environment
1.1265    raeburn  13703:     unless ($thisfn) {
1.620     albertel 13704:         if ($env{'request.symb'}) {
1.1427    raeburn  13705:             return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 13706: 	}
1.620     albertel 13707: 	$thisfn=$env{'request.filename'};
1.44      www      13708:     }
1.569     albertel 13709:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      13710: # is that filename actually a symb? Verify, clean, and return
                   13711:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 13712: 	if (&symbverify($thisfn,$1)) {
1.1427    raeburn  13713: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 13714: 	}
1.242     www      13715:     }
1.44      www      13716:     $thisfn=declutter($thisfn);
1.31      www      13717:     my %hash;
1.37      www      13718:     my %bighash;
                   13719:     my $syval='';
1.620     albertel 13720:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  13721:         my $targetfn = $thisfn;
1.609     banghart 13722:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  13723:             $targetfn = 'adm/wrapper/'.$thisfn;
                   13724:         }
1.687     albertel 13725: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   13726: 	    $targetfn=$1;
                   13727: 	}
1.1427    raeburn  13728:         unless ($ignoresymbdb) {
1.1424    raeburn  13729:             if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
                   13730:                           &GDBM_READER(),0640)) {
                   13731: 	        $syval=$hash{$targetfn};
                   13732:                 untie(%hash);
                   13733:             }
1.1427    raeburn  13734:             if ($syval && $checkforblock) {
                   13735:                 my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
1.1424    raeburn  13736:                 if (@blockers) {
                   13737:                     $syval='';
                   13738:                 }
                   13739:             }
1.37      www      13740:         }
                   13741: # ---------------------------------------------------------- There was an entry
                   13742:         if ($syval) {
1.601     albertel 13743: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 13744: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  13745: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13746: 		    #return $env{$cache_str}='';
1.601     albertel 13747: 		#}    
                   13748: 		#$syval.=$1;
                   13749: 	    #}
1.37      www      13750:         } else {
                   13751: # ------------------------------------------------------- Was not in symb table
1.620     albertel 13752:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 13753:                             &GDBM_READER(),0640)) {
1.37      www      13754: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      13755:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      13756:               unless ($ids) { 
                   13757:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      13758:               }
                   13759:               unless ($ids) {
                   13760: # alias?
                   13761: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      13762:               }
1.37      www      13763:               if ($ids) {
                   13764: # ------------------------------------------------------------------- Has ID(s)
                   13765:                  my @possibilities=split(/\,/,$ids);
1.39      www      13766:                  if ($#possibilities==0) {
                   13767: # ----------------------------------------------- There is only one possibility
1.37      www      13768: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 13769: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13770: 						    $resid,$thisfn);
1.1282    raeburn  13771:                      if (ref($possibles) eq 'HASH') {
1.1424    raeburn  13772:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
                   13773:                              $possibles->{$syval} = 1;
                   13774:                          }
1.1282    raeburn  13775:                      }
                   13776:                      if ($checkforblock) {
1.1424    raeburn  13777:                          unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
1.1426    raeburn  13778:                              my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
1.1424    raeburn  13779:                              if (@blockers) {
                   13780:                                  $syval = '';
1.1425    raeburn  13781:                                  untie(%bighash);
                   13782:                                  return $env{$cache_str}='';
1.1424    raeburn  13783:                              }
1.1282    raeburn  13784:                          }
                   13785:                      }
                   13786:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      13787: # ------------------------------------------ There is more than one possibility
                   13788:                      my $realpossible=0;
1.800     albertel 13789:                      foreach my $id (@possibilities) {
                   13790: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  13791:                          my $canaccess;
                   13792:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   13793:                              $canaccess = 1;
                   13794:                          } else { 
                   13795:                              $canaccess = &allowed('bre',$file);
                   13796:                          }
                   13797:                          if ($canaccess) {
                   13798:          		     my ($mapid,$resid)=split(/\./,$id);
                   13799:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   13800:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   13801: 						             $resid,$thisfn);
1.1424    raeburn  13802:                                  next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
1.1426    raeburn  13803:                                  next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
1.1282    raeburn  13804:                                  if ($checkforblock) {
1.1426    raeburn  13805:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
1.1424    raeburn  13806:                                      if (@blockers > 0) {
                   13807:                                          $syval = '';
                   13808:                                      } else {
1.1282    raeburn  13809:                                          $syval = $poss_syval;
                   13810:                                          $realpossible++;
                   13811:                                      }
                   13812:                                  } else {
                   13813:                                      $syval = $poss_syval;
                   13814:                                      $realpossible++;
                   13815:                                  }
1.1424    raeburn  13816:                                  if ($syval) {
                   13817:                                      if (ref($possibles) eq 'HASH') {
                   13818:                                          $possibles->{$syval} = 1;
                   13819:                                      }
                   13820:                                  }
1.1282    raeburn  13821:                              }
1.39      www      13822: 			 }
1.191     harris41 13823:                      }
1.39      www      13824: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      13825:                  } else {
                   13826:                      $syval='';
1.37      www      13827:                  }
                   13828: 	      }
1.1282    raeburn  13829:               untie(%bighash);
1.481     raeburn  13830:            }
1.31      www      13831:         }
1.62      www      13832:         if ($syval) {
1.1427    raeburn  13833: 	    return $env{$cache_str}=$syval;
1.62      www      13834:         }
1.31      www      13835:     }
1.949     raeburn  13836:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 13837:     return $env{$cache_str}='';
1.31      www      13838: }
                   13839: 
                   13840: # ---------------------------------------------------------- Return random seed
                   13841: 
1.32      www      13842: sub numval {
                   13843:     my $txt=shift;
                   13844:     $txt=~tr/A-J/0-9/;
                   13845:     $txt=~tr/a-j/0-9/;
                   13846:     $txt=~tr/K-T/0-9/;
                   13847:     $txt=~tr/k-t/0-9/;
                   13848:     $txt=~tr/U-Z/0-5/;
                   13849:     $txt=~tr/u-z/0-5/;
                   13850:     $txt=~s/\D//g;
1.564     albertel 13851:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      13852:     return int($txt);
1.368     albertel 13853: }
                   13854: 
1.484     albertel 13855: sub numval2 {
                   13856:     my $txt=shift;
                   13857:     $txt=~tr/A-J/0-9/;
                   13858:     $txt=~tr/a-j/0-9/;
                   13859:     $txt=~tr/K-T/0-9/;
                   13860:     $txt=~tr/k-t/0-9/;
                   13861:     $txt=~tr/U-Z/0-5/;
                   13862:     $txt=~tr/u-z/0-5/;
                   13863:     $txt=~s/\D//g;
                   13864:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13865:     my $total;
                   13866:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 13867:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 13868:     return int($total);
                   13869: }
                   13870: 
1.575     albertel 13871: sub numval3 {
                   13872:     use integer;
                   13873:     my $txt=shift;
                   13874:     $txt=~tr/A-J/0-9/;
                   13875:     $txt=~tr/a-j/0-9/;
                   13876:     $txt=~tr/K-T/0-9/;
                   13877:     $txt=~tr/k-t/0-9/;
                   13878:     $txt=~tr/U-Z/0-5/;
                   13879:     $txt=~tr/u-z/0-5/;
                   13880:     $txt=~s/\D//g;
                   13881:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   13882:     my $total;
                   13883:     foreach my $val (@txts) { $total+=$val; }
                   13884:     if ($_64bit) { $total=(($total<<32)>>32); }
                   13885:     return $total;
                   13886: }
                   13887: 
1.675     albertel 13888: sub digest {
                   13889:     my ($data)=@_;
                   13890:     my $digest=&Digest::MD5::md5($data);
                   13891:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   13892:     my ($e,$f);
                   13893:     {
                   13894:         use integer;
                   13895:         $e=($a+$b);
                   13896:         $f=($c+$d);
                   13897:         if ($_64bit) {
                   13898:             $e=(($e<<32)>>32);
                   13899:             $f=(($f<<32)>>32);
                   13900:         }
                   13901:     }
                   13902:     if (wantarray) {
                   13903: 	return ($e,$f);
                   13904:     } else {
                   13905: 	my $g;
                   13906: 	{
                   13907: 	    use integer;
                   13908: 	    $g=($e+$f);
                   13909: 	    if ($_64bit) {
                   13910: 		$g=(($g<<32)>>32);
                   13911: 	    }
                   13912: 	}
                   13913: 	return $g;
                   13914:     }
                   13915: }
                   13916: 
1.368     albertel 13917: sub latest_rnd_algorithm_id {
1.675     albertel 13918:     return '64bit5';
1.366     albertel 13919: }
1.32      www      13920: 
1.503     albertel 13921: sub get_rand_alg {
                   13922:     my ($courseid)=@_;
1.790     albertel 13923:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 13924:     if ($courseid) {
1.620     albertel 13925: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 13926:     }
                   13927:     return &latest_rnd_algorithm_id();
                   13928: }
                   13929: 
1.562     albertel 13930: sub validCODE {
                   13931:     my ($CODE)=@_;
                   13932:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   13933:     return 0;
                   13934: }
                   13935: 
1.491     albertel 13936: sub getCODE {
1.620     albertel 13937:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 13938:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   13939: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   13940: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 13941: 	return $Apache::lonhomework::history{'resource.CODE'};
                   13942:     }
                   13943:     return undef;
                   13944: }
1.1133    foxr     13945: #
                   13946: #  Determines the random seed for a specific context:
                   13947: #
                   13948: # parameters:
                   13949: #   symb      - in course context the symb for the seed.
                   13950: #   course_id - The course id of the form domain_coursenum.
                   13951: #   domain    - Domain for the user.
                   13952: #   course    - Course for the user.
                   13953: #   cenv      - environment of the course.
                   13954: #
                   13955: # NOTE:
                   13956: #   All parameters are picked out of the environment if missing
                   13957: #   or not defined.
                   13958: #   If a symb cannot be determined the current time is used instead.
                   13959: #
                   13960: #  For a given well defined symb, courside, domain, username,
                   13961: #  and course environment, the seed is reproducible.
                   13962: #
1.31      www      13963: sub rndseed {
1.1133    foxr     13964:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 13965:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 13966:     if (!defined($symb)) {
1.366     albertel 13967: 	unless ($symb=$wsymb) { return time; }
                   13968:     }
1.1146    foxr     13969:     if (!defined $courseid) { 
                   13970: 	$courseid=$wcourseid; 
                   13971:     }
                   13972:     if (!defined $domain) { $domain=$wdomain; }
                   13973:     if (!defined $username) { $username=$wusername }
1.1133    foxr     13974: 
                   13975:     my $which;
                   13976:     if (defined($cenv->{'rndseed'})) {
                   13977: 	$which = $cenv->{'rndseed'};
                   13978:     } else {
                   13979: 	$which =&get_rand_alg($courseid);
                   13980:     }
1.491     albertel 13981:     if (defined(&getCODE())) {
1.1133    foxr     13982: 
1.675     albertel 13983: 	if ($which eq '64bit5') {
                   13984: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   13985: 	} elsif ($which eq '64bit4') {
1.575     albertel 13986: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   13987: 	} else {
                   13988: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   13989: 	}
1.675     albertel 13990:     } elsif ($which eq '64bit5') {
                   13991: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 13992:     } elsif ($which eq '64bit4') {
                   13993: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 13994:     } elsif ($which eq '64bit3') {
                   13995: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 13996:     } elsif ($which eq '64bit2') {
                   13997: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 13998:     } elsif ($which eq '64bit') {
                   13999: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   14000:     }
                   14001:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   14002: }
                   14003: 
                   14004: sub rndseed_32bit {
                   14005:     my ($symb,$courseid,$domain,$username)=@_;
                   14006:     {
                   14007: 	use integer;
                   14008: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   14009: 	my $symbseed=numval($symb) << 22;
                   14010: 	my $namechck=unpack("%32C*",$username) << 17;
                   14011: 	my $nameseed=numval($username) << 12;
                   14012: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   14013: 	my $courseseed=unpack("%32C*",$courseid);
                   14014: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 14015: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   14016: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 14017: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 14018: 	return $num;
                   14019:     }
                   14020: }
                   14021: 
                   14022: sub rndseed_64bit {
                   14023:     my ($symb,$courseid,$domain,$username)=@_;
                   14024:     {
                   14025: 	use integer;
                   14026: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   14027: 	my $symbseed=numval($symb) << 10;
                   14028: 	my $namechck=unpack("%32S*",$username);
                   14029: 	
                   14030: 	my $nameseed=numval($username) << 21;
                   14031: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   14032: 	my $courseseed=unpack("%32S*",$courseid);
                   14033: 	
                   14034: 	my $num1=$symbchck+$symbseed+$namechck;
                   14035: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 14036: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   14037: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 14038: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 14039: 	return "$num1,$num2";
1.155     albertel 14040:     }
1.366     albertel 14041: }
                   14042: 
1.443     albertel 14043: sub rndseed_64bit2 {
                   14044:     my ($symb,$courseid,$domain,$username)=@_;
                   14045:     {
                   14046: 	use integer;
                   14047: 	# strings need to be an even # of cahracters long, it it is odd the
                   14048:         # last characters gets thrown away
                   14049: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   14050: 	my $symbseed=numval($symb) << 10;
                   14051: 	my $namechck=unpack("%32S*",$username.' ');
                   14052: 	
                   14053: 	my $nameseed=numval($username) << 21;
1.501     albertel 14054: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   14055: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   14056: 	
                   14057: 	my $num1=$symbchck+$symbseed+$namechck;
                   14058: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 14059: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   14060: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 14061: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 14062: 	return "$num1,$num2";
                   14063:     }
                   14064: }
                   14065: 
                   14066: sub rndseed_64bit3 {
                   14067:     my ($symb,$courseid,$domain,$username)=@_;
                   14068:     {
                   14069: 	use integer;
                   14070: 	# strings need to be an even # of cahracters long, it it is odd the
                   14071:         # last characters gets thrown away
                   14072: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   14073: 	my $symbseed=numval2($symb) << 10;
                   14074: 	my $namechck=unpack("%32S*",$username.' ');
                   14075: 	
                   14076: 	my $nameseed=numval2($username) << 21;
1.443     albertel 14077: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   14078: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   14079: 	
                   14080: 	my $num1=$symbchck+$symbseed+$namechck;
                   14081: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 14082: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   14083: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 14084: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      14085: 	
1.503     albertel 14086: 	return "$num1:$num2";
1.443     albertel 14087:     }
                   14088: }
                   14089: 
1.575     albertel 14090: sub rndseed_64bit4 {
                   14091:     my ($symb,$courseid,$domain,$username)=@_;
                   14092:     {
                   14093: 	use integer;
                   14094: 	# strings need to be an even # of cahracters long, it it is odd the
                   14095:         # last characters gets thrown away
                   14096: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   14097: 	my $symbseed=numval3($symb) << 10;
                   14098: 	my $namechck=unpack("%32S*",$username.' ');
                   14099: 	
                   14100: 	my $nameseed=numval3($username) << 21;
                   14101: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   14102: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   14103: 	
                   14104: 	my $num1=$symbchck+$symbseed+$namechck;
                   14105: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 14106: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   14107: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 14108: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      14109: 	
1.575     albertel 14110: 	return "$num1:$num2";
                   14111:     }
                   14112: }
                   14113: 
1.675     albertel 14114: sub rndseed_64bit5 {
                   14115:     my ($symb,$courseid,$domain,$username)=@_;
                   14116:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   14117:     return "$num1:$num2";
                   14118: }
                   14119: 
1.366     albertel 14120: sub rndseed_CODE_64bit {
                   14121:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 14122:     {
1.366     albertel 14123: 	use integer;
1.443     albertel 14124: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 14125: 	my $symbseed=numval2($symb);
1.491     albertel 14126: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   14127: 	my $CODEseed=numval(&getCODE());
1.443     albertel 14128: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 14129: 	my $num1=$symbseed+$CODEchck;
                   14130: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 14131: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   14132: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 14133: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   14134: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 14135: 	return "$num1:$num2";
1.366     albertel 14136:     }
                   14137: }
                   14138: 
1.575     albertel 14139: sub rndseed_CODE_64bit4 {
                   14140:     my ($symb,$courseid,$domain,$username)=@_;
                   14141:     {
                   14142: 	use integer;
                   14143: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   14144: 	my $symbseed=numval3($symb);
                   14145: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   14146: 	my $CODEseed=numval3(&getCODE());
                   14147: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   14148: 	my $num1=$symbseed+$CODEchck;
                   14149: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 14150: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   14151: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 14152: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   14153: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   14154: 	return "$num1:$num2";
                   14155:     }
                   14156: }
                   14157: 
1.675     albertel 14158: sub rndseed_CODE_64bit5 {
                   14159:     my ($symb,$courseid,$domain,$username)=@_;
                   14160:     my $code = &getCODE();
                   14161:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   14162:     return "$num1:$num2";
                   14163: }
                   14164: 
1.366     albertel 14165: sub setup_random_from_rndseed {
                   14166:     my ($rndseed)=@_;
1.503     albertel 14167:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  14168:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   14169:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   14170:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   14171:         } else {
                   14172:             &Math::Random::random_set_seed($num1,$num2);
                   14173:         }
1.366     albertel 14174:     } else {
                   14175: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 14176:     }
1.36      albertel 14177: }
                   14178: 
1.474     albertel 14179: sub latest_receipt_algorithm_id {
1.835     albertel 14180:     return 'receipt3';
1.474     albertel 14181: }
                   14182: 
1.480     www      14183: sub recunique {
                   14184:     my $fucourseid=shift;
                   14185:     my $unique;
1.835     albertel 14186:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   14187: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 14188: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      14189:     } else {
                   14190: 	$unique=$perlvar{'lonReceipt'};
                   14191:     }
                   14192:     return unpack("%32C*",$unique);
                   14193: }
                   14194: 
                   14195: sub recprefix {
                   14196:     my $fucourseid=shift;
                   14197:     my $prefix;
1.835     albertel 14198:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   14199: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 14200: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      14201:     } else {
                   14202: 	$prefix=$perlvar{'lonHostID'};
                   14203:     }
                   14204:     return unpack("%32C*",$prefix);
                   14205: }
                   14206: 
1.76      www      14207: sub ireceipt {
1.474     albertel 14208:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 14209: 
                   14210:     my $return =&recprefix($fucourseid).'-';
                   14211: 
                   14212:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   14213: 	$env{'request.state'} eq 'construct') {
                   14214: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   14215: 	return $return;
                   14216:     }
                   14217: 
1.76      www      14218:     my $cuname=unpack("%32C*",$funame);
                   14219:     my $cudom=unpack("%32C*",$fudom);
                   14220:     my $cucourseid=unpack("%32C*",$fucourseid);
                   14221:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      14222:     my $cunique=&recunique($fucourseid);
1.474     albertel 14223:     my $cpart=unpack("%32S*",$part);
1.835     albertel 14224:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   14225: 
1.790     albertel 14226: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 14227: 			       
                   14228: 	$return.= ($cunique%$cuname+
                   14229: 		   $cunique%$cudom+
                   14230: 		   $cusymb%$cuname+
                   14231: 		   $cusymb%$cudom+
                   14232: 		   $cucourseid%$cuname+
                   14233: 		   $cucourseid%$cudom+
                   14234: 		   $cpart%$cuname+
                   14235: 		   $cpart%$cudom);
                   14236:     } else {
                   14237: 	$return.= ($cunique%$cuname+
                   14238: 		   $cunique%$cudom+
                   14239: 		   $cusymb%$cuname+
                   14240: 		   $cusymb%$cudom+
                   14241: 		   $cucourseid%$cuname+
                   14242: 		   $cucourseid%$cudom);
                   14243:     }
                   14244:     return $return;
1.76      www      14245: }
                   14246: 
                   14247: sub receipt {
1.474     albertel 14248:     my ($part)=@_;
1.790     albertel 14249:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 14250:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      14251: }
1.260     ng       14252: 
1.790     albertel 14253: sub whichuser {
                   14254:     my ($passedsymb)=@_;
                   14255:     my ($symb,$courseid,$domain,$name,$publicuser);
                   14256:     if (defined($env{'form.grade_symb'})) {
                   14257: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   14258: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   14259: 	if (!$allowed &&
                   14260: 	    exists($env{'request.course.sec'}) &&
                   14261: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   14262: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   14263: 			      '/'.$env{'request.course.sec'});
                   14264: 	}
                   14265: 	if ($allowed) {
                   14266: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   14267: 	    $courseid=$tmp_courseid;
                   14268: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   14269: 	    ($name)=&get_env_multiple('form.grade_username');
                   14270: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   14271: 	}
                   14272:     }
                   14273:     if (!$passedsymb) {
                   14274: 	$symb=&symbread();
                   14275:     } else {
                   14276: 	$symb=$passedsymb;
                   14277:     }
                   14278:     $courseid=$env{'request.course.id'};
                   14279:     $domain=$env{'user.domain'};
                   14280:     $name=$env{'user.name'};
                   14281:     if ($name eq 'public' && $domain eq 'public') {
                   14282: 	if (!defined($env{'form.username'})) {
                   14283: 	    $env{'form.username'}.=time.rand(10000000);
                   14284: 	}
                   14285: 	$name.=$env{'form.username'};
                   14286:     }
                   14287:     return ($symb,$courseid,$domain,$name,$publicuser);
                   14288: 
                   14289: }
                   14290: 
1.36      albertel 14291: # ------------------------------------------------------------ Serves up a file
1.472     albertel 14292: # returns either the contents of the file or 
                   14293: # -1 if the file doesn't exist
1.481     raeburn  14294: #
                   14295: # if the target is a file that was uploaded via DOCS, 
                   14296: # a check will be made to see if a current copy exists on the local server,
                   14297: # if it does this will be served, otherwise a copy will be retrieved from
                   14298: # the home server for the course and stored in /home/httpd/html/userfiles on
                   14299: # the local server.   
1.472     albertel 14300: 
1.36      albertel 14301: sub getfile {
1.538     albertel 14302:     my ($file) = @_;
1.609     banghart 14303:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 14304:     &repcopy($file);
                   14305:     return &readfile($file);
                   14306: }
                   14307: 
                   14308: sub repcopy_userfile {
                   14309:     my ($file)=@_;
1.1142    raeburn  14310:     my $londocroot = $perlvar{'lonDocRoot'};
                   14311:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  14312:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 14313:     my ($cdom,$cnum,$filename) = 
1.811     albertel 14314: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 14315:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   14316:     if (-e "$file") {
1.828     www      14317: # we already have a local copy, check it out
1.538     albertel 14318: 	my @fileinfo = stat($file);
1.828     www      14319: 	my $rtncode;
                   14320: 	my $info;
1.538     albertel 14321: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 14322: 	if ($lwpresp ne 'ok') {
1.828     www      14323: # there is no such file anymore, even though we had a local copy
1.482     albertel 14324: 	    if ($rtncode eq '404') {
1.538     albertel 14325: 		unlink($file);
1.482     albertel 14326: 	    }
                   14327: 	    return -1;
                   14328: 	}
                   14329: 	if ($info < $fileinfo[9]) {
1.828     www      14330: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  14331: 	    return 'ok';
1.828     www      14332: 	} else {
                   14333: # the file is outdated, get rid of it
                   14334: 	    unlink($file);
1.482     albertel 14335: 	}
1.828     www      14336:     }
                   14337: # one way or the other, at this point, we don't have the file
                   14338: # construct the correct path for the file
                   14339:     my @parts = ($cdom,$cnum); 
                   14340:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   14341: 	push @parts, split(/\//,$1);
                   14342:     }
                   14343:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   14344:     foreach my $part (@parts) {
                   14345: 	$path .= '/'.$part;
                   14346: 	if (!-e $path) {
                   14347: 	    mkdir($path,0770);
1.482     albertel 14348: 	}
                   14349:     }
1.828     www      14350: # now the path exists for sure
                   14351: # get a user agent
                   14352:     my $transferfile=$file.'.in.transfer';
                   14353: # FIXME: this should flock
                   14354:     if (-e $transferfile) { return 'ok'; }
                   14355:     my $request;
                   14356:     $uri=~s/^\///;
1.980     raeburn  14357:     my $homeserver = &homeserver($cnum,$cdom);
1.1398    raeburn  14358:     my $hostname = &hostname($homeserver);
1.980     raeburn  14359:     my $protocol = $protocol{$homeserver};
                   14360:     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  14361:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
1.1345    raeburn  14362:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828     www      14363: # did it work?
                   14364:     if ($response->is_error()) {
                   14365: 	unlink($transferfile);
                   14366: 	&logthis("Userfile repcopy failed for $uri");
                   14367: 	return -1;
                   14368:     }
                   14369: # worked, rename the transfer file
                   14370:     rename($transferfile,$file);
1.607     raeburn  14371:     return 'ok';
1.481     raeburn  14372: }
                   14373: 
1.517     albertel 14374: sub tokenwrapper {
                   14375:     my $uri=shift;
1.980     raeburn  14376:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 14377:     $uri=~s|^/||;
1.620     albertel 14378:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 14379:     my $token=$1;
1.552     albertel 14380:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   14381:     if ($udom && $uname && $file) {
                   14382: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  14383:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  14384:         my $homeserver = &homeserver($uname,$udom);
1.1397    raeburn  14385:         my $hostname = &hostname($homeserver);
1.980     raeburn  14386:         my $protocol = $protocol{$homeserver};
                   14387:         $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  14388:         return $protocol.'://'.$hostname.'/'.$uri.
1.517     albertel 14389:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   14390:                                '&tokenissued='.$perlvar{'lonHostID'};
                   14391:     } else {
                   14392:         return '/adm/notfound.html';
                   14393:     }
                   14394: }
                   14395: 
1.828     www      14396: # call with reqtype HEAD: get last modification time
                   14397: # call with reqtype GET: get the file contents
                   14398: # Do not call this with reqtype GET for large files! It loads everything into memory
                   14399: #
1.481     raeburn  14400: sub getuploaded {
                   14401:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   14402:     $uri=~s/^\///;
1.980     raeburn  14403:     my $homeserver = &homeserver($cnum,$cdom);
1.1397    raeburn  14404:     my $hostname = &hostname($homeserver);
1.980     raeburn  14405:     my $protocol = $protocol{$homeserver};
                   14406:     $protocol = 'http' if ($protocol ne 'https');
1.1397    raeburn  14407:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
1.481     raeburn  14408:     my $request=new HTTP::Request($reqtype,$uri);
1.1345    raeburn  14409:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481     raeburn  14410:     $$rtncode = $response->code;
1.482     albertel 14411:     if (! $response->is_success()) {
                   14412: 	return 'failed';
                   14413:     }      
                   14414:     if ($reqtype eq 'HEAD') {
1.486     www      14415: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 14416:     } elsif ($reqtype eq 'GET') {
                   14417: 	$$info = $response->content;
1.472     albertel 14418:     }
1.482     albertel 14419:     return 'ok';
1.36      albertel 14420: }
                   14421: 
1.481     raeburn  14422: sub readfile {
                   14423:     my $file = shift;
                   14424:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   14425:     my $fh;
1.1359    raeburn  14426:     open($fh,"<",$file);
1.481     raeburn  14427:     my $a='';
1.800     albertel 14428:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  14429:     return $a;
                   14430: }
                   14431: 
1.36      albertel 14432: sub filelocation {
1.590     banghart 14433:     my ($dir,$file) = @_;
                   14434:     my $location;
                   14435:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 14436: 
                   14437:     if ($file =~ m-^/adm/-) {
                   14438: 	$file=~s-^/adm/wrapper/-/-;
                   14439: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   14440:     }
1.882     albertel 14441: 
1.1139    www      14442:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  14443:         $location = $file;
1.609     banghart 14444:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 14445:         my ($udom,$uname,$filename)=
1.811     albertel 14446:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 14447:         my $home=&homeserver($uname,$udom);
                   14448:         my $is_me=0;
                   14449:         my @ids=&current_machine_ids();
                   14450:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   14451:         if ($is_me) {
1.1117    foxr     14452:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 14453:         } else {
                   14454:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   14455:   	      $udom.'/'.$uname.'/'.$filename;
                   14456:         }
1.882     albertel 14457:     } elsif ($file =~ m-^/adm/-) {
                   14458: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 14459:     } else {
                   14460:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      14461:         $file=~s:^/(res|priv)/:/:;
                   14462:         my $space=$1;
1.590     banghart 14463:         if ( !( $file =~ m:^/:) ) {
                   14464:             $location = $dir. '/'.$file;
                   14465:         } else {
1.1142    raeburn  14466:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 14467:         }
1.59      albertel 14468:     }
1.590     banghart 14469:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 14470:     while ($location=~m{/\.\./}) {
                   14471: 	if ($location =~ m{/[^/]+/\.\./}) {
                   14472: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   14473: 	} else {
                   14474: 	    $location=~ s{/\.\./}{/}g;
                   14475: 	}
                   14476:     } #remove dir/..
1.590     banghart 14477:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   14478:     return $location;
1.46      www      14479: }
1.36      albertel 14480: 
1.46      www      14481: sub hreflocation {
                   14482:     my ($dir,$file)=@_;
1.980     raeburn  14483:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 14484: 	$file=filelocation($dir,$file);
1.700     albertel 14485:     } elsif ($file=~m-^/adm/-) {
                   14486: 	$file=~s-^/adm/wrapper/-/-;
                   14487: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 14488:     }
                   14489:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   14490: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   14491:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  14492: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   14493: 	        {/uploaded/$1/$2/}x;
1.46      www      14494:     }
1.913     albertel 14495:     if ($file=~ m{^/userfiles/}) {
                   14496: 	$file =~ s{^/userfiles/}{/uploaded/};
                   14497:     }
1.462     albertel 14498:     return $file;
1.465     albertel 14499: }
                   14500: 
1.1139    www      14501: 
                   14502: 
                   14503: 
                   14504: 
1.465     albertel 14505: sub current_machine_domains {
1.853     albertel 14506:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   14507: }
                   14508: 
                   14509: sub machine_domains {
                   14510:     my ($hostname) = @_;
1.465     albertel 14511:     my @domains;
1.838     albertel 14512:     my %hostname = &all_hostnames();
1.465     albertel 14513:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  14514: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 14515: 	if ($hostname eq $name) {
1.844     albertel 14516: 	    push(@domains,&host_domain($id));
1.465     albertel 14517: 	}
                   14518:     }
                   14519:     return @domains;
                   14520: }
                   14521: 
                   14522: sub current_machine_ids {
1.853     albertel 14523:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   14524: }
                   14525: 
                   14526: sub machine_ids {
                   14527:     my ($hostname) = @_;
                   14528:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 14529:     my @ids;
1.888     albertel 14530:     my %name_to_host = &all_names();
1.889     albertel 14531:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   14532: 	return @{ $name_to_host{$hostname} };
                   14533:     }
                   14534:     return;
1.31      www      14535: }
                   14536: 
1.824     raeburn  14537: sub additional_machine_domains {
                   14538:     my @domains;
1.1466    raeburn  14539:     if (-e "$perlvar{'lonTabDir'}/expected_domains.tab") {
                   14540:         if (open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab")) {
                   14541:             while (my $line = <$fh>) {
                   14542:                 chomp($line);           
                   14543:                 $line =~ s/\s//g;
                   14544:                 push(@domains,$line);
                   14545:             }
                   14546:             close($fh);
                   14547:         }
1.824     raeburn  14548:     }
                   14549:     return @domains;
                   14550: }
                   14551: 
                   14552: sub default_login_domain {
                   14553:     my $domain = $perlvar{'lonDefDomain'};
                   14554:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   14555:     foreach my $posdom (&current_machine_domains(),
                   14556:                         &additional_machine_domains()) {
                   14557:         if (lc($posdom) eq lc($testdomain)) {
                   14558:             $domain=$posdom;
                   14559:             last;
                   14560:         }
                   14561:     }
                   14562:     return $domain;
                   14563: }
                   14564: 
1.1414    raeburn  14565: sub shared_institution {
1.1439    raeburn  14566:     my ($dom,$lonhost) = @_;
                   14567:     if ($lonhost eq '') {
                   14568:         $lonhost = $perlvar{'lonHostID'};
                   14569:     }
1.1414    raeburn  14570:     my $same_intdom;
1.1439    raeburn  14571:     my $hostintdom = &internet_dom($lonhost);
1.1414    raeburn  14572:     if ($hostintdom ne '') {
                   14573:         my %iphost = &get_iphost();
                   14574:         my $primary_id = &domain($dom,'primary');
                   14575:         my $primary_ip = &get_host_ip($primary_id);
                   14576:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
                   14577:             foreach my $id (@{$iphost{$primary_ip}}) {
                   14578:                 my $intdom = &internet_dom($id);
                   14579:                 if ($intdom eq $hostintdom) {
                   14580:                     $same_intdom = 1;
                   14581:                     last;
                   14582:                 }
                   14583:             }
                   14584:         }
                   14585:     }
                   14586:     return $same_intdom;
                   14587: }
                   14588: 
1.1398    raeburn  14589: sub uses_sts {
                   14590:     my ($ignore_cache) = @_;
                   14591:     my $lonhost = $perlvar{'lonHostID'};
                   14592:     my $hostname = &hostname($lonhost);
                   14593:     my $sts_on;
                   14594:     if ($protocol{$lonhost} eq 'https') {
                   14595:         my $cachetime = 12*3600;
                   14596:         if (!$ignore_cache) {
                   14597:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
                   14598:             if (defined($cached)) {
                   14599:                 return $sts_on;
                   14600:             }
                   14601:         }
                   14602:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
                   14603:         my $request=new HTTP::Request('HEAD',$url);
                   14604:         my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,'','','',1);
                   14605:         if ($response->is_success) {
                   14606:             my $has_sts = $response->header('Strict-Transport-Security');
                   14607:             if ($has_sts eq '') {
                   14608:                 $sts_on = 0;
                   14609:             } else {
                   14610:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
                   14611:                     my $maxage = $1;
                   14612:                     if ($maxage) {
                   14613:                         $sts_on = 1;
                   14614:                     } else {
                   14615:                         $sts_on = 0;
                   14616:                     }
                   14617:                 } else {
                   14618:                     $sts_on = 0;
                   14619:                 }
                   14620:             }
                   14621:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
                   14622:         }
                   14623:     }
                   14624:     return;
                   14625: }
                   14626: 
1.1449    raeburn  14627: sub waf_allssl {
                   14628:     my ($host_name) = @_;
                   14629:     my $alias = &get_proxy_alias();
                   14630:     if ($host_name eq '') {
                   14631:         $host_name = $ENV{'SERVER_NAME'};
                   14632:     }
                   14633:     if (($host_name ne '') && ($alias eq $host_name)) {
                   14634:         my $serverhomedom = &host_domain($perlvar{'lonHostID'});
                   14635:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   14636:         if ($defdomdefaults{'waf_sslopt'}) {
                   14637:             return $defdomdefaults{'waf_sslopt'};
                   14638:         }
                   14639:     }
                   14640:     return;
                   14641: }
                   14642: 
1.1434    raeburn  14643: sub get_requestor_ip {
                   14644:     my ($r,$nolookup,$noproxy) = @_;
                   14645:     my $from_ip;
                   14646:     if (ref($r)) {
1.1447    raeburn  14647:         if ($r->can('useragent_ip')) {
                   14648:             if ($noproxy && $r->can('client_ip')) {
                   14649:                 $from_ip = $r->client_ip();
                   14650:             } else {
                   14651:                 $from_ip = $r->useragent_ip();
                   14652:             }
                   14653:         } elsif ($r->connection->can('remote_ip')) {
                   14654:             $from_ip = $r->connection->remote_ip();
                   14655:         } else {
                   14656:             $from_ip = $r->get_remote_host($nolookup);
                   14657:         }
1.1434    raeburn  14658:     } else {
                   14659:         $from_ip = $ENV{'REMOTE_ADDR'};
                   14660:     }
                   14661:     return $from_ip if ($noproxy); 
                   14662:     # Who controls proxy settings for server
                   14663:     my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14664:     my $proxyinfo = &get_proxy_settings($dom_in_use);
                   14665:     if ((ref($proxyinfo) eq 'HASH') && ($from_ip)) {
1.1437    raeburn  14666:         if ($proxyinfo->{'vpnint'}) {
                   14667:             if (&ip_match($from_ip,$proxyinfo->{'vpnint'})) {
1.1434    raeburn  14668:                 return $from_ip;
                   14669:             }
                   14670:         }
                   14671:         if ($proxyinfo->{'trusted'}) {
                   14672:             if (&ip_match($from_ip,$proxyinfo->{'trusted'})) {
                   14673:                 my $ipheader = $proxyinfo->{'ipheader'};
                   14674:                 my ($ip,$xfor);
                   14675:                 if (ref($r)) {
                   14676:                     if ($ipheader) {
                   14677:                         $ip = $r->headers_in->{$ipheader};
                   14678:                     }
                   14679:                     $xfor = $r->headers_in->{'X-Forwarded-For'};
                   14680:                 } else {
                   14681:                     if ($ipheader) {
                   14682:                         $ip = $ENV{'HTTP_'.uc($ipheader)};
                   14683:                     }
                   14684:                     $xfor = $ENV{'HTTP_X_FORWARDED_FOR'};
                   14685:                 }
                   14686:                 if (($ip eq '') && ($xfor ne '')) {
                   14687:                     foreach my $poss_ip (reverse(split(/\s*,\s*/,$xfor))) {
                   14688:                         unless (&ip_match($poss_ip,$proxyinfo->{'trusted'})) {
                   14689:                             $ip = $poss_ip;
1.1435    raeburn  14690:                             last;
1.1434    raeburn  14691:                         }
                   14692:                     }
                   14693:                 }
                   14694:                 if ($ip ne '') {
                   14695:                     return $ip;
                   14696:                 }
                   14697:             }
                   14698:         }
                   14699:     }
                   14700:     return $from_ip;
                   14701: }
                   14702: 
                   14703: sub get_proxy_settings {
                   14704:     my ($dom_in_use) = @_;
                   14705:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   14706:     my $proxyinfo = {
                   14707:                        ipheader => $domdefaults{'waf_ipheader'},
                   14708:                        trusted  => $domdefaults{'waf_trusted'},
1.1437    raeburn  14709:                        vpnint   => $domdefaults{'waf_vpnint'},
1.1438    raeburn  14710:                        vpnext   => $domdefaults{'waf_vpnext'},
1.1449    raeburn  14711:                        sslopt   => $domdefaults{'waf_sslopt'},
1.1434    raeburn  14712:                     };
                   14713:     return $proxyinfo;
                   14714: }
                   14715: 
                   14716: sub ip_match {
                   14717:     my ($ip,$pattern_str) = @_;
                   14718:     $ip=Net::CIDR::cidrvalidate($ip);
                   14719:     if ($ip) {
                   14720:         return Net::CIDR::cidrlookup($ip,split(/\s*,\s*/,$pattern_str));
                   14721:     }
                   14722:     return;
                   14723: }
                   14724: 
                   14725: sub get_proxy_alias {
1.1450    raeburn  14726:     my ($lonid) = @_;
                   14727:     if ($lonid eq '') {
                   14728:         $lonid = $perlvar{'lonHostID'};
                   14729:     }
                   14730:     if (!defined(&hostname($lonid))) {
                   14731:         return;
                   14732:     }
                   14733:     if ($lonid ne '') {
                   14734:         my ($alias,$cached) = &is_cached_new('proxyalias',$lonid);
1.1434    raeburn  14735:         if ($cached) {
                   14736:             return $alias;
                   14737:         }
1.1450    raeburn  14738:         my $dom = &Apache::lonnet::host_domain($lonid);
1.1434    raeburn  14739:         if ($dom ne '') {
                   14740:             my $cachetime = 60*60*24;
                   14741:             my %domconfig =
1.1437    raeburn  14742:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14743:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14744:                 if (ref($domconfig{'wafproxy'}{'alias'}) eq 'HASH') {
1.1450    raeburn  14745:                     $alias = $domconfig{'wafproxy'}{'alias'}{$lonid};
                   14746:                 }
                   14747:             }
                   14748:             return &do_cache_new('proxyalias',$lonid,$alias,$cachetime);
                   14749:         }
                   14750:     }
                   14751:     return;
                   14752: }
                   14753: 
                   14754: sub use_proxy_alias {
                   14755:     my ($r,$lonid) = @_;
                   14756:     my $alias = &get_proxy_alias($lonid);
                   14757:     if ($alias) {
                   14758:         my $dom = &host_domain($lonid);
                   14759:         if ($dom ne '') {
1.1467    raeburn  14760:             my $proxyinfo = &get_proxy_settings($dom);
1.1450    raeburn  14761:             my ($vpnint,$remote_ip);
                   14762:             if (ref($proxyinfo) eq 'HASH') {
                   14763:                 $vpnint = $proxyinfo->{'vpnint'};
                   14764:                 if ($vpnint) {
                   14765:                     $remote_ip = &get_requestor_ip($r,1,1);
1.1434    raeburn  14766:                 }
                   14767:             }
1.1450    raeburn  14768:             unless ($vpnint && &ip_match($remote_ip,$vpnint)) {
                   14769:                 return $alias;
                   14770:             }
1.1434    raeburn  14771:         }
                   14772:     }
                   14773:     return;
                   14774: }
                   14775: 
1.1474    raeburn  14776: sub alias_sso {
1.1467    raeburn  14777:     my ($lonid) = @_;
                   14778:     if ($lonid eq '') {
                   14779:         $lonid = $perlvar{'lonHostID'};
                   14780:     }
                   14781:     if (!defined(&hostname($lonid))) {
                   14782:         return;
                   14783:     }
                   14784:     if ($lonid ne '') {
                   14785:         my ($use_alias,$cached) = &is_cached_new('proxysaml',$lonid);
                   14786:         if ($cached) {
                   14787:             return $use_alias;
                   14788:         }
                   14789:         my $dom = &Apache::lonnet::host_domain($lonid);
                   14790:         if ($dom ne '') {
                   14791:             my $cachetime = 60*60*24;
                   14792:             my %domconfig =
                   14793:                 &Apache::lonnet::get_dom('configuration',['wafproxy'],$dom);
                   14794:             if (ref($domconfig{'wafproxy'}) eq 'HASH') {
                   14795:                 if (ref($domconfig{'wafproxy'}{'saml'}) eq 'HASH') {
                   14796:                     $use_alias = $domconfig{'wafproxy'}{'saml'}{$lonid};
                   14797:                 }
                   14798:             }
                   14799:             return &do_cache_new('proxysaml',$lonid,$use_alias,$cachetime);
                   14800:         }
                   14801:     }
                   14802:     return;
                   14803: }
                   14804: 
1.1465    raeburn  14805: sub get_saml_landing {
                   14806:     my ($lonid) = @_;
                   14807:     if ($lonid eq '') {
                   14808:         my $defdom = &default_login_domain();
                   14809:         my @hosts = &current_machine_ids();
                   14810:         if (@hosts > 1) {
                   14811:             foreach my $hostid (@hosts) {
                   14812:                 if (&host_domain($hostid) eq $defdom) {
                   14813:                     $lonid = $hostid;
                   14814:                     last;
                   14815:                 }
                   14816:             }
                   14817:         } else {
                   14818:             $lonid = $perlvar{'lonHostID'};
                   14819:         }
                   14820:         if ($lonid) {
                   14821:             unless (&Apache::lonnet::host_domain($lonid) eq $defdom) {
                   14822:                 return;
                   14823:             }
                   14824:         } else {
                   14825:             return;
                   14826:         }
                   14827:     } elsif (!defined(&hostname($lonid))) {
                   14828:         return;
                   14829:     }
                   14830:     my ($landing,$cached) = &is_cached_new('samllanding',$lonid);
                   14831:     if ($cached) {
                   14832:         return $landing;
                   14833:     }
                   14834:     my $dom = &Apache::lonnet::host_domain($lonid);
                   14835:     if ($dom ne '') {
                   14836:         my $cachetime = 60*60*24;
                   14837:         my %domconfig =
                   14838:             &Apache::lonnet::get_dom('configuration',['login'],$dom);
                   14839:         if (ref($domconfig{'login'}) eq 'HASH') {
                   14840:             if (ref($domconfig{'login'}{'saml'}) eq 'HASH') {
                   14841:                 if (ref($domconfig{'login'}{'saml'}{$lonid}) eq 'HASH') {
                   14842:                     $landing = 1;
                   14843:                 }
                   14844:             }
                   14845:         }
                   14846:         return &do_cache_new('samllanding',$lonid,$landing,$cachetime);
                   14847:     }
                   14848:     return;
                   14849: }
                   14850: 
1.31      www      14851: # ------------------------------------------------------------- Declutters URLs
                   14852: 
                   14853: sub declutter {
                   14854:     my $thisfn=shift;
1.569     albertel 14855:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  14856:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   14857:         $thisfn=~s{^/home/httpd/html}{};
                   14858:     }
1.31      www      14859:     $thisfn=~s/^\///;
1.697     albertel 14860:     $thisfn=~s|^adm/wrapper/||;
                   14861:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      14862:     $thisfn=~s/^res\///;
1.1172    bisitz   14863:     $thisfn=~s/^priv\///;
1.1032    raeburn  14864:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   14865:         $thisfn=~s/\?.+$//;
                   14866:     }
1.268     www      14867:     return $thisfn;
                   14868: }
                   14869: 
                   14870: # ------------------------------------------------------------- Clutter up URLs
                   14871: 
                   14872: sub clutter {
                   14873:     my $thisfn='/'.&declutter(shift);
1.887     albertel 14874:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 14875: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      14876:        $thisfn='/res'.$thisfn; 
                   14877:     }
1.1031    raeburn  14878:     if ($thisfn !~m|^/adm|) {
                   14879: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 14880: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 14881: 	} else {
                   14882: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   14883: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 14884: 	    if ($embstyle eq 'ssi'
                   14885: 		|| ($embstyle eq 'hdn')
                   14886: 		|| ($embstyle eq 'rat')
                   14887: 		|| ($embstyle eq 'prv')
                   14888: 		|| ($embstyle eq 'ign')) {
                   14889: 		#do nothing with these
                   14890: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 14891: 		|| ($embstyle eq 'emb')
                   14892: 		|| ($embstyle eq 'wrp')) {
                   14893: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 14894: 	    } elsif ($embstyle eq 'unk'
                   14895: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 14896: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 14897: 	    } else {
1.718     www      14898: #		&logthis("Got a blank emb style");
1.695     albertel 14899: 	    }
1.694     albertel 14900: 	}
1.1343    raeburn  14901:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298    raeburn  14902:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 14903:     }
1.31      www      14904:     return $thisfn;
1.12      www      14905: }
                   14906: 
1.787     albertel 14907: sub clutter_with_no_wrapper {
                   14908:     my $uri = &clutter(shift);
                   14909:     if ($uri =~ m-^/adm/-) {
                   14910: 	$uri =~ s-^/adm/wrapper/-/-;
                   14911: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   14912:     }
                   14913:     return $uri;
                   14914: }
                   14915: 
1.557     albertel 14916: sub freeze_escape {
                   14917:     my ($value)=@_;
                   14918:     if (ref($value)) {
                   14919: 	$value=&nfreeze($value);
                   14920: 	return '__FROZEN__'.&escape($value);
                   14921:     }
                   14922:     return &escape($value);
                   14923: }
                   14924: 
1.11      www      14925: 
1.557     albertel 14926: sub thaw_unescape {
                   14927:     my ($value)=@_;
                   14928:     if ($value =~ /^__FROZEN__/) {
                   14929: 	substr($value,0,10,undef);
                   14930: 	$value=&unescape($value);
                   14931: 	return &thaw($value);
                   14932:     }
                   14933:     return &unescape($value);
                   14934: }
                   14935: 
1.436     albertel 14936: sub correct_line_ends {
                   14937:     my ($result)=@_;
                   14938:     $$result =~s/\r\n/\n/mg;
                   14939:     $$result =~s/\r/\n/mg;
1.415     albertel 14940: }
1.1       albertel 14941: # ================================================================ Main Program
                   14942: 
1.184     www      14943: sub goodbye {
1.204     albertel 14944:    &logthis("Starting Shut down");
1.443     albertel 14945: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 14946:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 14947: #converted
1.599     albertel 14948: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 14949:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   14950: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   14951: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 14952: #1.1 only
1.870     albertel 14953: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   14954: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   14955: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   14956: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   14957:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 14958:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   14959:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      14960:    &flushcourselogs();
                   14961:    &logthis("Shutting down");
                   14962: }
                   14963: 
1.852     albertel 14964: sub get_dns {
1.1210    raeburn  14965:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 14966:     if (!$ignore_cache) {
                   14967: 	my ($content,$cached)=
                   14968: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   14969: 	if ($cached) {
1.1210    raeburn  14970: 	    &$func($content,$hashref);
1.869     albertel 14971: 	    return;
                   14972: 	}
                   14973:     }
                   14974: 
                   14975:     my %alldns;
1.1379    raeburn  14976:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
                   14977:         foreach my $dns (<$config>) {
                   14978: 	    next if ($dns !~ /^\^(\S*)/x);
                   14979:             my $line = $1;
                   14980:             my ($host,$protocol) = split(/:/,$line);
                   14981:             if ($protocol ne 'https') {
                   14982:                 $protocol = 'http';
                   14983:             }
                   14984: 	    $alldns{$host} = $protocol;
1.979     raeburn  14985:         }
1.1379    raeburn  14986:         close($config);
1.869     albertel 14987:     }
                   14988:     while (%alldns) {
1.1263    raeburn  14989: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.1456    raeburn  14990:         my ($contents,@content);
                   14991:         if ($dns eq Sys::Hostname::FQDN::fqdn()) {
                   14992:             my $command = (split('/',$url))[3];
                   14993:             my ($dir,$file) = &parse_getdns_url($command,$url);
                   14994:             delete($alldns{$dns});
                   14995:             next if (($dir eq '') || ($file eq ''));
                   14996:             if (open(my $config,'<',"$dir/$file")) {
1.1457    raeburn  14997:                 @content = <$config>;
1.1456    raeburn  14998:                 close($config);
                   14999:             }
                   15000:             if ($url eq '/adm/dns/loncapaCRL') {
                   15001:                 $contents = join('',@content);
                   15002:             }
                   15003:         } else {
                   15004: 	    my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
                   15005:             my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
                   15006:             delete($alldns{$dns});
                   15007: 	    next if ($response->is_error());
                   15008:             if ($url eq '/adm/dns/loncapaCRL') {
                   15009:                 $contents = $response->content;
                   15010:             } else {
                   15011:                 @content = split("\n",$response->content);
                   15012:             }
                   15013:         }
1.1379    raeburn  15014:         if ($url eq '/adm/dns/loncapaCRL') {
1.1456    raeburn  15015:             return &$func($contents);
1.1379    raeburn  15016:         } else {
                   15017: 	    unless ($nocache) {
                   15018: 	        &do_cache_new('dns',$url,\@content,30*24*60*60);
                   15019: 	    }
                   15020: 	    &$func(\@content,$hashref);
                   15021:             return;
                   15022:         }
                   15023:     }
                   15024:     my $which = (split('/',$url,4))[3];
                   15025:     if ($which eq 'loncapaCRL') {
                   15026:         my $diskfile = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
                   15027:         if (-e $diskfile) {
                   15028:             &logthis("unable to contact DNS, on disk file $diskfile not updated");
                   15029:         } else {
                   15030:             &logthis("unable to contact DNS, no on disk file $diskfile available");
                   15031:         }
                   15032:     } else {
                   15033:         &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   15034:         if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
                   15035:             my @content = <$config>;
                   15036:             close($config);
                   15037:             &$func(\@content,$hashref);
                   15038:         }
1.852     albertel 15039:     }
1.1210    raeburn  15040:     return;
                   15041: }
                   15042: 
                   15043: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  15044: sub parse_dns_checksums_tab {
1.1210    raeburn  15045:     my ($lines,$hashref) = @_;
1.1264    raeburn  15046:     my $lonhost = $perlvar{'lonHostID'};
                   15047:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  15048:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  15049:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   15050:     my $webconfdir = '/etc/httpd/conf';
                   15051:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   15052:         $webconfdir = '/etc/apache2';
                   15053:     } elsif ($distro =~ /^sles(\d+)$/) {
                   15054:         if ($1 >= 10) {
                   15055:             $webconfdir = '/etc/apache2';
                   15056:         }
                   15057:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   15058:         if ($1 >= 10.0) {
                   15059:             $webconfdir = '/etc/apache2';
                   15060:         }
                   15061:     }
1.1210    raeburn  15062:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   15063:     my (%chksum,%revnum);
                   15064:     if (ref($lines) eq 'ARRAY') {
                   15065:         chomp(@{$lines});
1.1238    raeburn  15066:         my $version = shift(@{$lines});
                   15067:         if ($version eq $release) {  
1.1210    raeburn  15068:             foreach my $line (@{$lines}) {
1.1238    raeburn  15069:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  15070:                 if ($file =~ m{^/etc/httpd/conf}) {
                   15071:                     if ($webconfdir eq '/etc/apache2') {
                   15072:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   15073:                     }
                   15074:                 }
1.1238    raeburn  15075:                 $chksum{$file} = $shasum;
                   15076:                 $revnum{$file} = $version;
1.1210    raeburn  15077:             }
                   15078:             if (ref($hashref) eq 'HASH') {
                   15079:                 %{$hashref} = (
                   15080:                                 sums     => \%chksum,
                   15081:                                 versions => \%revnum,
                   15082:                               );
                   15083:             }
                   15084:         }
                   15085:     }
1.869     albertel 15086:     return;
1.852     albertel 15087: }
1.1210    raeburn  15088: 
                   15089: sub fetch_dns_checksums {
1.1238    raeburn  15090:     my %checksums;
                   15091:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  15092:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  15093:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   15094:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  15095:              \%checksums);
1.1210    raeburn  15096:     return \%checksums;
                   15097: }
                   15098: 
1.1379    raeburn  15099: sub fetch_crl_pemfile {
                   15100:     return &get_dns("/adm/dns/loncapaCRL",\&save_crl_pem,1,1);
                   15101: }
                   15102: 
                   15103: sub save_crl_pem {
1.1456    raeburn  15104:     my ($content) = @_;
1.1380    raeburn  15105:     my ($msg,$hadchanges);
1.1456    raeburn  15106:     if ($content ne '') {
1.1379    raeburn  15107:         my $now = time;
                   15108:         my $lonca = $perlvar{'lonCertificateDirectory'}.'/'.$perlvar{'lonnetCertificateAuthority'};
                   15109:         my $tmpcrl = $tmpdir.'/'.$perlvar{'lonnetCertRevocationList'}.'_'.$now.'.'.$$.'.tmp';
                   15110:         if (open(my $fh,'>',"$tmpcrl")) {
1.1456    raeburn  15111:             print $fh $content;
1.1379    raeburn  15112:             close($fh);
                   15113:             if (-e $lonca) {
                   15114:                 if (open(PIPE,"openssl crl -in $tmpcrl -inform pem -CAfile $lonca -noout 2>&1 |")) {
                   15115:                     my $check = <PIPE>;
                   15116:                     close(PIPE);
                   15117:                     chomp($check);
                   15118:                     if ($check eq 'verify OK') {
                   15119:                         my $dest = "$perlvar{'lonCertificateDirectory'}/$perlvar{'lonnetCertRevocationList'}";
1.1380    raeburn  15120:                         my $backup;
1.1379    raeburn  15121:                         if (-e $dest) {
1.1380    raeburn  15122:                             if (&File::Copy::move($dest,"$dest.bak")) {
                   15123:                                 $backup = 'ok';
                   15124:                             }
1.1379    raeburn  15125:                         }
                   15126:                         if (&File::Copy::move($tmpcrl,$dest)) {
                   15127:                             $msg = 'ok';
1.1380    raeburn  15128:                             if ($backup) {
                   15129:                                 my (%oldnums,%newnums);
                   15130:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest.bak |grep 'Serial Number' |")) {
                   15131:                                     while (<PIPE>) {
                   15132:                                         $oldnums{(split(/:/))[1]} = 1;
                   15133:                                     }
                   15134:                                     close(PIPE);
                   15135:                                 }
                   15136:                                 if (open(PIPE, "openssl crl -inform PEM -text -noout -in $dest |grep 'Serial Number' |")) {
                   15137:                                     while(<PIPE>) {
                   15138:                                         $newnums{(split(/:/))[1]} = 1;
                   15139:                                     }
                   15140:                                     close(PIPE);
                   15141:                                 }
                   15142:                                 foreach my $key (sort {$b <=> $a } (keys(%newnums))) {
                   15143:                                     unless (exists($oldnums{$key})) {
                   15144:                                         $hadchanges = 1;
                   15145:                                         last;
                   15146:                                     }
                   15147:                                 }
                   15148:                                 unless ($hadchanges) {
                   15149:                                     foreach my $key (sort {$b <=> $a } (keys(%oldnums))) {
                   15150:                                         unless (exists($newnums{$key})) {
                   15151:                                             $hadchanges = 1;
                   15152:                                             last;
                   15153:                                         }
                   15154:                                     }
                   15155:                                 }
                   15156:                             }
1.1379    raeburn  15157:                         }
                   15158:                     } else {
                   15159:                         unlink($tmpcrl);
                   15160:                     }
                   15161:                 } else {
                   15162:                     unlink($tmpcrl);
                   15163:                 }
                   15164:             } else {
                   15165:                 unlink($tmpcrl);
                   15166:             }
                   15167:         }
                   15168:     }
1.1380    raeburn  15169:     return ($msg,$hadchanges);
1.1379    raeburn  15170: }
                   15171: 
1.1456    raeburn  15172: sub parse_getdns_url {
                   15173:     my ($command,$url) = @_;
                   15174:     my $dir = $perlvar{'lonTabDir'};
                   15175:     my $file;
                   15176:     if ($command eq 'hosts') {
                   15177:         $file = 'dns_hosts.tab';
                   15178:     } elsif ($command eq 'domain') {
                   15179:         $file = 'dns_domain.tab';
                   15180:     } elsif ($command eq 'checksums') {
                   15181:         my $version = (split('/',$url))[4];
                   15182:         $file = "dns_checksums/$version.tab",
                   15183:     } elsif ($command eq 'loncapaCRL') {
                   15184:         $dir = $perlvar{'lonCertificateDirectory'};
                   15185:         $file = $perlvar{'lonnetCertRevocationList'};
                   15186:     }
                   15187:     return ($dir,$file);
                   15188: }
                   15189: 
1.327     albertel 15190: # ------------------------------------------------------------ Read domain file
                   15191: {
1.852     albertel 15192:     my $loaded;
1.846     albertel 15193:     my %domain;
                   15194: 
1.852     albertel 15195:     sub parse_domain_tab {
                   15196: 	my ($lines) = @_;
                   15197: 	foreach my $line (@$lines) {
                   15198: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      15199: 
1.846     albertel 15200: 	    chomp($line);
1.852     albertel 15201: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 15202: 	    my %this_domain;
                   15203: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   15204: 			       'lang_def', 'city', 'longi', 'lati',
                   15205: 			       'primary') {
                   15206: 		$this_domain{$field} = shift(@elements);
                   15207: 	    }
                   15208: 	    $domain{$name} = \%this_domain;
1.852     albertel 15209: 	}
                   15210:     }
1.864     albertel 15211: 
                   15212:     sub reset_domain_info {
                   15213: 	undef($loaded);
                   15214: 	undef(%domain);
                   15215:     }
                   15216: 
1.852     albertel 15217:     sub load_domain_tab {
1.1293    raeburn  15218: 	my ($ignore_cache,$nocache) = @_;
                   15219: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 15220: 	my $fh;
1.1359    raeburn  15221: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 15222: 	    my @lines = <$fh>;
                   15223: 	    &parse_domain_tab(\@lines);
1.448     albertel 15224: 	}
1.852     albertel 15225: 	close($fh);
                   15226: 	$loaded = 1;
1.327     albertel 15227:     }
1.846     albertel 15228: 
                   15229:     sub domain {
1.852     albertel 15230: 	&load_domain_tab() if (!$loaded);
                   15231: 
1.846     albertel 15232: 	my ($name,$what) = @_;
                   15233: 	return if ( !exists($domain{$name}) );
                   15234: 
                   15235: 	if (!$what) {
                   15236: 	    return $domain{$name}{'description'};
                   15237: 	}
                   15238: 	return $domain{$name}{$what};
                   15239:     }
1.974     raeburn  15240: 
                   15241:     sub domain_info {
                   15242:         &load_domain_tab() if (!$loaded);
                   15243:         return %domain;
                   15244:     }
                   15245: 
1.327     albertel 15246: }
                   15247: 
                   15248: 
1.1       albertel 15249: # ------------------------------------------------------------- Read hosts file
                   15250: {
1.838     albertel 15251:     my %hostname;
1.844     albertel 15252:     my %hostdom;
1.845     albertel 15253:     my %libserv;
1.852     albertel 15254:     my $loaded;
1.888     albertel 15255:     my %name_to_host;
1.1074    raeburn  15256:     my %internetdom;
1.1107    raeburn  15257:     my %LC_dns_serv;
1.852     albertel 15258: 
                   15259:     sub parse_hosts_tab {
                   15260: 	my ($file) = @_;
                   15261: 	foreach my $configline (@$file) {
                   15262: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  15263:             chomp($configline);
                   15264: 	    if ($configline =~ /^\^/) {
                   15265:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   15266:                     $LC_dns_serv{$1} = 1;
                   15267:                 }
                   15268:                 next;
                   15269:             }
1.1074    raeburn  15270: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 15271: 	    $name=~s/\s//g;
                   15272: 	    if ($id && $domain && $role && $name) {
1.1351    raeburn  15273:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   15274:                     my $curr = $hostname{$id};
                   15275:                     my $skip;
                   15276:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   15277:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   15278:                             $skip = 1;
                   15279:                         } else {
                   15280:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   15281:                         }
                   15282:                     }
                   15283:                     unless ($skip) {
                   15284:                         push(@{$name_to_host{$name}},$id);
                   15285:                     }
                   15286:                 } else {
                   15287:                     push(@{$name_to_host{$name}},$id);
                   15288:                 }
1.852     albertel 15289: 		$hostname{$id}=$name;
                   15290: 		$hostdom{$id}=$domain;
                   15291: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  15292:                 if (defined($protocol)) {
                   15293:                     if ($protocol eq 'https') {
                   15294:                         $protocol{$id} = $protocol;
                   15295:                     } else {
                   15296:                         $protocol{$id} = 'http'; 
                   15297:                     }
1.968     raeburn  15298:                 } else {
1.969     raeburn  15299:                     $protocol{$id} = 'http';
1.968     raeburn  15300:                 }
1.1074    raeburn  15301:                 if (defined($intdom)) {
                   15302:                     $internetdom{$id} = $intdom;
                   15303:                 }
1.852     albertel 15304: 	    }
                   15305: 	}
                   15306:     }
1.864     albertel 15307:     
                   15308:     sub reset_hosts_info {
1.897     albertel 15309: 	&purge_remembered();
1.864     albertel 15310: 	&reset_domain_info();
                   15311: 	&reset_hosts_ip_info();
1.1339    raeburn  15312:         undef(%internetdom);
1.892     albertel 15313: 	undef(%name_to_host);
1.864     albertel 15314: 	undef(%hostname);
                   15315: 	undef(%hostdom);
                   15316: 	undef(%libserv);
                   15317: 	undef($loaded);
                   15318:     }
1.1       albertel 15319: 
1.852     albertel 15320:     sub load_hosts_tab {
1.1293    raeburn  15321: 	my ($ignore_cache,$nocache) = @_;
                   15322: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359    raeburn  15323: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 15324: 	my @config = <$config>;
                   15325: 	&parse_hosts_tab(\@config);
                   15326: 	close($config);
                   15327: 	$loaded=1;
1.1       albertel 15328:     }
1.852     albertel 15329: 
1.838     albertel 15330:     sub hostname {
1.852     albertel 15331: 	&load_hosts_tab() if (!$loaded);
                   15332: 
1.838     albertel 15333: 	my ($lonid) = @_;
                   15334: 	return $hostname{$lonid};
                   15335:     }
1.845     albertel 15336: 
1.838     albertel 15337:     sub all_hostnames {
1.852     albertel 15338: 	&load_hosts_tab() if (!$loaded);
                   15339: 
1.838     albertel 15340: 	return %hostname;
                   15341:     }
1.845     albertel 15342: 
1.888     albertel 15343:     sub all_names {
1.1293    raeburn  15344:         my ($ignore_cache,$nocache) = @_;
                   15345: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 15346: 
                   15347: 	return %name_to_host;
                   15348:     }
                   15349: 
1.974     raeburn  15350:     sub all_host_domain {
                   15351:         &load_hosts_tab() if (!$loaded);
                   15352:         return %hostdom;
                   15353:     }
                   15354: 
1.1339    raeburn  15355:     sub all_host_intdom {
                   15356:         &load_hosts_tab() if (!$loaded);
                   15357:         return %internetdom;
                   15358:     }
                   15359: 
1.845     albertel 15360:     sub is_library {
1.852     albertel 15361: 	&load_hosts_tab() if (!$loaded);
                   15362: 
1.845     albertel 15363: 	return exists($libserv{$_[0]});
                   15364:     }
                   15365: 
                   15366:     sub all_library {
1.852     albertel 15367: 	&load_hosts_tab() if (!$loaded);
                   15368: 
1.845     albertel 15369: 	return %libserv;
                   15370:     }
                   15371: 
1.1062    droeschl 15372:     sub unique_library {
                   15373: 	#2x reverse removes all hostnames that appear more than once
                   15374:         my %unique = reverse &all_library();
                   15375:         return reverse %unique;
                   15376:     }
                   15377: 
1.841     albertel 15378:     sub get_servers {
1.852     albertel 15379: 	&load_hosts_tab() if (!$loaded);
                   15380: 
1.841     albertel 15381: 	my ($domain,$type) = @_;
                   15382: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   15383: 	                                          : %hostname;
                   15384: 	my %result;
1.842     albertel 15385: 	if (ref($domain) eq 'ARRAY') {
                   15386: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 15387: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 15388: 		    $result{$host} = $hostname;
                   15389: 		}
                   15390: 	    }
                   15391: 	} else {
                   15392: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   15393: 		if ($hostdom{$host} eq $domain) {
                   15394: 		    $result{$host} = $hostname;
                   15395: 		}
1.841     albertel 15396: 	    }
                   15397: 	}
                   15398: 	return %result;
                   15399:     }
1.845     albertel 15400: 
1.1062    droeschl 15401:     sub get_unique_servers {
                   15402:         my %unique = reverse &get_servers(@_);
                   15403: 	return reverse %unique;
                   15404:     }
                   15405: 
1.844     albertel 15406:     sub host_domain {
1.852     albertel 15407: 	&load_hosts_tab() if (!$loaded);
                   15408: 
1.844     albertel 15409: 	my ($lonid) = @_;
                   15410: 	return $hostdom{$lonid};
                   15411:     }
                   15412: 
1.841     albertel 15413:     sub all_domains {
1.852     albertel 15414: 	&load_hosts_tab() if (!$loaded);
                   15415: 
1.841     albertel 15416: 	my %seen;
                   15417: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   15418: 	return @uniq;
                   15419:     }
1.1074    raeburn  15420: 
                   15421:     sub internet_dom {
                   15422:         &load_hosts_tab() if (!$loaded);
                   15423: 
                   15424:         my ($lonid) = @_;
                   15425:         return $internetdom{$lonid};
                   15426:     }
1.1107    raeburn  15427: 
                   15428:     sub is_LC_dns {
                   15429:         &load_hosts_tab() if (!$loaded);
                   15430: 
                   15431:         my ($hostname) = @_;
                   15432:         return exists($LC_dns_serv{$hostname});
                   15433:     }
                   15434: 
1.1       albertel 15435: }
                   15436: 
1.847     albertel 15437: { 
                   15438:     my %iphost;
1.856     albertel 15439:     my %name_to_ip;
                   15440:     my %lonid_to_ip;
1.869     albertel 15441: 
1.847     albertel 15442:     sub get_hosts_from_ip {
                   15443: 	my ($ip) = @_;
                   15444: 	my %iphosts = &get_iphost();
                   15445: 	if (ref($iphosts{$ip})) {
                   15446: 	    return @{$iphosts{$ip}};
                   15447: 	}
                   15448: 	return;
1.839     albertel 15449:     }
1.864     albertel 15450:     
                   15451:     sub reset_hosts_ip_info {
                   15452: 	undef(%iphost);
                   15453: 	undef(%name_to_ip);
                   15454: 	undef(%lonid_to_ip);
                   15455:     }
1.856     albertel 15456: 
                   15457:     sub get_host_ip {
                   15458: 	my ($lonid) = @_;
                   15459: 	if (exists($lonid_to_ip{$lonid})) {
                   15460: 	    return $lonid_to_ip{$lonid};
                   15461: 	}
                   15462: 	my $name=&hostname($lonid);
                   15463:    	my $ip = gethostbyname($name);
                   15464: 	return if (!$ip || length($ip) ne 4);
                   15465: 	$ip=inet_ntoa($ip);
                   15466: 	$name_to_ip{$name}   = $ip;
                   15467: 	$lonid_to_ip{$lonid} = $ip;
                   15468: 	return $ip;
                   15469:     }
1.847     albertel 15470:     
                   15471:     sub get_iphost {
1.1293    raeburn  15472: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 15473: 
1.869     albertel 15474: 	if (!$ignore_cache) {
                   15475: 	    if (%iphost) {
                   15476: 		return %iphost;
                   15477: 	    }
                   15478: 	    my ($ip_info,$cached)=
                   15479: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   15480: 	    if ($cached) {
                   15481: 		%iphost      = %{$ip_info->[0]};
                   15482: 		%name_to_ip  = %{$ip_info->[1]};
                   15483: 		%lonid_to_ip = %{$ip_info->[2]};
                   15484: 		return %iphost;
                   15485: 	    }
                   15486: 	}
1.894     albertel 15487: 
                   15488: 	# get yesterday's info for fallback
                   15489: 	my %old_name_to_ip;
                   15490: 	my ($ip_info,$cached)=
                   15491: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   15492: 	if ($cached) {
                   15493: 	    %old_name_to_ip = %{$ip_info->[1]};
                   15494: 	}
                   15495: 
1.1293    raeburn  15496: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 15497: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 15498: 	    my $ip;
                   15499: 	    if (!exists($name_to_ip{$name})) {
                   15500: 		$ip = gethostbyname($name);
                   15501: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 15502: 		    if (defined($old_name_to_ip{$name})) {
                   15503: 			$ip = $old_name_to_ip{$name};
                   15504: 			&logthis("Can't find $name defaulting to old $ip");
                   15505: 		    } else {
                   15506: 			&logthis("Name $name no IP found");
                   15507: 			next;
                   15508: 		    }
                   15509: 		} else {
                   15510: 		    $ip=inet_ntoa($ip);
1.847     albertel 15511: 		}
                   15512: 		$name_to_ip{$name} = $ip;
                   15513: 	    } else {
                   15514: 		$ip = $name_to_ip{$name};
1.653     albertel 15515: 	    }
1.888     albertel 15516: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   15517: 		$lonid_to_ip{$id} = $ip;
                   15518: 	    }
                   15519: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 15520: 	}
1.1293    raeburn  15521:         unless ($nocache) {
                   15522: 	    &do_cache_new('iphost','iphost',
                   15523: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   15524: 		          48*60*60);
                   15525:         }
1.869     albertel 15526: 
1.847     albertel 15527: 	return %iphost;
1.598     albertel 15528:     }
                   15529: 
1.992     raeburn  15530:     #
                   15531:     #  Given a DNS returns the loncapa host name for that DNS 
                   15532:     # 
                   15533:     sub host_from_dns {
                   15534:         my ($dns) = @_;
                   15535:         my @hosts;
                   15536:         my $ip;
                   15537: 
1.993     raeburn  15538:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  15539:             $ip = $name_to_ip{$dns};
                   15540:         }
                   15541:         if (!$ip) {
                   15542:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   15543:             if (length($ip) == 4) { 
                   15544: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   15545:             }
                   15546:         }
                   15547:         if ($ip) {
                   15548: 	    @hosts = get_hosts_from_ip($ip);
                   15549: 	    return $hosts[0];
                   15550:         }
                   15551:         return undef;
1.986     foxr     15552:     }
1.992     raeburn  15553: 
1.1074    raeburn  15554:     sub get_internet_names {
                   15555:         my ($lonid) = @_;
                   15556:         return if ($lonid eq '');
                   15557:         my ($idnref,$cached)=
                   15558:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   15559:         if ($cached) {
                   15560:             return $idnref;
                   15561:         }
                   15562:         my $ip = &get_host_ip($lonid);
                   15563:         my @hosts = &get_hosts_from_ip($ip);
                   15564:         my %iphost = &get_iphost();
                   15565:         my (@idns,%seen);
                   15566:         foreach my $id (@hosts) {
                   15567:             my $dom = &host_domain($id);
                   15568:             my $prim_id = &domain($dom,'primary');
                   15569:             my $prim_ip = &get_host_ip($prim_id);
                   15570:             next if ($seen{$prim_ip});
                   15571:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   15572:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   15573:                     my $intdom = &internet_dom($id);
                   15574:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   15575:                         push(@idns,$intdom);
                   15576:                     }
                   15577:                 }
                   15578:             }
                   15579:             $seen{$prim_ip} = 1;
                   15580:         }
1.1219    raeburn  15581:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  15582:     }
                   15583: 
1.986     foxr     15584: }
                   15585: 
1.1079    raeburn  15586: sub all_loncaparevs {
1.1249    raeburn  15587:     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  15588: }
                   15589: 
1.1227    raeburn  15590: # ---------------------------------------------------------- Read loncaparev table
                   15591: {
                   15592:     sub load_loncaparevs { 
                   15593:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359    raeburn  15594:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227    raeburn  15595:                 while (my $configline=<$config>) {
                   15596:                     chomp($configline);
                   15597:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   15598:                     $loncaparevs{$hostid}=$loncaparev;
                   15599:                 }
                   15600:                 close($config);
                   15601:             }
                   15602:         }
                   15603:     }
                   15604: }
                   15605: 
                   15606: # ---------------------------------------------------------- Read serverhostID table
                   15607: {
                   15608:     sub load_serverhomeIDs {
                   15609:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359    raeburn  15610:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227    raeburn  15611:                 while (my $configline=<$config>) {
                   15612:                     chomp($configline);
                   15613:                     my ($name,$id)=split(/:/,$configline);
                   15614:                     $serverhomeIDs{$name}=$id;
                   15615:                 }
                   15616:                 close($config);
                   15617:             }
                   15618:         }
                   15619:     }
                   15620: }
                   15621: 
                   15622: 
1.862     albertel 15623: BEGIN {
                   15624: 
                   15625: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   15626:     unless ($readit) {
                   15627: {
                   15628:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   15629:     %perlvar = (%perlvar,%{$configvars});
                   15630: }
                   15631: 
                   15632: 
1.1       albertel 15633: # ------------------------------------------------------ Read spare server file
                   15634: {
1.1359    raeburn  15635:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 15636: 
                   15637:     while (my $configline=<$config>) {
                   15638:        chomp($configline);
1.284     matthew  15639:        if ($configline) {
1.784     albertel 15640: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 15641: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 15642: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 15643:        }
                   15644:     }
1.448     albertel 15645:     close($config);
1.1       albertel 15646: }
1.11      www      15647: # ------------------------------------------------------------ Read permissions
                   15648: {
1.1359    raeburn  15649:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      15650: 
                   15651:     while (my $configline=<$config>) {
1.448     albertel 15652: 	chomp($configline);
                   15653: 	if ($configline) {
                   15654: 	    my ($role,$perm)=split(/ /,$configline);
                   15655: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   15656: 	}
1.11      www      15657:     }
1.448     albertel 15658:     close($config);
1.11      www      15659: }
                   15660: 
                   15661: # -------------------------------------------- Read plain texts for permissions
                   15662: {
1.1359    raeburn  15663:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      15664: 
                   15665:     while (my $configline=<$config>) {
1.448     albertel 15666: 	chomp($configline);
                   15667: 	if ($configline) {
1.742     raeburn  15668: 	    my ($short,@plain)=split(/:/,$configline);
                   15669:             %{$prp{$short}} = ();
                   15670: 	    if (@plain > 0) {
                   15671:                 $prp{$short}{'std'} = $plain[0];
                   15672:                 for (my $i=1; $i<@plain; $i++) {
                   15673:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   15674:                 }
                   15675:             }
1.448     albertel 15676: 	}
1.135     www      15677:     }
1.448     albertel 15678:     close($config);
1.135     www      15679: }
                   15680: 
                   15681: # ---------------------------------------------------------- Read package table
                   15682: {
1.1359    raeburn  15683:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      15684: 
                   15685:     while (my $configline=<$config>) {
1.483     albertel 15686: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 15687: 	chomp($configline);
                   15688: 	my ($short,$plain)=split(/:/,$configline);
                   15689: 	my ($pack,$name)=split(/\&/,$short);
                   15690: 	if ($plain ne '') {
                   15691: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   15692: 	    $packagetab{$short}=$plain; 
                   15693: 	}
1.11      www      15694:     }
1.448     albertel 15695:     close($config);
1.329     matthew  15696: }
                   15697: 
1.1073    raeburn  15698: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  15699: 
                   15700: &load_loncaparevs();
1.1073    raeburn  15701: 
1.1074    raeburn  15702: # ---------------------------------------------------------- Read serverhostID table
                   15703: 
1.1227    raeburn  15704: &load_serverhomeIDs();
                   15705: 
                   15706: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  15707: {
                   15708:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   15709:     if (-e $file) {
                   15710:         my $parser = HTML::LCParser->new($file);
                   15711:         while (my $token = $parser->get_token()) {
                   15712:             if ($token->[0] eq 'S') {
                   15713:                 my $item = $token->[1];
                   15714:                 my $name = $token->[2]{'name'};
                   15715:                 my $value = $token->[2]{'value'};
1.1285    raeburn  15716:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  15717:                 my $namematch = $token->[2]{'namematch'};
                   15718:                 if ($item eq 'parameter') {
                   15719:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   15720:                         my $release = $parser->get_text();
                   15721:                         $release =~ s/(^\s*|\s*$ )//gx;
                   15722:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   15723:                     }
                   15724:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  15725:                     my $release = $parser->get_text();
                   15726:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  15727:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  15728:                 }
                   15729:             }
                   15730:         }
                   15731:     }
1.1073    raeburn  15732: }
                   15733: 
1.1138    raeburn  15734: # ---------------------------------------------------------- Read managers table
                   15735: {
                   15736:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359    raeburn  15737:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  15738:             while (my $configline=<$config>) {
                   15739:                 chomp($configline);
                   15740:                 next if ($configline =~ /^\#/);
                   15741:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   15742:                     $managerstab{$configline} = 1;
                   15743:                 }
                   15744:             }
                   15745:             close($config);
                   15746:         }
                   15747:     }
                   15748: }
                   15749: 
1.329     matthew  15750: # ------------- set up temporary directory
                   15751: {
1.1117    foxr     15752:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  15753: 
1.11      www      15754: }
                   15755: 
1.1405    raeburn  15756: # ------------- set default texengine (domain default overrides this)
                   15757: {
                   15758:     $deftex = LONCAPA::texengine();
                   15759: }
                   15760: 
1.1416    raeburn  15761: # ------------- set default minimum length for passwords for internal auth users
                   15762: {
                   15763:     $passwdmin = LONCAPA::passwd_min();
                   15764: }
                   15765: 
1.794     albertel 15766: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   15767: 				'compress_threshold'=> 20_000,
                   15768:  			        });
1.185     www      15769: 
1.281     www      15770: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      15771: $dumpcount=0;
1.958     www      15772: $locknum=0;
1.22      www      15773: 
1.163     harris41 15774: &logtouch();
1.672     albertel 15775: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      15776: $readit=1;
1.564     albertel 15777:     {
                   15778: 	use integer;
                   15779: 	my $test=(2**32)+1;
1.568     albertel 15780: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 15781: 	&logthis(" Detected 64bit platform ($_64bit)");
                   15782:     }
1.195     www      15783: }
1.1       albertel 15784: }
1.179     www      15785: 
1.1       albertel 15786: 1;
1.191     harris41 15787: __END__
                   15788: 
1.243     albertel 15789: =pod
                   15790: 
1.191     harris41 15791: =head1 NAME
                   15792: 
1.243     albertel 15793: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 15794: 
                   15795: =head1 SYNOPSIS
                   15796: 
1.243     albertel 15797: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 15798: 
                   15799:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   15800: 
1.243     albertel 15801: Common parameters:
                   15802: 
                   15803: =over 4
                   15804: 
                   15805: =item *
                   15806: 
                   15807: $uname : an internal username (if $cname expecting a course Id specifically)
                   15808: 
                   15809: =item *
                   15810: 
                   15811: $udom : a domain (if $cdom expecting a course's domain specifically)
                   15812: 
                   15813: =item *
                   15814: 
                   15815: $symb : a resource instance identifier
                   15816: 
                   15817: =item *
                   15818: 
                   15819: $namespace : the name of a .db file that contains the data needed or
                   15820: being set.
                   15821: 
                   15822: =back
                   15823: 
1.394     bowersj2 15824: =head1 OVERVIEW
1.191     harris41 15825: 
1.394     bowersj2 15826: lonnet provides subroutines which interact with the
                   15827: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   15828: about classes, users, and resources.
1.243     albertel 15829: 
                   15830: For many of these objects you can also use this to store data about
                   15831: them or modify them in various ways.
1.191     harris41 15832: 
1.394     bowersj2 15833: =head2 Symbs
1.191     harris41 15834: 
1.394     bowersj2 15835: To identify a specific instance of a resource, LON-CAPA uses symbols
                   15836: or "symbs"X<symb>. These identifiers are built from the URL of the
                   15837: map, the resource number of the resource in the map, and the URL of
                   15838: the resource itself. The latter is somewhat redundant, but might help
                   15839: if maps change.
                   15840: 
                   15841: An example is
                   15842: 
                   15843:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   15844: 
                   15845: The respective map entry is
                   15846: 
                   15847:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   15848:   title="Problem 2">
                   15849:  </resource>
                   15850: 
                   15851: Symbs are used by the random number generator, as well as to store and
                   15852: restore data specific to a certain instance of for example a problem.
                   15853: 
                   15854: =head2 Storing And Retrieving Data
                   15855: 
                   15856: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   15857: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   15858: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   15859: is is the non-critical message twin of cstore. These functions are for
                   15860: handlers to store a perl hash to a user's permanent data space in an
                   15861: easy manner, and to retrieve it again on another call. It is expected
                   15862: that a handler would use this once at the beginning to retrieve data,
                   15863: and then again once at the end to send only the new data back.
                   15864: 
                   15865: The data is stored in the user's data directory on the user's
                   15866: homeserver under the ID of the course.
                   15867: 
                   15868: The hash that is returned by restore will have all of the previous
                   15869: value for all of the elements of the hash.
                   15870: 
                   15871: Example:
                   15872: 
                   15873:  #creating a hash
                   15874:  my %hash;
                   15875:  $hash{'foo'}='bar';
                   15876: 
                   15877:  #storing it
                   15878:  &Apache::lonnet::cstore(\%hash);
                   15879: 
                   15880:  #changing a value
                   15881:  $hash{'foo'}='notbar';
                   15882: 
                   15883:  #adding a new value
                   15884:  $hash{'bar'}='foo';
                   15885:  &Apache::lonnet::cstore(\%hash);
                   15886: 
                   15887:  #retrieving the hash
                   15888:  my %history=&Apache::lonnet::restore();
                   15889: 
                   15890:  #print the hash
                   15891:  foreach my $key (sort(keys(%history))) {
                   15892:    print("\%history{$key} = $history{$key}");
                   15893:  }
                   15894: 
                   15895: Will print out:
1.191     harris41 15896: 
1.394     bowersj2 15897:  %history{1:foo} = bar
                   15898:  %history{1:keys} = foo:timestamp
                   15899:  %history{1:timestamp} = 990455579
                   15900:  %history{2:bar} = foo
                   15901:  %history{2:foo} = notbar
                   15902:  %history{2:keys} = foo:bar:timestamp
                   15903:  %history{2:timestamp} = 990455580
                   15904:  %history{bar} = foo
                   15905:  %history{foo} = notbar
                   15906:  %history{timestamp} = 990455580
                   15907:  %history{version} = 2
                   15908: 
                   15909: Note that the special hash entries C<keys>, C<version> and
                   15910: C<timestamp> were added to the hash. C<version> will be equal to the
                   15911: total number of versions of the data that have been stored. The
                   15912: C<timestamp> attribute will be the UNIX time the hash was
                   15913: stored. C<keys> is available in every historical section to list which
                   15914: keys were added or changed at a specific historical revision of a
                   15915: hash.
                   15916: 
                   15917: B<Warning>: do not store the hash that restore returns directly. This
                   15918: will cause a mess since it will restore the historical keys as if the
                   15919: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 15920: 
1.394     bowersj2 15921: Calling convention:
1.191     harris41 15922: 
1.1225    raeburn  15923:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  15924:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 15925: 
1.394     bowersj2 15926: For more detailed information, see lonnet specific documentation.
1.191     harris41 15927: 
1.394     bowersj2 15928: =head1 RETURN MESSAGES
1.191     harris41 15929: 
1.394     bowersj2 15930: =over 4
1.191     harris41 15931: 
1.394     bowersj2 15932: =item * B<con_lost>: unable to contact remote host
1.191     harris41 15933: 
1.394     bowersj2 15934: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   15935: when the connection is brought back up
1.191     harris41 15936: 
1.394     bowersj2 15937: =item * B<con_failed>: unable to contact remote host and unable to save message
                   15938: for later delivery
1.191     harris41 15939: 
1.967     bisitz   15940: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 15941: 
1.394     bowersj2 15942: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 15943: that was requested
1.191     harris41 15944: 
1.243     albertel 15945: =back
1.191     harris41 15946: 
1.243     albertel 15947: =head1 PUBLIC SUBROUTINES
1.191     harris41 15948: 
1.243     albertel 15949: =head2 Session Environment Functions
1.191     harris41 15950: 
1.243     albertel 15951: =over 4
1.191     harris41 15952: 
1.394     bowersj2 15953: =item * 
                   15954: X<appenv()>
1.949     raeburn  15955: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 15956: the user envirnoment file, and will be restored for each access this
1.620     albertel 15957: user makes during this session, also modifies the %env for the current
1.949     raeburn  15958: process. Optional rolesarrayref - if defined contains a reference to an array
                   15959: of roles which are exempt from the restriction on modifying user.role entries 
                   15960: in the user's environment.db and in %env.    
1.191     harris41 15961: 
                   15962: =item *
1.394     bowersj2 15963: X<delenv()>
1.987     raeburn  15964: B<delenv($delthis,$regexp)>: removes all items from the session
                   15965: environment file that begin with $delthis. If the 
                   15966: optional second arg - $regexp - is true, $delthis is treated as a 
                   15967: regular expression, otherwise \Q$delthis\E is used. 
                   15968: The values are also deleted from the current processes %env.
1.191     harris41 15969: 
1.795     albertel 15970: =item * get_env_multiple($name) 
                   15971: 
                   15972: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   15973: values may be defined and end up as an array ref.
                   15974: 
                   15975: returns an array of values
                   15976: 
1.243     albertel 15977: =back
                   15978: 
                   15979: =head2 User Information
1.191     harris41 15980: 
1.243     albertel 15981: =over 4
1.191     harris41 15982: 
                   15983: =item *
1.394     bowersj2 15984: X<queryauthenticate()>
                   15985: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 15986: authentication scheme
                   15987: 
                   15988: =item *
1.394     bowersj2 15989: X<authenticate()>
1.1073    raeburn  15990: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 15991: authenticate user from domain's lib servers (first use the current
                   15992: one). C<$upass> should be the users password.
1.1073    raeburn  15993: $checkdefauth is optional (value is 1 if a check should be made to
                   15994:    authenticate user using default authentication method, and allow
                   15995:    account creation if username does not have account in the domain).
                   15996: $clientcancheckhost is optional (value is 1 if checking whether the
                   15997:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 15998: 
                   15999: =item *
1.394     bowersj2 16000: X<homeserver()>
                   16001: B<homeserver($uname,$udom)>: find the server which has
                   16002: the user's directory and files (there must be only one), this caches
                   16003: the answer, and also caches if there is a borken connection.
1.191     harris41 16004: 
                   16005: =item *
1.394     bowersj2 16006: X<idget()>
1.1300    raeburn  16007: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   16008: a list of student/employee IDs or clicker IDs
                   16009: (student/employee IDs are a unique resource in a domain, there must be 
                   16010: only 1 ID per username, and only 1 username per ID in a specific domain).
                   16011: clickerIDs are not necessarily unique, as students might share clickers.
                   16012: (returns hash: id=>name,id=>name)
1.191     harris41 16013: 
                   16014: =item *
1.394     bowersj2 16015: X<idrget()>
                   16016: B<idrget($udom,@unames)>: find the IDs behind a list of
                   16017: usernames (returns hash: name=>id,name=>id)
1.191     harris41 16018: 
                   16019: =item *
1.394     bowersj2 16020: X<idput()>
1.1300    raeburn  16021: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   16022: names and associated student/employee IDs or clicker IDs.
                   16023: 
                   16024: =item *
                   16025: X<iddel()>
                   16026: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   16027: student/employee ID or clicker ID username look-ups from domain.
                   16028: The homeserver ($uhome) and namespace ($namespace) are optional.
                   16029: If no $uhome is provided, it will be determined usig &homeserver()
                   16030: for each user.  If no $namespace is provided, the default is ids.
                   16031: 
                   16032: =item *
                   16033: X<updateclickers()>
                   16034: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   16035: clicker ID-to-username look-ups in clickers.db on library server.
                   16036: Permitted actions are add or del (i.e., add or delete). The 
                   16037: clickers.db contains clickerID as keys (escaped), and each corresponding
                   16038: value is an escaped comma-separated list of usernames (for whom the
                   16039: library server is the homeserver), who registered that particular ID.
                   16040: If $critical is true, the update will be sent via &critical, otherwise
                   16041: &reply() will be used.
1.191     harris41 16042: 
                   16043: =item *
1.394     bowersj2 16044: X<rolesinit()>
1.1169    droeschl 16045: B<rolesinit($udom,$username)>: get user privileges.
                   16046: returns user role, first access and timer interval hashes
1.243     albertel 16047: 
                   16048: =item *
1.1171    droeschl 16049: X<privileged()>
                   16050: B<privileged($username,$domain)>: returns a true if user has a
                   16051: privileged and active role (i.e. su or dc), false otherwise.
                   16052: 
                   16053: =item *
1.551     albertel 16054: X<getsection()>
                   16055: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 16056: course $cname, return section name/number or '' for "not in course"
                   16057: and '-1' for "no section"
                   16058: 
                   16059: =item *
1.394     bowersj2 16060: X<userenvironment()>
                   16061: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 16062: passed in @what from the requested user's environment, returns a hash
                   16063: 
1.858     raeburn  16064: =item * 
                   16065: X<userlog_query()>
1.859     albertel 16066: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   16067: activity.log file. %filters defines filters applied when parsing the
                   16068: log file. These can be start or end timestamps, or the type of action
                   16069: - log to look for Login or Logout events, check for Checkin or
                   16070: Checkout, role for role selection. The response is in the form
                   16071: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   16072: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  16073: 
1.243     albertel 16074: =back
                   16075: 
                   16076: =head2 User Roles
                   16077: 
                   16078: =over 4
                   16079: 
                   16080: =item *
                   16081: 
1.1284    raeburn  16082: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   16083: returns codes for allowed actions.
                   16084: 
                   16085: The first argument is required, all others are optional.
                   16086: 
                   16087: $priv is the privilege being checked.
                   16088: $uri contains additional information about what is being checked for access (e.g.,
                   16089: URL, course ID etc.). 
                   16090: $symb is the unique resource instance identifier in a course; if needed,
                   16091: but not provided, it will be retrieved via a call to &symbread(). 
                   16092: $role is the role for which a priv is being checked (only used if priv is evb). 
                   16093: $clientip is the user's IP address (only used when checking for access to portfolio 
                   16094: files).
                   16095: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   16096: prevents recursive calls to &allowed.
                   16097: 
1.243     albertel 16098:  F: full access
                   16099:  U,I,K: authentication modes (cxx only)
                   16100:  '': forbidden
                   16101:  1: user needs to choose course
                   16102:  2: browse allowed
1.766     albertel 16103:  A: passphrase authentication needed
1.1284    raeburn  16104:  B: access temporarily blocked because of a blocking event in a course.
1.1402    raeburn  16105:  D: access blocked because access is required via session initiated via deep-link 
1.243     albertel 16106: 
                   16107: =item *
                   16108: 
1.1192    raeburn  16109: constructaccess($url,$setpriv) : check for access to construction space URL
                   16110: 
                   16111: See if the owner domain and name in the URL match those in the
                   16112: expected environment.  If so, return three element list
                   16113: ($ownername,$ownerdomain,$ownerhome).
                   16114: 
                   16115: Otherwise return the null string.
                   16116: 
                   16117: If second argument 'setpriv' is true, it assigns the privileges,
                   16118: and returns the same three element list, unless the owner has
                   16119: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   16120: in which case the null string is returned.
                   16121: 
                   16122: =item *
                   16123: 
1.1326    raeburn  16124: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   16125: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   16126: for system, domain, and course level. $uname and $udom are optional (current
                   16127: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 16128: 
                   16129: =item *
                   16130: 
1.988     raeburn  16131: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   16132: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  16133: $type is Course (default) or Community.
1.988     raeburn  16134: If $forcedefault evaluates to true, text returned will be default 
                   16135: text for $type. Otherwise, if this is a course, the text returned 
                   16136: will be a custom name for the role (if defined in the course's 
                   16137: environment).  If no custom name is defined the default is returned.
                   16138:    
1.832     raeburn  16139: =item *
                   16140: 
1.1219    raeburn  16141: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  16142: All arguments are optional. Returns a hash of a roles, either for
                   16143: co-author/assistant author roles for a user's Construction Space
1.906     albertel 16144: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  16145: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   16146: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   16147: For each key, value is set to colon-separated start and end times for
                   16148: the role.  If no username and domain are specified, will default to
1.934     raeburn  16149: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  16150: of role statuses (active, future or previous), roles 
                   16151: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   16152: to restrict the list of roles reported. If no array ref is 
                   16153: provided for types, will default to return only active roles.
1.834     albertel 16154: 
1.1195    raeburn  16155: =item *
                   16156: 
                   16157: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  16158: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   16159: 
                   16160: Additional optional arguments are: $type (if role checking is to be restricted 
                   16161: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  16162: available roles) or future (roles available in the future), and
                   16163: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  16164: have active Domain Coordinator role in course's domain or in additional
                   16165: domains (specified in 'Domains to check for privileged users' in course
                   16166: environment -- set via:  Course Settings -> Classlists and staff listing).
                   16167: 
                   16168: =item *
                   16169: 
                   16170: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   16171: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   16172: $possdomains and $possroles are optional array refs -- to domains to check and
                   16173: roles to check.  If $possdomains is not specified, a dump will be done of the
                   16174: users' roles.db to check for a dc or su role in any domain. This can be
                   16175: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   16176: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   16177: this then allows &privileged_by_domain() to be used, which caches the identity
                   16178: of privileged users, eliminating the need for repeated calls to &dump().
                   16179: 
                   16180: =item *
                   16181: 
                   16182: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   16183: where the outer hash keys are domains specified in the $possdomains array ref,
                   16184: next inner hash keys are privileged roles specified in the $roles array ref,
                   16185: and the innermost hash contains key = value pairs for username:domain = end:start
                   16186: for active or future "privileged" users with that role in that domain. To avoid
                   16187: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   16188: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  16189: 
1.243     albertel 16190: =back
                   16191: 
                   16192: =head2 User Modification
                   16193: 
                   16194: =over 4
                   16195: 
                   16196: =item *
                   16197: 
1.957     raeburn  16198: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 16199: user for the level given by URL.  Optional start and end dates (leave empty
                   16200: string or zero for "no date")
1.191     harris41 16201: 
                   16202: =item *
                   16203: 
1.243     albertel 16204: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   16205: change a users, password, possible return values are: ok,
                   16206: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   16207: refused
1.191     harris41 16208: 
                   16209: =item *
                   16210: 
1.243     albertel 16211: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 16212: 
                   16213: =item *
                   16214: 
1.1058    raeburn  16215: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   16216:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   16217: 
                   16218: will update user information (firstname,middlename,lastname,generation,
                   16219: permanentemail), and if forceid is true, student/employee ID also.
                   16220: A user's institutional affiliation(s) can also be updated.
                   16221: User information fields will not be overwritten with empty entries 
                   16222: unless the field is included in the $candelete array reference.
                   16223: This array is included when a single user is modified via "Manage Users",
                   16224: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 16225: 
                   16226: =item *
                   16227: 
1.286     matthew  16228: modifystudent
                   16229: 
1.957     raeburn  16230: modify a student's enrollment and identification information.
1.1235    raeburn  16231: The course id is resolved based on the current user's environment.  
                   16232: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  16233: associated with a course.
                   16234: 
1.297     matthew  16235: This call is essentially a wrapper for lonnet::modifyuser and
                   16236: lonnet::modify_student_enrollment
1.286     matthew  16237: 
                   16238: Inputs: 
                   16239: 
                   16240: =over 4
                   16241: 
1.957     raeburn  16242: =item B<$udom> Student's loncapa domain
1.286     matthew  16243: 
1.957     raeburn  16244: =item B<$uname> Student's loncapa login name
1.286     matthew  16245: 
1.964     bisitz   16246: =item B<$uid> Student/Employee ID
1.286     matthew  16247: 
1.957     raeburn  16248: =item B<$umode> Student's authentication mode
1.286     matthew  16249: 
1.957     raeburn  16250: =item B<$upass> Student's password
1.286     matthew  16251: 
1.957     raeburn  16252: =item B<$first> Student's first name
1.286     matthew  16253: 
1.957     raeburn  16254: =item B<$middle> Student's middle name
1.286     matthew  16255: 
1.957     raeburn  16256: =item B<$last> Student's last name
1.286     matthew  16257: 
1.957     raeburn  16258: =item B<$gene> Student's generation
1.286     matthew  16259: 
1.957     raeburn  16260: =item B<$usec> Student's section in course
1.286     matthew  16261: 
                   16262: =item B<$end> Unix time of the roles expiration
                   16263: 
                   16264: =item B<$start> Unix time of the roles start date
                   16265: 
                   16266: =item B<$forceid> If defined, allow $uid to be changed
                   16267: 
                   16268: =item B<$desiredhome> server to use as home server for student
                   16269: 
1.957     raeburn  16270: =item B<$email> Student's permanent e-mail address
                   16271: 
                   16272: =item B<$type> Type of enrollment (auto or manual)
                   16273: 
1.963     raeburn  16274: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   16275: 
                   16276: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  16277: 
1.963     raeburn  16278: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  16279: 
1.963     raeburn  16280: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  16281: 
1.1216    raeburn  16282: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   16283: 
                   16284: =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  16285: 
1.286     matthew  16286: =back
1.297     matthew  16287: 
                   16288: =item *
                   16289: 
                   16290: modify_student_enrollment
                   16291: 
1.1235    raeburn  16292: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  16293: 'role.request.course' must be defined for this function to proceed.
                   16294: 
                   16295: Inputs:
                   16296: 
                   16297: =over 4
                   16298: 
1.1235    raeburn  16299: =item $udom, student's domain
1.297     matthew  16300: 
1.1235    raeburn  16301: =item $uname, student's name
1.297     matthew  16302: 
1.1235    raeburn  16303: =item $uid, student's user id
1.297     matthew  16304: 
1.1235    raeburn  16305: =item $first, student's first name
1.297     matthew  16306: 
                   16307: =item $middle
                   16308: 
                   16309: =item $last
                   16310: 
                   16311: =item $gene
                   16312: 
                   16313: =item $usec
                   16314: 
                   16315: =item $end
                   16316: 
                   16317: =item $start
                   16318: 
1.957     raeburn  16319: =item $type
                   16320: 
                   16321: =item $locktype
                   16322: 
                   16323: =item $cid
                   16324: 
                   16325: =item $selfenroll
                   16326: 
                   16327: =item $context
                   16328: 
1.1216    raeburn  16329: =item $credits, number of credits student will earn from this class
                   16330: 
1.1314    raeburn  16331: =item $instsec, institutional course section code for student
                   16332: 
1.297     matthew  16333: =back
                   16334: 
1.191     harris41 16335: 
                   16336: =item *
                   16337: 
1.243     albertel 16338: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   16339: custom role; give a custom role to a user for the level given by URL.  Specify
                   16340: name and domain of role author, and role name
1.191     harris41 16341: 
                   16342: =item *
                   16343: 
1.243     albertel 16344: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 16345: 
                   16346: =item *
                   16347: 
1.243     albertel 16348: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   16349: 
                   16350: =back
                   16351: 
                   16352: =head2 Course Infomation
                   16353: 
                   16354: =over 4
1.191     harris41 16355: 
                   16356: =item *
                   16357: 
1.1118    foxr     16358: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 16359: specified course id, including all environment settings for the
                   16360: course, the description of the course will be in the hash under the
                   16361: key 'description'
1.191     harris41 16362: 
1.1118    foxr     16363: $options is an optional parameter that if supplied is a hash reference that controls
                   16364: what how this function works.  It has the following key/values:
                   16365: 
                   16366: =over 4
                   16367: 
                   16368: =item freshen_cache
                   16369: 
                   16370: If defined, and the environment cache for the course is valid, it is 
                   16371: returned in the returned hash.
                   16372: 
                   16373: =item one_time
                   16374: 
                   16375: If defined, the last cache time is set to _now_
                   16376: 
                   16377: =item user
                   16378: 
                   16379: If defined, the supplied username is used instead of the current user.
                   16380: 
                   16381: 
                   16382: =back
                   16383: 
1.191     harris41 16384: =item *
                   16385: 
1.624     albertel 16386: resdata($name,$domain,$type,@which) : request for current parameter
                   16387: setting for a specific $type, where $type is either 'course' or 'user',
                   16388: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  16389: answers for 10 minutes.
1.243     albertel 16390: 
1.877     foxr     16391: =item *
                   16392: 
                   16393: get_courseresdata($courseid, $domain) : dump the entire course resource
                   16394: data base, returning a hash that is keyed by the resource name and has
                   16395: values that are the resource value.  I believe that the timestamps and
                   16396: versions are also returned.
                   16397: 
1.1236    raeburn  16398: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   16399: supplemental content area. This routine caches the number of files for 
                   16400: 10 minutes.
                   16401: 
1.243     albertel 16402: =back
                   16403: 
                   16404: =head2 Course Modification
                   16405: 
                   16406: =over 4
1.191     harris41 16407: 
                   16408: =item *
                   16409: 
1.243     albertel 16410: writecoursepref($courseid,%prefs) : write preferences (environment
                   16411: database) for a course
1.191     harris41 16412: 
                   16413: =item *
                   16414: 
1.1011    raeburn  16415: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   16416: 
                   16417: =item *
                   16418: 
1.1038    raeburn  16419: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 16420: 
1.1167    droeschl 16421: =item *
                   16422: 
                   16423: is_course($courseid), is_course($cdom, $cnum)
                   16424: 
                   16425: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   16426: two component version $cdom, $cnum. It checks if the specified course exists.
                   16427: 
                   16428: Returns:
                   16429:     undef if the course doesn't exist, otherwise
                   16430:     in scalar context the combined courseid.
                   16431:     in list context the two components of the course identifier, domain and 
                   16432:     courseid.    
                   16433: 
1.243     albertel 16434: =back
                   16435: 
1.1401    raeburn  16436: =head2 Bubblesheet Configuration
                   16437: 
                   16438: =over 4
                   16439: 
                   16440: =item *
                   16441: 
                   16442: get_scantron_config($which)
                   16443: 
                   16444: $which - the name of the configuration to parse from the file.
                   16445: 
                   16446: Parses and returns the bubblesheet configuration line selected as a
                   16447: hash of configuration file fields.
                   16448: 
                   16449: 
                   16450: Returns:
                   16451:     If the named configuration is not in the file, an empty
                   16452:     hash is returned.
                   16453: 
                   16454:     a hash with the fields
                   16455:       name         - internal name for the this configuration setup
                   16456:       description  - text to display to operator that describes this config
                   16457:       CODElocation - if 0 or the string 'none'
                   16458:                           - no CODE exists for this config
                   16459:                      if -1 || the string 'letter'
                   16460:                           - a CODE exists for this config and is
                   16461:                             a string of letters
                   16462:                      Unsupported value (but planned for future support)
                   16463:                           if a positive integer
                   16464:                                - The CODE exists as the first n items from
                   16465:                                  the question section of the form
                   16466:                           if the string 'number'
                   16467:                                - The CODE exists for this config and is
                   16468:                                  a string of numbers
                   16469:       CODEstart   - (only matter if a CODE exists) column in the line where
                   16470:                      the CODE starts
                   16471:       CODElength  - length of the CODE
                   16472:       IDstart     - column where the student/employee ID starts
                   16473:       IDlength    - length of the student/employee ID info
                   16474:       Qstart      - column where the information from the bubbled
                   16475:                     'questions' start
                   16476:       Qlength     - number of columns comprising a single bubble line from
                   16477:                     the sheet. (usually either 1 or 10)
                   16478:       Qon         - either a single character representing the character used
                   16479:                     to signal a bubble was chosen in the positional setup, or
                   16480:                     the string 'letter' if the letter of the chosen bubble is
                   16481:                     in the final, or 'number' if a number representing the
                   16482:                     chosen bubble is in the file (1->A 0->J)
                   16483:       Qoff        - the character used to represent that a bubble was
                   16484:                     left blank
                   16485:       PaperID     - if the scanning process generates a unique number for each
                   16486:                     sheet scanned the column that this ID number starts in
                   16487:       PaperIDlength - number of columns that comprise the unique ID number
                   16488:                       for the sheet of paper
                   16489:       FirstName   - column that the first name starts in
                   16490:       FirstNameLength - number of columns that the first name spans
                   16491:       LastName    - column that the last name starts in
                   16492:       LastNameLength - number of columns that the last name spans
                   16493:       BubblesPerRow - number of bubbles available in each row used to
                   16494:                       bubble an answer. (If not specified, 10 assumed).
                   16495: 
                   16496: 
                   16497: =item *
                   16498: 
                   16499: get_scantronformat_file($cdom)
                   16500: 
                   16501: $cdom - the course's domain (optional); if not supplied, uses
                   16502: domain for current $env{'request.course.id'}.
                   16503: 
                   16504: Returns an array containing lines from the scantron format file for
                   16505: the domain of the course.
                   16506: 
                   16507: If a url for a custom.tab file is listed in domain's configuration.db,
                   16508: lines are from this file.
                   16509: 
                   16510: Otherwise, if a default.tab has been published in RES space by the
                   16511: domainconfig user, lines are from this file.
                   16512: 
                   16513: Otherwise, fall back to getting lines from the legacy file on the
                   16514: local server:  /home/httpd/lonTabs/default_scantronformat.tab
                   16515: 
                   16516: =back
                   16517: 
1.243     albertel 16518: =head2 Resource Subroutines
                   16519: 
                   16520: =over 4
1.191     harris41 16521: 
                   16522: =item *
                   16523: 
1.243     albertel 16524: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 16525: 
                   16526: =item *
                   16527: 
1.243     albertel 16528: repcopy($filename) : subscribes to the requested file, and attempts to
                   16529: replicate from the owning library server, Might return
1.607     raeburn  16530: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   16531: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 16532: resource. Expects the local filesystem pathname
                   16533: (/home/httpd/html/res/....)
                   16534: 
                   16535: =back
                   16536: 
                   16537: =head2 Resource Information
                   16538: 
                   16539: =over 4
1.191     harris41 16540: 
                   16541: =item *
                   16542: 
1.1228    raeburn  16543: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   16544: and returns the value of a variety of different possible values,
                   16545: $varname should be a request string, and the other parameters can be
                   16546: used to specify who and what one is asking about. Ordinarily, $cid 
                   16547: does not need to be specified, as it is retrived from 
                   16548: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   16549: within lonuserstate::loadmap() when initializing a course, before
                   16550: $env{'request.course.id'} has been set, so it needs to be provided
                   16551: in that one case.
1.243     albertel 16552: 
                   16553: Possible values for $varname are environment.lastname (or other item
                   16554: from the envirnment hash), user.name (or someother aspect about the
                   16555: user), resource.0.maxtries (or some other part and parameter of a
                   16556: resource)
1.204     albertel 16557: 
                   16558: =item *
                   16559: 
1.243     albertel 16560: directcondval($number) : get current value of a condition; reads from a state
                   16561: string
1.204     albertel 16562: 
                   16563: =item *
                   16564: 
1.243     albertel 16565: condval($condidx) : value of condition index based on state
1.204     albertel 16566: 
                   16567: =item *
                   16568: 
1.1362    raeburn  16569: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 16570: resource's metadata, $what should be either a specific key, or either
                   16571: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362    raeburn  16572: packages that this resource currently uses, the last 3 arguments are 
                   16573: only used internally for recursive metadata.
                   16574: 
                   16575: the toolsymb is only used where the uri is for an external tool (for which
                   16576: the uri as well as the symb are guaranteed to be unique).
1.243     albertel 16577: 
1.1371    raeburn  16578: this function automatically caches all requests except any made recursively
                   16579: to retrieve a list of metadata keys for an imported library file ($liburi is 
                   16580: defined).
1.191     harris41 16581: 
                   16582: =item *
                   16583: 
1.243     albertel 16584: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   16585: network of library servers; returns file handle of where SQL and regex results
                   16586: will be stored for query
1.191     harris41 16587: 
                   16588: =item *
                   16589: 
1.1282    raeburn  16590: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   16591: return symbolic list entry (all arguments optional). 
                   16592: 
                   16593: Args: filename is the filename (including path) for the file for which a symb 
                   16594: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   16595: to check access status if more than one resource was found in the bighash 
                   16596: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   16597: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   16598: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   16599: cause possible symbs to be checked to determine if they are subject to content
                   16600: blocking, if so they will not be included as possible symbs; possibles is a
                   16601: ref to a hash, which, as a side effect, will be populated with all possible 
                   16602: symbs (content blocking not tested).
                   16603:  
1.243     albertel 16604: returns the data handle
1.191     harris41 16605: 
                   16606: =item *
                   16607: 
1.1190    raeburn  16608: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   16609: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 16610: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  16611: on failure, user must be in a course, as it assumes the existence of
                   16612: the course initial hash, and uses $env('request.course.id'}.  The third
                   16613: arg is an optional reference to a scalar.  If this arg is passed in the 
                   16614: call to symbverify, it will be set to 1 if the symb has been set to be 
                   16615: encrypted; otherwise it will be null.  
1.191     harris41 16616: 
                   16617: =item *
                   16618: 
1.243     albertel 16619: symbclean($symb) : removes versions numbers from a symb, returns the
                   16620: cleaned symb
1.191     harris41 16621: 
                   16622: =item *
                   16623: 
1.243     albertel 16624: is_on_map($uri) : checks if the $uri is somewhere on the current
                   16625: course map, user must be in a course for it to work.
1.191     harris41 16626: 
                   16627: =item *
                   16628: 
1.243     albertel 16629: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 16630: 
                   16631: =item *
                   16632: 
1.243     albertel 16633: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   16634: a random seed, all arguments are optional, if they aren't sent it uses the
                   16635: environment to derive them. Note: if symb isn't sent and it can't get one
                   16636: from &symbread it will use the current time as its return value
1.191     harris41 16637: 
                   16638: =item *
                   16639: 
1.243     albertel 16640: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   16641: unfakeable, receipt
1.191     harris41 16642: 
                   16643: =item *
                   16644: 
1.620     albertel 16645: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 16646: 
                   16647: =item *
                   16648: 
1.243     albertel 16649: countacc($url) : count the number of accesses to a given URL
1.191     harris41 16650: 
                   16651: =item *
                   16652: 
1.243     albertel 16653: 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 16654: 
                   16655: =item *
                   16656: 
1.243     albertel 16657: 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 16658: 
                   16659: =item *
                   16660: 
1.243     albertel 16661: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 16662: 
                   16663: =item *
                   16664: 
1.243     albertel 16665: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   16666: forcing spreadsheet to reevaluate the resource scores next time.
                   16667: 
1.1195    raeburn  16668: =item * 
                   16669: 
1.1196    raeburn  16670: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   16671: when viewing in course context.
1.1195    raeburn  16672: 
1.1196    raeburn  16673:  input: six args -- filename (decluttered), course number, course domain,
                   16674:                     url, symb (if registered) and group (if this is a 
                   16675:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  16676: 
1.1196    raeburn  16677:  output: array of five scalars --
1.1195    raeburn  16678:          $cfile -- url for file editing if editable on current server
                   16679:          $home -- homeserver of resource (i.e., for author if published,
                   16680:                                           or course if uploaded.).
                   16681:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  16682:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   16683:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  16684: 
                   16685: =item *
                   16686: 
                   16687: is_course_upload($file,$cnum,$cdom)
                   16688: 
                   16689: Used in course context to determine if current file was uploaded to 
                   16690: the course (i.e., would be found in /userfiles/docs on the course's 
                   16691: homeserver.
                   16692: 
                   16693:   input: 3 args -- filename (decluttered), course number and course domain.
                   16694:   output: boolean -- 1 if file was uploaded.
                   16695: 
1.243     albertel 16696: =back
                   16697: 
                   16698: =head2 Storing/Retreiving Data
                   16699: 
                   16700: =over 4
1.191     harris41 16701: 
                   16702: =item *
                   16703: 
1.1269    raeburn  16704: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   16705: permanently for this url; hashref needs to be given and should be a \%hashname;
                   16706: the remaining args aren't required and if they aren't passed or are '' they will
                   16707: be derived from the env (with the exception of $laststore, which is an 
                   16708: optional arg used when a user's submission is stored in grading).
                   16709: $laststore is $version=$timestamp, where $version is the most recent version
                   16710: number retrieved for the corresponding $symb in the $namespace db file, and
                   16711: $timestamp is the timestamp for that transaction (UNIX time).
                   16712: $laststore is currently only passed when cstore() is called by 
                   16713: structuretags::finalize_storage().
1.191     harris41 16714: 
                   16715: =item *
                   16716: 
1.1269    raeburn  16717: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   16718: but uses critical subroutine
1.191     harris41 16719: 
                   16720: =item *
                   16721: 
1.243     albertel 16722: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   16723: all args are optional
1.191     harris41 16724: 
                   16725: =item *
                   16726: 
1.717     albertel 16727: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   16728: dumps the complete (or key matching regexp) namespace into a hash
                   16729: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   16730: normally &store()ed into
                   16731: 
                   16732: $range should be either an integer '100' (give me the first 100
                   16733:                                            matching records)
                   16734:               or be  two integers sperated by a - with no spaces
                   16735:                  '30-50' (give me the 30th through the 50th matching
                   16736:                           records)
                   16737: 
                   16738: 
                   16739: =item *
                   16740: 
1.1269    raeburn  16741: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 16742: replaces a &store() version of data with a replacement set of data
                   16743: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  16744: reference. If $tolog is true, the transaction is logged in the courselog
                   16745: with an action=PUTSTORE.
1.717     albertel 16746: 
                   16747: =item *
                   16748: 
1.243     albertel 16749: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   16750: works very similar to store/cstore, but all data is stored in a
                   16751: temporary location and can be reset using tmpreset, $storehash should
                   16752: be a hash reference, returns nothing on success
1.191     harris41 16753: 
                   16754: =item *
                   16755: 
1.243     albertel 16756: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   16757: similar to restore, but all data is stored in a temporary location and
                   16758: can be reset using tmpreset. Returns a hash of values on success,
                   16759: error string otherwise.
1.191     harris41 16760: 
                   16761: =item *
                   16762: 
1.243     albertel 16763: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   16764: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 16765: 
                   16766: =item *
                   16767: 
1.243     albertel 16768: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16769: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 16770: 
                   16771: =item *
                   16772: 
1.243     albertel 16773: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   16774: namesp ($udom and $uname are optional)
1.191     harris41 16775: 
                   16776: =item *
                   16777: 
1.702     albertel 16778: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 16779: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 16780: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  16781: 
1.702     albertel 16782: $range should be either an integer '100' (give me the first 100
                   16783:                                            matching records)
                   16784:               or be  two integers sperated by a - with no spaces
                   16785:                  '30-50' (give me the 30th through the 50th matching
                   16786:                           records)
1.449     matthew  16787: =item *
                   16788: 
                   16789: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   16790: $store can be a scalar, an array reference, or if the amount to be 
                   16791: incremented is > 1, a hash reference.
                   16792: 
                   16793: ($udom and $uname are optional)
1.191     harris41 16794: 
                   16795: =item *
                   16796: 
1.243     albertel 16797: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   16798: ($udom and $uname are optional)
1.191     harris41 16799: 
                   16800: =item *
                   16801: 
1.243     albertel 16802: cput($namespace,$storehash,$udom,$uname) : critical put
                   16803: ($udom and $uname are optional)
1.191     harris41 16804: 
                   16805: =item *
                   16806: 
1.748     albertel 16807: newput($namespace,$storehash,$udom,$uname) :
                   16808: 
                   16809: Attempts to store the items in the $storehash, but only if they don't
                   16810: currently exist, if this succeeds you can be certain that you have 
                   16811: successfully created a new key value pair in the $namespace db.
                   16812: 
                   16813: 
                   16814: Args:
                   16815:  $namespace: name of database to store values to
                   16816:  $storehash: hashref to store to the db
                   16817:  $udom: (optional) domain of user containing the db
                   16818:  $uname: (optional) name of user caontaining the db
                   16819: 
                   16820: Returns:
                   16821:  'ok' -> succeeded in storing all keys of $storehash
                   16822:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   16823:                         least <key> already existed in the db (other
                   16824:                         requested keys may also already exist)
1.967     bisitz   16825:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 16826:  'con_lost' -> unable to contact request server
                   16827:  'refused' -> action was not allowed by remote machine
                   16828: 
                   16829: 
                   16830: =item *
                   16831: 
1.243     albertel 16832: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   16833: reference filled in from namesp (encrypts the return communication)
                   16834: ($udom and $uname are optional)
1.191     harris41 16835: 
                   16836: =item *
                   16837: 
1.243     albertel 16838: log($udom,$name,$home,$message) : write to permanent log for user; use
                   16839: critical subroutine
                   16840: 
1.806     raeburn  16841: =item *
                   16842: 
1.860     raeburn  16843: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   16844: array reference filled in from namespace found in domain level on either
                   16845: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  16846: 
                   16847: =item *
                   16848: 
1.860     raeburn  16849: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   16850: domain level either on specified domain server ($uhome) or primary domain 
                   16851: server ($udom and $uhome are optional)
1.806     raeburn  16852: 
1.943     raeburn  16853: =item * 
                   16854: 
1.1240    raeburn  16855: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   16856: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   16857: the target domain.
                   16858: 
                   16859: May also include additional key => value pairs for the following groups:
                   16860: 
                   16861: =over
                   16862: 
                   16863: =item
                   16864: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   16865: 
                   16866: =over
                   16867: 
                   16868: =item defaultquota, authorquota
                   16869: 
                   16870: =back
                   16871: 
                   16872: =item
                   16873: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   16874: portfolio for users).
                   16875: 
                   16876: =over
                   16877: 
                   16878: =item
                   16879: aboutme, blog, webdav, portfolio
                   16880: 
                   16881: =back
                   16882: 
                   16883: =item
                   16884: requestcourses: ability to request courses, and how requests are processed.
                   16885: 
                   16886: =over
                   16887: 
                   16888: =item
1.1305    raeburn  16889: official, unofficial, community, textbook, placement
1.1240    raeburn  16890: 
                   16891: =back
                   16892: 
                   16893: =item
                   16894: inststatus: types of institutional affiliation, and order in which they are displayed.
                   16895: 
                   16896: =over
                   16897: 
                   16898: =item
1.1256    raeburn  16899: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  16900: 
                   16901: =back
                   16902: 
                   16903: =item
                   16904: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   16905: for course's uploaded content.
                   16906: 
                   16907: =over
                   16908: 
                   16909: =item
1.1246    raeburn  16910: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  16911: communityquota, textbookquota, placementquota
1.1240    raeburn  16912: 
                   16913: =back
                   16914: 
                   16915: =item
                   16916: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   16917: on your servers.
                   16918: 
                   16919: =over
                   16920: 
                   16921: =item 
                   16922: remotesessions, hostedsessions
                   16923: 
                   16924: =back
                   16925: 
                   16926: =back
                   16927: 
                   16928: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   16929: utility to create a configuration.db file on a domain's primary library server 
                   16930: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   16931: -- corresponding values are authentication type (internal, krb4, krb5,
                   16932: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   16933: will be available. Values are retrieved from cache (if current), unless the
                   16934: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   16935: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   16936: 
                   16937: Typical usage:
1.943     raeburn  16938: 
1.1240    raeburn  16939: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  16940: 
1.243     albertel 16941: =back
                   16942: 
                   16943: =head2 Network Status Functions
                   16944: 
                   16945: =over 4
1.191     harris41 16946: 
                   16947: =item *
                   16948: 
1.1137    raeburn  16949: dirlist() : return directory list based on URI (first arg).
                   16950: 
                   16951: Inputs: 1 required, 5 optional.
                   16952: 
                   16953: =over
                   16954: 
                   16955: =item 
                   16956: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   16957: 
                   16958: =item
                   16959: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   16960: 
                   16961: =item
                   16962: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   16963: 
                   16964: =item
                   16965: $getpropath - boolean: 1 if prepend path using &propath(). 
                   16966: 
                   16967: =item
                   16968: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   16969: 
                   16970: =item 
                   16971: $alternateRoot - path to prepend in place of path from $uri.
                   16972: 
                   16973: =back
                   16974: 
                   16975: Returns: Array of up to two items.
                   16976: 
                   16977: =over
                   16978: 
                   16979: a reference to an array of files/subdirectories
                   16980: 
                   16981: =over
                   16982: 
                   16983: Each element in the array of files/subdirectories is a & separated list of
                   16984: item name and the result of running stat on the item.  If dirlist was requested
                   16985: for a file instead of a directory, the item name will be ''. For a directory 
                   16986: listing, if the item is a metadata file, the element will end &N&M 
                   16987: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   16988: default copyright set (1).  
                   16989: 
                   16990: =back
                   16991: 
                   16992: a scalar containing error condition (if encountered).
                   16993: 
                   16994: =over
                   16995: 
                   16996: =item 
                   16997: no_host (no homeserver identified for $username:$domain).
                   16998: 
                   16999: =item 
                   17000: no_such_host (server contacted for listing not identified as valid host).
                   17001: 
                   17002: =item 
                   17003: con_lost (connection to remote server failed).
                   17004: 
                   17005: =item 
                   17006: refused (invalid $username:$domain received on lond side).
                   17007: 
                   17008: =item 
                   17009: no_such_dir (directory at specified path on lond side does not exist). 
                   17010: 
                   17011: =item 
                   17012: empty (directory at specified path on lond side is empty).
                   17013: 
                   17014: =over
                   17015: 
                   17016: This is currently not encountered because the &ls3, &ls2, 
                   17017: &ls (_handler) routines on the lond side do not filter out
                   17018: . and .. from a directory listing. 
                   17019: 
                   17020: =back
                   17021: 
                   17022: =back
                   17023: 
                   17024: =back
1.191     harris41 17025: 
                   17026: =item *
                   17027: 
1.243     albertel 17028: spareserver() : find server with least workload from spare.tab
                   17029: 
1.986     foxr     17030: 
                   17031: =item *
                   17032: 
                   17033: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   17034: if there is no corresponding loncapa host.
                   17035: 
1.243     albertel 17036: =back
                   17037: 
1.986     foxr     17038: 
1.243     albertel 17039: =head2 Apache Request
                   17040: 
                   17041: =over 4
1.191     harris41 17042: 
                   17043: =item *
                   17044: 
1.243     albertel 17045: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   17046: localhost, posts hash
                   17047: 
                   17048: =back
                   17049: 
                   17050: =head2 Data to String to Data
                   17051: 
                   17052: =over 4
1.191     harris41 17053: 
                   17054: =item *
                   17055: 
1.243     albertel 17056: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   17057: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 17058: 
                   17059: =item *
                   17060: 
1.243     albertel 17061: hashref2str($hashref) : convert a hashref into a string complete with
                   17062: escaping and '=' and '&' separators, supports elements that are
                   17063: arrayrefs and hashrefs
1.191     harris41 17064: 
                   17065: =item *
                   17066: 
1.243     albertel 17067: arrayref2str($arrayref) : convert an arrayref into a string complete
                   17068: with escaping and '&' separators, supports elements that are arrayrefs
                   17069: and hashrefs
1.191     harris41 17070: 
                   17071: =item *
                   17072: 
1.243     albertel 17073: str2hash($string) : convert string to hash using unescaping and
                   17074: splitting on '=' and '&', supports elements that are arrayrefs and
                   17075: hashrefs
1.191     harris41 17076: 
                   17077: =item *
                   17078: 
1.243     albertel 17079: str2array($string) : convert string to hash using unescaping and
                   17080: splitting on '&', supports elements that are arrayrefs and hashrefs
                   17081: 
                   17082: =back
                   17083: 
                   17084: =head2 Logging Routines
                   17085: 
                   17086: 
                   17087: These routines allow one to make log messages in the lonnet.log and
                   17088: lonnet.perm logfiles.
1.191     harris41 17089: 
1.1119    foxr     17090: =over 4
                   17091: 
1.191     harris41 17092: =item *
                   17093: 
1.243     albertel 17094: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 17095: 
                   17096: =item *
                   17097: 
1.243     albertel 17098: logthis() : append message to the normal lonnet.log file, it gets
                   17099: preiodically rolled over and deleted.
1.191     harris41 17100: 
                   17101: =item *
                   17102: 
1.243     albertel 17103: logperm() : append a permanent message to lonnet.perm.log, this log
                   17104: file never gets deleted by any automated portion of the system, only
                   17105: messages of critical importance should go in here.
                   17106: 
1.1119    foxr     17107: 
1.243     albertel 17108: =back
                   17109: 
                   17110: =head2 General File Helper Routines
                   17111: 
                   17112: =over 4
1.191     harris41 17113: 
                   17114: =item *
                   17115: 
1.481     raeburn  17116: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   17117: (a) files in /uploaded
                   17118:   (i) If a local copy of the file exists - 
                   17119:       compares modification date of local copy with last-modified date for 
                   17120:       definitive version stored on home server for course. If local copy is 
                   17121:       stale, requests a new version from the home server and stores it. 
                   17122:       If the original has been removed from the home server, then local copy 
                   17123:       is unlinked.
                   17124:   (ii) If local copy does not exist -
                   17125:       requests the file from the home server and stores it. 
                   17126:   
                   17127:   If $caller is 'uploadrep':  
                   17128:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   17129:     for request for files originally uploaded via DOCS. 
                   17130:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   17131:   
                   17132:   Otherwise:
                   17133:      This indicates a call from the content generation phase of the request.
                   17134:      -  returns the entire contents of the file or -1.
                   17135:      
                   17136: (b) files in /res
                   17137:    - returns the entire contents of a file or -1; 
                   17138:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 17139: 
1.712     albertel 17140: 
                   17141: =item *
                   17142: 
                   17143: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   17144:                   reference
                   17145: 
                   17146: returns either a stat() list of data about the file or an empty list
                   17147: if the file doesn't exist or couldn't find out about it (connection
                   17148: problems or user unknown)
                   17149: 
1.191     harris41 17150: =item *
                   17151: 
1.243     albertel 17152: filelocation($dir,$file) : returns file system location of a file
                   17153: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   17154: directory that relative $file lookups are to looked in ($dir of /a/dir
                   17155: and a file of ../bob will become /a/bob)
1.191     harris41 17156: 
                   17157: =item *
                   17158: 
                   17159: hreflocation($dir,$file) : returns file system location or a URL; same as
                   17160: filelocation except for hrefs
                   17161: 
                   17162: =item *
                   17163: 
1.1261    raeburn  17164: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   17165: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 17166: 
1.243     albertel 17167: =back
                   17168: 
1.608     albertel 17169: =head2 Usererfile file routines (/uploaded*)
                   17170: 
                   17171: =over 4
                   17172: 
                   17173: =item *
                   17174: 
                   17175: userfileupload(): main rotine for putting a file in a user or course's
                   17176:                   filespace, arguments are,
                   17177: 
1.620     albertel 17178:  formname - required - this is the name of the element in $env where the
1.608     albertel 17179:            filename, and the contents of the file to create/modifed exist
1.620     albertel 17180:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   17181:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  17182:  context - if coursedoc, store the file in the course of the active role
                   17183:              of the current user; 
                   17184:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   17185:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 17186:  subdir - required - subdirectory to put the file in under ../userfiles/
                   17187:          if undefined, it will be placed in "unknown"
                   17188: 
                   17189:  (This routine calls clean_filename() to remove any dangerous
                   17190:  characters from the filename, and then calls finuserfileupload() to
                   17191:  complete the transaction)
                   17192: 
                   17193:  returns either the url of the uploaded file (/uploaded/....) if successful
                   17194:  and /adm/notfound.html if unsuccessful
                   17195: 
                   17196: =item *
                   17197: 
                   17198: clean_filename(): routine for cleaing a filename up for storage in
                   17199:                  userfile space, argument is:
                   17200: 
                   17201:  filename - proposed filename
                   17202: 
                   17203: returns: the new clean filename
                   17204: 
                   17205: =item *
                   17206: 
1.1090    raeburn  17207: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 17208: userspace, probably shouldn't be called directly
                   17209: 
                   17210:   docuname: username or courseid of destination for the file
                   17211:   docudom: domain of user/course of destination for the file
                   17212:   formname: same as for userfileupload()
1.1090    raeburn  17213:   fname: filename (including subdirectories) for the file
                   17214:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
1.1401    raeburn  17215:           if hashref, and context is scantron, will convert csv format to standard format
1.1090    raeburn  17216:   allfiles: reference to hash used to store objects found by parser
                   17217:   codebase: reference to hash used for codebases of java objects found by parser
                   17218:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   17219:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   17220:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   17221:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   17222:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   17223:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  17224:   mimetype: reference to scalar to accommodate mime type determined
                   17225:             from File::MMagic if $parser = parse.
1.608     albertel 17226: 
                   17227:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  17228:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   17229:  was 'overwrite').
                   17230:  
1.608     albertel 17231: 
                   17232: =item *
                   17233: 
                   17234: renameuserfile(): renames an existing userfile to a new name
                   17235: 
                   17236:   Args:
                   17237:    docuname: username or courseid of destination for the file
                   17238:    docudom: domain of user/course of destination for the file
                   17239:    old: current file name (including any subdirs under userfiles)
                   17240:    new: desired file name (including any subdirs under userfiles)
                   17241: 
                   17242: =item *
                   17243: 
                   17244: mkdiruserfile(): creates a directory is a userfiles dir
                   17245: 
                   17246:   Args:
                   17247:    docuname: username or courseid of destination for the file
                   17248:    docudom: domain of user/course of destination for the file
                   17249:    dir: dir to create (including any subdirs under userfiles)
                   17250: 
                   17251: =item *
                   17252: 
                   17253: removeuserfile(): removes a file that exists in userfiles
                   17254: 
                   17255:   Args:
                   17256:    docuname: username or courseid of destination for the file
                   17257:    docudom: domain of user/course of destination for the file
                   17258:    fname: filname to delete (including any subdirs under userfiles)
                   17259: 
                   17260: =item *
                   17261: 
                   17262: removeuploadedurl(): convience function for removeuserfile()
                   17263: 
                   17264:   Args:
                   17265:    url:  a full /uploaded/... url to delete
                   17266: 
1.747     albertel 17267: =item * 
                   17268: 
                   17269: get_portfile_permissions():
                   17270:   Args:
                   17271:     domain: domain of user or course contain the portfolio files
                   17272:     user: name of user or num of course contain the portfolio files
                   17273:   Returns:
                   17274:     hashref of a dump of the proper file_permissions.db
                   17275:    
                   17276: 
                   17277: =item * 
                   17278: 
                   17279: get_access_controls():
                   17280: 
                   17281: Args:
                   17282:   current_permissions: the hash ref returned from get_portfile_permissions()
                   17283:   group: (optional) the group you want the files associated with
                   17284:   file: (optional) the file you want access info on
                   17285: 
                   17286: Returns:
1.749     raeburn  17287:     a hash (keys are file names) of hashes containing
                   17288:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   17289:         values are XML containing access control settings (see below) 
1.747     albertel 17290: 
                   17291: Internal notes:
                   17292: 
1.749     raeburn  17293:  access controls are stored in file_permissions.db as key=value pairs.
                   17294:     key -> path to file/file_name\0uniqueID:scope_end_start
                   17295:         where scope -> public,guest,course,group,domains or users.
                   17296:               end -> UNIX time for end of access (0 -> no end date)
                   17297:               start -> UNIX time for start of access
                   17298: 
                   17299:     value -> XML description of access control
                   17300:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   17301:             <start></start>
                   17302:             <end></end>
                   17303: 
                   17304:             <password></password>  for scope type = guest
                   17305: 
                   17306:             <domain></domain>     for scope type = course or group
                   17307:             <number></number>
                   17308:             <roles id="">
                   17309:              <role></role>
                   17310:              <access></access>
                   17311:              <section></section>
                   17312:              <group></group>
                   17313:             </roles>
                   17314: 
                   17315:             <dom></dom>         for scope type = domains
                   17316: 
                   17317:             <users>             for scope type = users
                   17318:              <user>
                   17319:               <uname></uname>
                   17320:               <udom></udom>
                   17321:              </user>
                   17322:             </users>
                   17323:            </scope> 
                   17324:               
                   17325:  Access data is also aggregated for each file in an additional key=value pair:
                   17326:  key -> path to file/file_name\0accesscontrol 
                   17327:  value -> reference to hash
                   17328:           hash contains key = value pairs
                   17329:           where key = uniqueID:scope_end_start
                   17330:                 value = UNIX time record was last updated
                   17331: 
                   17332:           Used to improve speed of look-ups of access controls for each file.  
                   17333:  
                   17334:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   17335: 
1.1198    raeburn  17336: =item *
                   17337: 
1.749     raeburn  17338: modify_access_controls():
                   17339: 
                   17340: Modifies access controls for a portfolio file
                   17341: Args
                   17342: 1. file name
                   17343: 2. reference to hash of required changes,
                   17344: 3. domain
                   17345: 4. username
                   17346:   where domain,username are the domain of the portfolio owner 
                   17347:   (either a user or a course) 
                   17348: 
                   17349: Returns:
                   17350: 1. result of additions or updates ('ok' or 'error', with error message). 
                   17351: 2. result of deletions ('ok' or 'error', with error message).
                   17352: 3. reference to hash of any new or updated access controls.
                   17353: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   17354:    key = integer (inbound ID)
1.1198    raeburn  17355:    value = uniqueID
                   17356: 
                   17357: =item *
                   17358: 
                   17359: get_timebased_id():
                   17360: 
                   17361: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   17362: course via the Course Editor (e.g., folders, composite pages, 
                   17363: group bulletin boards).
                   17364: 
                   17365: Args: (first three required; six others optional)
                   17366: 
                   17367: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   17368:    docssequence, or name of group
                   17369: 
                   17370: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   17371:    e.g., num, boardids
                   17372: 
                   17373: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   17374:    file will be named nohist_namespace.db
                   17375: 
                   17376: 4. cdom: domain of course; default is current course domain from %env
                   17377: 
                   17378: 5. cnum: course number; default is current course number from %env
                   17379: 
                   17380: 6. idtype: set to concat if an additional digit is to be appended to the 
                   17381:    unix timestamp to form the suffix, if the plain timestamp is already
                   17382:    in use.  Default is to not do this, but simply increment the unix 
                   17383:    timestamp by 1 until a unique key is obtained.
                   17384: 
                   17385: 7. who: holder of locking key; defaults to user:domain for user.
                   17386: 
                   17387: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   17388:    retrying); default is 3.
                   17389: 
                   17390: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   17391: 
                   17392: Returns:
                   17393: 
                   17394: 1. suffix obtained (numeric)
                   17395: 
                   17396: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   17397: 
                   17398: 3. error: contains (localized) error message if an error occurred.
                   17399: 
1.747     albertel 17400: 
1.608     albertel 17401: =back
                   17402: 
1.243     albertel 17403: =head2 HTTP Helper Routines
                   17404: 
                   17405: =over 4
                   17406: 
1.191     harris41 17407: =item *
                   17408: 
                   17409: escape() : unpack non-word characters into CGI-compatible hex codes
                   17410: 
                   17411: =item *
                   17412: 
                   17413: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   17414: 
1.243     albertel 17415: =back
                   17416: 
                   17417: =head1 PRIVATE SUBROUTINES
                   17418: 
                   17419: =head2 Underlying communication routines (Shouldn't call)
                   17420: 
                   17421: =over 4
                   17422: 
                   17423: =item *
                   17424: 
                   17425: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   17426: 
                   17427: =item *
                   17428: 
                   17429: reply() : uses subreply to send a message to remote machine, logs all failures
                   17430: 
                   17431: =item *
                   17432: 
                   17433: critical() : passes a critical message to another server; if cannot
                   17434: get through then place message in connection buffer directory and
                   17435: returns con_delayed, if incapable of saving message, returns
                   17436: con_failed
                   17437: 
                   17438: =item *
                   17439: 
                   17440: reconlonc() : tries to reconnect lonc client processes.
                   17441: 
                   17442: =back
                   17443: 
                   17444: =head2 Resource Access Logging
                   17445: 
                   17446: =over 4
                   17447: 
                   17448: =item *
                   17449: 
                   17450: flushcourselogs() : flush (save) buffer logs and access logs
                   17451: 
                   17452: =item *
                   17453: 
                   17454: courselog($what) : save message for course in hash
                   17455: 
                   17456: =item *
                   17457: 
                   17458: courseacclog($what) : save message for course using &courselog().  Perform
                   17459: special processing for specific resource types (problems, exams, quizzes, etc).
                   17460: 
1.191     harris41 17461: =item *
                   17462: 
                   17463: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   17464: as a PerlChildExitHandler
1.243     albertel 17465: 
                   17466: =back
                   17467: 
                   17468: =head2 Other
                   17469: 
                   17470: =over 4
                   17471: 
                   17472: =item *
                   17473: 
                   17474: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 17475: 
                   17476: =back
                   17477: 
                   17478: =cut
1.877     foxr     17479: 

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